Merge branch 'blender2.7' of git.blender.org:blender
[blender.git] / source / blender / editors / gpencil / gpencil_primitive.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2017, Blender Foundation
17  * This is a new part of Blender
18  * Operators for creating new Grease Pencil primitives (boxes, circles, ...)
19  */
20
21 /** \file
22  * \ingroup edgpencil
23  */
24
25 #include <stdio.h>
26 #include <string.h>
27 #include <stdlib.h>
28 #include <stddef.h>
29 #include <math.h>
30
31 #include "MEM_guardedalloc.h"
32
33 #include "BLI_blenlib.h"
34 #include "BLI_utildefines.h"
35 #include "BLI_math.h"
36 #include "BLI_rand.h"
37
38 #include "BLT_translation.h"
39
40 #include "PIL_time.h"
41
42 #include "DNA_brush_types.h"
43 #include "DNA_gpencil_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_scene_types.h"
47 #include "DNA_screen_types.h"
48 #include "DNA_space_types.h"
49 #include "DNA_view3d_types.h"
50
51 #include "BKE_brush.h"
52 #include "BKE_colortools.h"
53 #include "BKE_context.h"
54 #include "BKE_deform.h"
55 #include "BKE_global.h"
56 #include "BKE_gpencil.h"
57 #include "BKE_main.h"
58 #include "BKE_material.h"
59 #include "BKE_paint.h"
60 #include "BKE_report.h"
61
62 #include "UI_interface.h"
63 #include "UI_resources.h"
64
65 #include "WM_api.h"
66 #include "WM_types.h"
67
68 #include "RNA_access.h"
69 #include "RNA_define.h"
70 #include "RNA_enum_types.h"
71
72 #include "ED_gpencil.h"
73 #include "ED_object.h"
74 #include "ED_screen.h"
75 #include "ED_view3d.h"
76 #include "ED_space_api.h"
77
78 #include "DEG_depsgraph.h"
79 #include "DEG_depsgraph_query.h"
80
81 #include "gpencil_intern.h"
82
83 #define MIN_EDGES 2
84 #define MAX_EDGES 128
85 #define MAX_CP 128
86
87 #define IDLE 0
88 #define IN_PROGRESS 1
89 #define IN_CURVE_EDIT 2
90 #define IN_MOVE 3
91 #define IN_BRUSH_SIZE 4
92 #define IN_BRUSH_STRENGTH 5
93
94 #define SELECT_NONE 0
95 #define SELECT_START 1
96 #define SELECT_CP1 2
97 #define SELECT_CP2 3
98 #define SELECT_END 4
99
100 #define BIG_SIZE_CTL    15
101 #define MID_SIZE_CTL    10
102 #define SMALL_SIZE_CTL   8
103
104 #define MOVE_NONE 0
105 #define MOVE_ENDS 1
106 #define MOVE_CP 2
107
108   /* ************************************************ */
109   /* Core/Shared Utilities */
110
111 /* clear the session buffers (call this before AND after a paint operation) */
112 static void gp_session_validatebuffer(tGPDprimitive *p)
113 {
114         bGPdata *gpd = p->gpd;
115
116         /* clear memory of buffer (or allocate it if starting a new session) */
117         if (gpd->runtime.sbuffer) {
118                 memset(gpd->runtime.sbuffer, 0, sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX);
119         }
120         else {
121                 gpd->runtime.sbuffer = MEM_callocN(sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX, "gp_session_strokebuffer");
122         }
123
124         /* reset indices */
125         gpd->runtime.sbuffer_size = 0;
126
127         /* reset flags */
128         gpd->runtime.sbuffer_sflag = 0;
129         gpd->runtime.sbuffer_sflag |= GP_STROKE_3DSPACE;
130
131         if (ELEM(p->type, GP_STROKE_BOX, GP_STROKE_CIRCLE))
132                 gpd->runtime.sbuffer_sflag |= GP_STROKE_CYCLIC;
133 }
134
135 static void gp_init_colors(tGPDprimitive *p)
136 {
137         bGPdata *gpd = p->gpd;
138         Brush *brush = p->brush;
139
140         Material *ma = NULL;
141         MaterialGPencilStyle *gp_style = NULL;
142
143         /* use brush material */
144         ma = BKE_gpencil_get_material_from_brush(brush);
145
146         /* if no brush defaults, get material and color info */
147         if ((ma == NULL) || (ma->gp_style == NULL)) {
148                 BKE_gpencil_material_ensure(p->bmain, p->ob);
149
150                 /* assign always the first material to the brush */
151                 p->mat = give_current_material(p->ob, 1);
152                 brush->gpencil_settings->material = p->mat;
153         }
154         else {
155                 p->mat = ma;
156         }
157
158         /* check if the material is already on object material slots and add it if missing */
159         if (BKE_gpencil_get_material_index(p->ob, p->mat) == 0) {
160                 BKE_object_material_slot_add(p->bmain, p->ob);
161                 assign_material(p->bmain, p->ob, ma, p->ob->totcol, BKE_MAT_ASSIGN_USERPREF);
162         }
163
164         /* assign color information to temp data */
165         gp_style = p->mat->gp_style;
166         if (gp_style) {
167
168                 /* set colors */
169                 if (gp_style->flag & GP_STYLE_STROKE_SHOW) {
170                         copy_v4_v4(gpd->runtime.scolor, gp_style->stroke_rgba);
171                 }
172                 else {
173                         /* if no stroke, use fill */
174                         copy_v4_v4(gpd->runtime.scolor, gp_style->fill_rgba);
175                 }
176
177                 copy_v4_v4(gpd->runtime.sfill, gp_style->fill_rgba);
178                 /* add some alpha to make easy the filling without hide strokes */
179                 if (gpd->runtime.sfill[3] > 0.8f) {
180                         gpd->runtime.sfill[3] = 0.8f;
181                 }
182
183                 gpd->runtime.mode = (short)gp_style->mode;
184                 gpd->runtime.bstroke_style = gp_style->stroke_style;
185                 gpd->runtime.bfill_style = gp_style->fill_style;
186         }
187 }
188
189 /* Helper to square a primitive */
190 static void gpencil_primitive_to_square(tGPDprimitive *tgpi, const float x, const float y)
191 {
192         float w = fabsf(x);
193         float h = fabsf(y);
194         if ((x > 0 && y > 0) || (x < 0 && y < 0)) {
195                 if (w > h)
196                         tgpi->end[1] = tgpi->origin[1] + x;
197                 else
198                         tgpi->end[0] = tgpi->origin[0] + y;
199         }
200         else {
201                 if (w > h)
202                         tgpi->end[1] = tgpi->origin[1] - x;
203                 else
204                         tgpi->end[0] = tgpi->origin[0] - y;
205         }
206 }
207
208 /* Helper to rotate point around origin */
209 static void gp_rotate_v2_v2v2fl(float v[2], const float p[2], const float origin[2], const float angle)
210 {
211         float pt[2];
212         float r[2];
213         sub_v2_v2v2(pt, p, origin);
214         rotate_v2_v2fl(r, pt, angle);
215         add_v2_v2v2(v, r, origin);
216 }
217
218 /* Helper to rotate line around line centre */
219 static void gp_primitive_rotate_line(float va[2], float vb[2], const float a[2], const float b[2], const float angle)
220 {
221         float midpoint[2];
222         mid_v2_v2v2(midpoint, a, b);
223         gp_rotate_v2_v2v2fl(va, a, midpoint, angle);
224         gp_rotate_v2_v2v2fl(vb, b, midpoint, angle);
225 }
226
227 /* Helper to update cps */
228 static void gp_primitive_update_cps(tGPDprimitive *tgpi)
229 {
230         if (!tgpi->curve) {
231                 mid_v2_v2v2(tgpi->midpoint, tgpi->start, tgpi->end);
232                 copy_v2_v2(tgpi->cp1, tgpi->midpoint);
233                 copy_v2_v2(tgpi->cp2, tgpi->cp1);
234         }
235         else if (tgpi->type == GP_STROKE_CURVE) {
236                 mid_v2_v2v2(tgpi->midpoint, tgpi->start, tgpi->end);
237                 copy_v2_v2(tgpi->cp1, tgpi->midpoint);
238                 copy_v2_v2(tgpi->cp2, tgpi->cp1);
239         }
240         else if (tgpi->type == GP_STROKE_ARC) {
241                 if (tgpi->flip) {
242                         gp_primitive_rotate_line(tgpi->cp1, tgpi->cp2, tgpi->start, tgpi->end, M_PI_2);
243                 }
244                 else {
245                         gp_primitive_rotate_line(tgpi->cp1, tgpi->cp2, tgpi->end, tgpi->start, M_PI_2);
246                 }
247         }
248 }
249
250 /* Helper to reflect point */
251 static void UNUSED_FUNCTION(gp_reflect_point_v2_v2v2v2)(
252         float va[2], const float p[2], const float a[2], const float b[2])
253 {
254         float point[2];
255         closest_to_line_v2(point, p, a, b);
256         va[0] = point[0] - (p[0] - point[0]);
257         va[1] = point[1] - (p[1] - point[1]);
258 }
259
260   /* Poll callback for primitive operators */
261 static bool gpencil_primitive_add_poll(bContext *C)
262 {
263         /* only 3D view */
264         ScrArea *sa = CTX_wm_area(C);
265         if (sa && sa->spacetype != SPACE_VIEW3D) {
266                 return 0;
267         }
268
269         /* need data to create primitive */
270         bGPdata *gpd = CTX_data_gpencil_data(C);
271         if (gpd == NULL) {
272                 return 0;
273         }
274
275         /* only in edit and paint modes
276          * - paint as it's the "drawing/creation mode"
277          * - edit as this is more of an atomic editing operation
278          *   (similar to copy/paste), and also for consistency
279          */
280         if ((gpd->flag & (GP_DATA_STROKE_PAINTMODE | GP_DATA_STROKE_EDITMODE)) == 0) {
281                 CTX_wm_operator_poll_msg_set(C, "Primitives can only be added in Draw or Edit modes");
282                 return 0;
283         }
284
285         /* don't allow operator to function if the active layer is locked/hidden
286          * (BUT, if there isn't an active layer, we are free to add new layer when the time comes)
287          */
288         bGPDlayer *gpl = BKE_gpencil_layer_getactive(gpd);
289         if ((gpl) && (gpl->flag & (GP_LAYER_LOCKED | GP_LAYER_HIDE))) {
290                 CTX_wm_operator_poll_msg_set(C, "Primitives cannot be added as active layer is locked or hidden");
291                 return 0;
292         }
293
294         return 1;
295 }
296
297 /* Allocate memory to stroke, adds MAX_EDGES on every call */
298 static void gpencil_primitive_allocate_memory(tGPDprimitive *tgpi)
299 {
300         tgpi->point_count += (tgpi->type == GP_STROKE_BOX) ? (MAX_EDGES * 4 + 1) : (MAX_EDGES + 1);
301         bGPDstroke *gpsf = tgpi->gpf->strokes.first;
302         gpsf->points = MEM_reallocN(gpsf->points, sizeof(bGPDspoint) * tgpi->point_count);
303         if (gpsf->dvert != NULL)
304                 gpsf->dvert = MEM_reallocN(gpsf->dvert, sizeof(MDeformVert) * tgpi->point_count);
305         tgpi->points = MEM_reallocN(tgpi->points, sizeof(tGPspoint) * tgpi->point_count);
306 }
307
308 /* ****************** Primitive Interactive *********************** */
309
310 /* Helper: Create internal strokes primitives data */
311 static void gp_primitive_set_initdata(bContext *C, tGPDprimitive *tgpi)
312 {
313         ToolSettings *ts = CTX_data_tool_settings(C);
314         Depsgraph *depsgraph = CTX_data_depsgraph(C);
315         int cfra_eval = (int)DEG_get_ctime(depsgraph);
316
317         bGPDlayer *gpl = CTX_data_active_gpencil_layer(C);
318
319         /* if brush doesn't exist, create a new one */
320         Paint *paint = &ts->gp_paint->paint;
321         /* if not exist, create a new one */
322         if (paint->brush == NULL) {
323                 /* create new brushes */
324                 BKE_brush_gpencil_presets(C);
325         }
326         tgpi->brush = paint->brush;
327
328         /* if layer doesn't exist, create a new one */
329         if (gpl == NULL) {
330                 gpl = BKE_gpencil_layer_addnew(tgpi->gpd, DATA_("Primitives"), true);
331         }
332         tgpi->gpl = gpl;
333
334         /* create a new temporary frame */
335         tgpi->gpf = MEM_callocN(sizeof(bGPDframe), "Temp bGPDframe");
336         tgpi->gpf->framenum = tgpi->cframe = cfra_eval;
337
338         /* create new temp stroke */
339         bGPDstroke *gps = MEM_callocN(sizeof(bGPDstroke), "Temp bGPDstroke");
340         gps->thickness = 2.0f;
341         gps->inittime = 0.0f;
342
343         /* enable recalculation flag by default */
344         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
345         gps->flag &= ~GP_STROKE_SELECT;
346         /* the polygon must be closed, so enabled cyclic */
347         if (ELEM(tgpi->type, GP_STROKE_BOX, GP_STROKE_CIRCLE)) {
348                 gps->flag |= GP_STROKE_CYCLIC;
349         }
350
351         gps->flag |= GP_STROKE_3DSPACE;
352
353         gps->mat_nr = BKE_gpencil_get_material_index(tgpi->ob, tgpi->mat) - 1;
354
355         /* allocate memory for storage points, but keep empty */
356         gps->totpoints = 0;
357         gps->points = MEM_callocN(sizeof(bGPDspoint), "gp_stroke_points");
358         /* initialize triangle memory to dummy data */
359         gps->tot_triangles = 0;
360         gps->triangles = NULL;
361         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
362
363         /* add to strokes */
364         BLI_addtail(&tgpi->gpf->strokes, gps);
365
366         /* allocate memory for storage points */
367         gpencil_primitive_allocate_memory(tgpi);
368
369         /* Random generator, only init once. */
370         uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX);
371         tgpi->rng = BLI_rng_new(rng_seed);
372 }
373
374 /* add new segment to curve */
375 static void gpencil_primitive_add_segment(tGPDprimitive *tgpi)
376 {
377         if (tgpi->tot_stored_edges > 0) {
378                 tgpi->tot_stored_edges += (tgpi->tot_edges - 1);
379         }
380         else {
381                 tgpi->tot_stored_edges += tgpi->tot_edges;
382         }
383         gpencil_primitive_allocate_memory(tgpi);
384 }
385
386 /* Helper: set control point */
387 static void gp_primitive_set_cp(tGPDprimitive *tgpi, float p[2], float color[4], int size)
388 {
389         if (tgpi->flag == IN_PROGRESS) {
390                 return;
391         }
392
393         bGPDcontrolpoint *cp_points = tgpi->gpd->runtime.cp_points;
394
395         if (tgpi->gpd->runtime.tot_cp_points < MAX_CP) {
396                 CLAMP(size, 5, 20);
397                 bGPDcontrolpoint *cp = &cp_points[tgpi->gpd->runtime.tot_cp_points];
398                 copy_v2_v2(&cp->x, p);
399                 copy_v4_v4(cp->color, color);
400                 color[3] = 0.8f;
401                 cp->size = size;
402                 tgpi->gpd->runtime.tot_cp_points += 1;
403         }
404 }
405
406 /* Helper: Draw status message while the user is running the operator */
407 static void gpencil_primitive_status_indicators(bContext *C, tGPDprimitive *tgpi)
408 {
409         Scene *scene = tgpi->scene;
410         char status_str[UI_MAX_DRAW_STR];
411         char msg_str[UI_MAX_DRAW_STR];
412
413         if (tgpi->type == GP_STROKE_LINE) {
414                 BLI_strncpy(
415                         msg_str,
416                         IFACE_("Line: ESC to cancel, LMB set origin, Enter/MMB to confirm, WHEEL/+- to adjust subdivision number, Shift to align, Alt to center, E: extrude"),
417                         UI_MAX_DRAW_STR);
418         }
419         else if (tgpi->type == GP_STROKE_BOX) {
420                 BLI_strncpy(
421                         msg_str,
422                         IFACE_("Rectangle: ESC to cancel, LMB set origin, Enter/MMB to confirm, WHEEL/+- to adjust subdivision number, Shift to square, Alt to center"),
423                         UI_MAX_DRAW_STR);
424         }
425         else if (tgpi->type == GP_STROKE_CIRCLE) {
426                 BLI_strncpy(
427                         msg_str,
428                         IFACE_("Circle: ESC to cancel, Enter/MMB to confirm, WHEEL/+- to adjust edge number, Shift to square, Alt to center"),
429                         UI_MAX_DRAW_STR);
430         }
431         else if (tgpi->type == GP_STROKE_ARC) {
432                 BLI_strncpy(msg_str,
433                         IFACE_("Arc: ESC to cancel, Enter/MMB to confirm, WHEEL/+- to adjust edge number, Shift to square, Alt to center, M: Flip, E: extrude"),
434                         UI_MAX_DRAW_STR);
435         }
436         else if (tgpi->type == GP_STROKE_CURVE) {
437                 BLI_strncpy(
438                         msg_str,
439                         IFACE_("Curve: ESC to cancel, Enter/MMB to confirm, WHEEL/+- to adjust edge number, Shift to square, Alt to center, E: extrude"),
440                         UI_MAX_DRAW_STR);
441         }
442
443         if (ELEM(tgpi->type, GP_STROKE_CIRCLE, GP_STROKE_ARC, GP_STROKE_LINE, GP_STROKE_BOX)) {
444                 if (hasNumInput(&tgpi->num)) {
445                         char str_offs[NUM_STR_REP_LEN];
446
447                         outputNumInput(&tgpi->num, str_offs, &scene->unit);
448                         BLI_snprintf(status_str, sizeof(status_str), "%s: %s", msg_str, str_offs);
449                 }
450                 else {
451                         if (tgpi->flag == IN_PROGRESS) {
452                                 BLI_snprintf(
453                                         status_str, sizeof(status_str), "%s: %d (%d, %d) (%d, %d)", msg_str, tgpi->tot_edges,
454                                         (int)tgpi->start[0], (int)tgpi->start[1], (int)tgpi->end[0], (int)tgpi->end[1]);
455                         }
456                         else {
457                                 BLI_snprintf(
458                                         status_str, sizeof(status_str), "%s: %d (%d, %d)", msg_str, tgpi->tot_edges,
459                                         (int)tgpi->end[0], (int)tgpi->end[1]);
460                         }
461                 }
462         }
463         else {
464                 if (tgpi->flag == IN_PROGRESS) {
465                         BLI_snprintf(
466                                 status_str, sizeof(status_str), "%s: %d (%d, %d) (%d, %d)", msg_str, tgpi->tot_edges,
467                                 (int)tgpi->start[0], (int)tgpi->start[1], (int)tgpi->end[0], (int)tgpi->end[1]);
468                 }
469                 else {
470                         BLI_snprintf(
471                                 status_str, sizeof(status_str), "%s: (%d, %d)", msg_str,
472                                 (int)tgpi->end[0], (int)tgpi->end[1]);
473                 }
474         }
475         ED_workspace_status_text(C, status_str);
476 }
477
478 /* create a rectangle */
479 static void gp_primitive_rectangle(tGPDprimitive *tgpi, tGPspoint *points2D)
480 {
481         float coords[5][2];
482
483         coords[0][0] = tgpi->start[0];
484         coords[0][1] = tgpi->start[1];
485         coords[1][0] = tgpi->end[0];
486         coords[1][1] = tgpi->start[1];
487         coords[2][0] = tgpi->end[0];
488         coords[2][1] = tgpi->end[1];
489         coords[3][0] = tgpi->start[0];
490         coords[3][1] = tgpi->end[1];
491         coords[4][0] = tgpi->start[0];
492         coords[4][1] = tgpi->start[1];
493
494         const float step = 1.0f / (float)(tgpi->tot_edges);
495         int i = tgpi->tot_stored_edges;
496
497         for (int j = 0; j < 4; j++) {
498                 float a = 0.0f;
499                 for (int k = 0; k < tgpi->tot_edges; k++) {
500                         tGPspoint *p2d = &points2D[i];
501                         interp_v2_v2v2(&p2d->x, coords[j], coords[j + 1], a);
502                         a += step;
503                         i++;
504                 }
505         }
506
507         mid_v2_v2v2(tgpi->midpoint, tgpi->start, tgpi->end);
508         float color[4];
509         UI_GetThemeColor4fv(TH_GIZMO_PRIMARY, color);
510         gp_primitive_set_cp(tgpi, tgpi->end, color, BIG_SIZE_CTL);
511         if (tgpi->tot_stored_edges) {
512                 UI_GetThemeColor4fv(TH_REDALERT, color);
513                 gp_primitive_set_cp(tgpi, tgpi->start, color, SMALL_SIZE_CTL);
514         }
515         else {
516                 gp_primitive_set_cp(tgpi, tgpi->start, color, BIG_SIZE_CTL);
517         }
518         UI_GetThemeColor4fv(TH_REDALERT, color);
519         gp_primitive_set_cp(tgpi, tgpi->midpoint, color, SMALL_SIZE_CTL);
520 }
521
522 /* create a line */
523 static void gp_primitive_line(tGPDprimitive *tgpi, tGPspoint *points2D)
524 {
525         const int totpoints = (tgpi->tot_edges + tgpi->tot_stored_edges);
526         const float step = 1.0f / (float)(tgpi->tot_edges - 1);
527         float a = tgpi->tot_stored_edges ? step : 0.0f;
528
529         for (int i = tgpi->tot_stored_edges; i < totpoints; i++) {
530                 tGPspoint *p2d = &points2D[i];
531                 interp_v2_v2v2(&p2d->x, tgpi->start, tgpi->end, a);
532                 a += step;
533         }
534
535         float color[4];
536         UI_GetThemeColor4fv(TH_GIZMO_PRIMARY, color);
537         gp_primitive_set_cp(tgpi, tgpi->end, color, BIG_SIZE_CTL);
538         if (tgpi->tot_stored_edges) {
539                 UI_GetThemeColor4fv(TH_REDALERT, color);
540                 gp_primitive_set_cp(tgpi, tgpi->start, color, SMALL_SIZE_CTL);
541         }
542         else {
543                 gp_primitive_set_cp(tgpi, tgpi->start, color, BIG_SIZE_CTL);
544         }
545 }
546
547 /* create an arc */
548 static void gp_primitive_arc(tGPDprimitive *tgpi, tGPspoint *points2D)
549 {
550         const int totpoints = (tgpi->tot_edges + tgpi->tot_stored_edges);
551         const float step = M_PI_2 / (float)(tgpi->tot_edges - 1);
552         float start[2];
553         float end[2];
554         float cp1[2];
555         float corner[2];
556         float midpoint[2];
557         float a = tgpi->tot_stored_edges ? step : 0.0f;
558
559         mid_v2_v2v2(tgpi->midpoint, tgpi->start, tgpi->end);
560         copy_v2_v2(start, tgpi->start);
561         copy_v2_v2(end, tgpi->end);
562         copy_v2_v2(cp1, tgpi->cp1);
563         copy_v2_v2(midpoint, tgpi->midpoint);
564
565         corner[0] = midpoint[0] - (cp1[0] - midpoint[0]);
566         corner[1] = midpoint[1] - (cp1[1] - midpoint[1]);
567
568         for (int i = tgpi->tot_stored_edges; i < totpoints; i++) {
569                 tGPspoint *p2d = &points2D[i];
570                 p2d->x = corner[0] + (end[0] - corner[0]) * sinf(a) + (start[0] - corner[0]) * cosf(a);
571                 p2d->y = corner[1] + (end[1] - corner[1]) * sinf(a) + (start[1] - corner[1]) * cosf(a);
572                 a += step;
573         }
574         float color[4];
575         UI_GetThemeColor4fv(TH_GIZMO_PRIMARY, color);
576         gp_primitive_set_cp(tgpi, tgpi->end, color, BIG_SIZE_CTL);
577         if (tgpi->tot_stored_edges) {
578                 UI_GetThemeColor4fv(TH_REDALERT, color);
579                 gp_primitive_set_cp(tgpi, tgpi->start, color, SMALL_SIZE_CTL);
580         }
581         else {
582                 gp_primitive_set_cp(tgpi, tgpi->start, color, BIG_SIZE_CTL);
583         }
584         UI_GetThemeColor4fv(TH_GIZMO_SECONDARY, color);
585         gp_primitive_set_cp(tgpi, tgpi->cp1, color, BIG_SIZE_CTL * 0.9f);
586 }
587
588 /* create a bezier */
589 static void gp_primitive_bezier(tGPDprimitive *tgpi, tGPspoint *points2D)
590 {
591         const int totpoints = (tgpi->tot_edges + tgpi->tot_stored_edges);
592         const float step = 1.0f / (float)(tgpi->tot_edges - 1);
593         float bcp1[2];
594         float bcp2[2];
595         float bcp3[2];
596         float bcp4[2];
597         float a = tgpi->tot_stored_edges ? step : 0.0f;
598
599         copy_v2_v2(bcp1, tgpi->start);
600         copy_v2_v2(bcp2, tgpi->cp1);
601         copy_v2_v2(bcp3, tgpi->cp2);
602         copy_v2_v2(bcp4, tgpi->end);
603
604         for (int i = tgpi->tot_stored_edges; i < totpoints; i++) {
605                 tGPspoint *p2d = &points2D[i];
606                 interp_v2_v2v2v2v2_cubic(&p2d->x, bcp1, bcp2, bcp3, bcp4, a);
607                 a += step;
608         }
609         float color[4];
610         UI_GetThemeColor4fv(TH_GIZMO_PRIMARY, color);
611         gp_primitive_set_cp(tgpi, tgpi->end, color, BIG_SIZE_CTL);
612         if (tgpi->tot_stored_edges) {
613                 UI_GetThemeColor4fv(TH_REDALERT, color);
614                 gp_primitive_set_cp(tgpi, tgpi->start, color, SMALL_SIZE_CTL);
615         }
616         else {
617                 gp_primitive_set_cp(tgpi, tgpi->start, color, BIG_SIZE_CTL);
618         }
619         UI_GetThemeColor4fv(TH_GIZMO_SECONDARY, color);
620         gp_primitive_set_cp(tgpi, tgpi->cp1, color, BIG_SIZE_CTL * 0.9f);
621         gp_primitive_set_cp(tgpi, tgpi->cp2, color, BIG_SIZE_CTL * 0.9f);
622 }
623
624 /* create a circle */
625 static void gp_primitive_circle(tGPDprimitive *tgpi, tGPspoint *points2D)
626 {
627         const int totpoints = (tgpi->tot_edges + tgpi->tot_stored_edges);
628         const float step = (2.0f * M_PI) / (float)(tgpi->tot_edges);
629         float center[2];
630         float radius[2];
631         float a = 0.0f;
632
633         center[0] = tgpi->start[0] + ((tgpi->end[0] - tgpi->start[0]) / 2.0f);
634         center[1] = tgpi->start[1] + ((tgpi->end[1] - tgpi->start[1]) / 2.0f);
635         radius[0] = fabsf(((tgpi->end[0] - tgpi->start[0]) / 2.0f));
636         radius[1] = fabsf(((tgpi->end[1] - tgpi->start[1]) / 2.0f));
637
638         for (int i = tgpi->tot_stored_edges; i < totpoints; i++) {
639                 tGPspoint *p2d = &points2D[i];
640                 p2d->x = (center[0] + cosf(a) * radius[0]);
641                 p2d->y = (center[1] + sinf(a) * radius[1]);
642                 a += step;
643         }
644         float color[4];
645         UI_GetThemeColor4fv(TH_GIZMO_PRIMARY, color);
646         gp_primitive_set_cp(tgpi, tgpi->end, color, BIG_SIZE_CTL);
647         gp_primitive_set_cp(tgpi, tgpi->start, color, BIG_SIZE_CTL);
648         UI_GetThemeColor4fv(TH_REDALERT, color);
649         gp_primitive_set_cp(tgpi, center, color, SMALL_SIZE_CTL);
650 }
651
652 /* Helper: Update shape of the stroke */
653 static void gp_primitive_update_strokes(bContext *C, tGPDprimitive *tgpi)
654 {
655         ToolSettings *ts = tgpi->scene->toolsettings;
656         bGPdata *gpd = tgpi->gpd;
657         Brush *brush = tgpi->brush;
658         bGPDstroke *gps = tgpi->gpf->strokes.first;
659         GP_Sculpt_Settings *gset = &ts->gp_sculpt;
660         int depth_margin = (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 4 : 0;
661         const char *align_flag = &ts->gpencil_v3d_align;
662         bool is_depth = (bool)(*align_flag & (GP_PROJECT_DEPTH_VIEW | GP_PROJECT_DEPTH_STROKE));
663         const bool is_camera = (bool)(ts->gp_sculpt.lock_axis == 0) &&
664                 (tgpi->rv3d->persp == RV3D_CAMOB) && (!is_depth);
665
666         if (tgpi->type == GP_STROKE_BOX)
667                 gps->totpoints = (tgpi->tot_edges * 4 + tgpi->tot_stored_edges);
668         else
669                 gps->totpoints = (tgpi->tot_edges + tgpi->tot_stored_edges);
670
671         if (tgpi->tot_stored_edges)
672                 gps->totpoints--;
673
674         tgpi->gpd->runtime.tot_cp_points = 0;
675
676         /* compute screen-space coordinates for points */
677         tGPspoint *points2D = tgpi->points;
678
679         if (tgpi->tot_edges > 1) {
680                 switch (tgpi->type) {
681                         case GP_STROKE_BOX:
682                                 gp_primitive_rectangle(tgpi, points2D);
683                                 break;
684                         case GP_STROKE_LINE:
685                                 gp_primitive_line(tgpi, points2D);
686                                 break;
687                         case GP_STROKE_CIRCLE:
688                                 gp_primitive_circle(tgpi, points2D);
689                                 break;
690                         case GP_STROKE_ARC:
691                                 gp_primitive_arc(tgpi, points2D);
692                                 break;
693                         case GP_STROKE_CURVE:
694                                 gp_primitive_bezier(tgpi, points2D);
695                         default:
696                                 break;
697                 }
698         }
699
700         /* convert screen-coordinates to 3D coordinates */
701         gp_session_validatebuffer(tgpi);
702         gp_init_colors(tgpi);
703         if (gset->flag & GP_SCULPT_SETT_FLAG_PRIMITIVE_CURVE) {
704                 curvemapping_initialize(ts->gp_sculpt.cur_primitive);
705         }
706         if (tgpi->brush->gpencil_settings->flag & GP_BRUSH_USE_JITTER_PRESSURE) {
707                 curvemapping_initialize(tgpi->brush->gpencil_settings->curve_jitter);
708         }
709         if (tgpi->brush->gpencil_settings->flag & GP_BRUSH_USE_STENGTH_PRESSURE) {
710                 curvemapping_initialize(tgpi->brush->gpencil_settings->curve_strength);
711         }
712
713         /* get an array of depths, far depths are blended */
714         float *depth_arr = NULL;
715         if (is_depth) {
716                 int i;
717                 int mval_i[2], mval_prev[2] = { 0 };
718                 bool interp_depth = false;
719                 bool found_depth = false;
720
721                 /* need to restore the original projection settings before packing up */
722                 view3d_region_operator_needs_opengl(tgpi->win, tgpi->ar);
723                 ED_view3d_autodist_init(
724                         tgpi->depsgraph, tgpi->ar, tgpi->v3d, (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
725
726                 depth_arr = MEM_mallocN(sizeof(float) * gps->totpoints, "depth_points");
727                 tGPspoint *ptc = &points2D[0];
728                 for (i = 0; i < gps->totpoints; i++, ptc++) {
729                         round_v2i_v2fl(mval_i, &ptc->x);
730                         if ((ED_view3d_autodist_depth(
731                                      tgpi->ar, mval_i, depth_margin, depth_arr + i) == 0) &&
732                             (i && (ED_view3d_autodist_depth_seg(
733                                            tgpi->ar, mval_i, mval_prev, depth_margin + 1, depth_arr + i) == 0)))
734                         {
735                                 interp_depth = true;
736                         }
737                         else {
738                                 found_depth = true;
739                         }
740                         copy_v2_v2_int(mval_prev, mval_i);
741                 }
742
743                 if (!found_depth) {
744                         for (i = 0; i < gps->totpoints; i++) {
745                                 depth_arr[i] = 0.9999f;
746                         }
747                 }
748                 else {
749                         /* if all depth are too high disable */
750                         bool valid_depth = false;
751                         for (i = 0; i < gps->totpoints; i++) {
752                                 if (depth_arr[i] < 0.9999f) {
753                                         valid_depth = true;
754                                         break;
755                                 }
756                         }
757                         if (!valid_depth) {
758                                 MEM_SAFE_FREE(depth_arr);
759                                 is_depth = false;
760                         }
761                         else {
762                                 if ((ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE_ENDPOINTS) ||
763                                     (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE_FIRST))
764                                 {
765                                         int first_valid = 0;
766                                         int last_valid = 0;
767
768                                         /* find first valid contact point */
769                                         for (i = 0; i < gps->totpoints; i++) {
770                                                 if (depth_arr[i] != FLT_MAX)
771                                                         break;
772                                         }
773                                         first_valid = i;
774
775                                         /* find last valid contact point */
776                                         if (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE_FIRST) {
777                                                 last_valid = first_valid;
778                                         }
779                                         else {
780                                                 for (i = gps->totpoints - 1; i >= 0; i--) {
781                                                         if (depth_arr[i] != FLT_MAX)
782                                                                 break;
783                                                 }
784                                                 last_valid = i;
785                                         }
786
787                                         /* invalidate any other point, to interpolate between
788                                          * first and last contact in an imaginary line between them */
789                                         for (i = 0; i < gps->totpoints; i++) {
790                                                 if ((i != first_valid) && (i != last_valid)) {
791                                                         depth_arr[i] = FLT_MAX;
792                                                 }
793                                         }
794                                         interp_depth = true;
795                                 }
796
797                                 if (interp_depth) {
798                                         interp_sparse_array(depth_arr, gps->totpoints, FLT_MAX);
799                                 }
800                         }
801                 }
802         }
803
804         /* load stroke points and sbuffer */
805         for (int i = 0; i < gps->totpoints; i++) {
806                 bGPDspoint *pt = &gps->points[i];
807                 tGPspoint *p2d = &points2D[i];
808
809                 /* set rnd value for reuse */
810                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) && (p2d->rnd_dirty != true)) {
811                         p2d->rnd[0] = BLI_rng_get_float(tgpi->rng);
812                         p2d->rnd[1] = BLI_rng_get_float(tgpi->rng);
813                         p2d->rnd[2] = BLI_rng_get_float(tgpi->rng);
814                         p2d->rnd_dirty = true;
815                 }
816
817                 /* Copy points to buffer */
818                 tGPspoint *tpt = ((tGPspoint *)(gpd->runtime.sbuffer) + gpd->runtime.sbuffer_size);
819
820                 /* Store original points */
821                 float tmp_xyp[2];
822                 copy_v2_v2(tmp_xyp, &p2d->x);
823
824                 /* calc pressure */
825                 float curve_pressure = 1.0;
826                 float pressure = 1.0;
827                 float strength = brush->gpencil_settings->draw_strength;
828
829                 /* normalize value to evaluate curve */
830                 if (gset->flag & GP_SCULPT_SETT_FLAG_PRIMITIVE_CURVE) {
831                         float value = (float)i / (gps->totpoints - 1);
832                         curve_pressure = curvemapping_evaluateF(gset->cur_primitive, 0, value);
833                         pressure = curve_pressure;
834                 }
835
836                 /* apply jitter to position */
837                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
838                     (brush->gpencil_settings->draw_jitter > 0.0f))
839                 {
840                         float jitter;
841
842                         if (brush->gpencil_settings->flag & GP_BRUSH_USE_JITTER_PRESSURE) {
843                                 jitter = curvemapping_evaluateF(brush->gpencil_settings->curve_jitter, 0, curve_pressure);
844                                 jitter *= brush->gpencil_settings->draw_sensitivity;
845                         }
846                         else {
847                                 jitter = brush->gpencil_settings->draw_jitter;
848                         }
849
850                         /* exponential value */
851                         const float exfactor = SQUARE(brush->gpencil_settings->draw_jitter + 2.0f);
852                         const float fac = p2d->rnd[0] * exfactor * jitter;
853
854                         /* vector */
855                         float mvec[2], svec[2];;
856                         if (i > 0) {
857                                 mvec[0] = (p2d->x - (p2d - 1)->x);
858                                 mvec[1] = (p2d->y - (p2d - 1)->y);
859                                 normalize_v2(mvec);
860                         }
861                         else {
862                                 zero_v2(mvec);
863                         }
864                         svec[0] = -mvec[1];
865                         svec[1] = mvec[0];
866
867                         if (p2d->rnd[1] > 0.5f) {
868                                 mul_v2_fl(svec, -fac);
869                         }
870                         else {
871                                 mul_v2_fl(svec, fac);
872                         }
873                         add_v2_v2(&p2d->x, svec);
874                 }
875
876                 /* apply randomness to pressure */
877                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
878                     (brush->gpencil_settings->draw_random_press > 0.0f))
879                 {
880                         if (p2d->rnd[0] > 0.5f) {
881                                 pressure -= brush->gpencil_settings->draw_random_press * p2d->rnd[1];
882                         }
883                         else {
884                                 pressure += brush->gpencil_settings->draw_random_press * p2d->rnd[2];
885                         }
886                 }
887
888                 /* color strength */
889                 if (brush->gpencil_settings->flag & GP_BRUSH_USE_STENGTH_PRESSURE) {
890                         float curvef = curvemapping_evaluateF(brush->gpencil_settings->curve_strength, 0, curve_pressure);
891                         strength *= curvef * brush->gpencil_settings->draw_sensitivity;
892                         strength *= brush->gpencil_settings->draw_strength;
893                 }
894
895                 CLAMP(strength, GPENCIL_STRENGTH_MIN, 1.0f);
896
897                 /* apply randomness to color strength */
898                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
899                     (brush->gpencil_settings->draw_random_strength > 0.0f))
900                 {
901                         if (p2d->rnd[2] > 0.5f) {
902                                 strength -= strength * brush->gpencil_settings->draw_random_strength * p2d->rnd[0];
903                         }
904                         else {
905                                 strength += strength * brush->gpencil_settings->draw_random_strength * p2d->rnd[1];
906                         }
907                         CLAMP(strength, GPENCIL_STRENGTH_MIN, 1.0f);
908                 }
909
910                 copy_v2_v2(&tpt->x, &p2d->x);
911
912                 CLAMP_MIN(pressure, 0.1f);
913
914                 tpt->pressure = pressure;
915                 tpt->strength = strength;
916                 tpt->time = p2d->time;
917
918                 /* point uv */
919                 if (gpd->runtime.sbuffer_size > 0) {
920                         MaterialGPencilStyle *gp_style = tgpi->mat->gp_style;
921                         const float pixsize = gp_style->texture_pixsize / 1000000.0f;
922                         tGPspoint *tptb = (tGPspoint *)gpd->runtime.sbuffer + gpd->runtime.sbuffer_size - 1;
923                         bGPDspoint spt, spt2;
924
925                         /* get origin to reproject point */
926                         float origin[3];
927                         ED_gp_get_drawing_reference(tgpi->scene, tgpi->ob, tgpi->gpl,
928                                 ts->gpencil_v3d_align, origin);
929                         /* reproject current */
930                         ED_gpencil_tpoint_to_point(tgpi->ar, origin, tpt, &spt);
931                         ED_gp_project_point_to_plane(tgpi->ob, tgpi->rv3d, origin, tgpi->lock_axis - 1, &spt);
932
933                         /* reproject previous */
934                         ED_gpencil_tpoint_to_point(tgpi->ar, origin, tptb, &spt2);
935                         ED_gp_project_point_to_plane(tgpi->ob, tgpi->rv3d, origin, tgpi->lock_axis - 1, &spt2);
936                         tgpi->totpixlen += len_v3v3(&spt.x, &spt2.x) / pixsize;
937                         tpt->uv_fac = tgpi->totpixlen;
938                         if ((gp_style) && (gp_style->sima)) {
939                                 tpt->uv_fac /= gp_style->sima->gen_x;
940                         }
941                 }
942                 else {
943                         tgpi->totpixlen = 0.0f;
944                         tpt->uv_fac = 0.0f;
945                 }
946
947                 tpt->uv_rot = p2d->uv_rot;
948
949                 gpd->runtime.sbuffer_size++;
950
951                 /* add small offset to keep stroke over the surface */
952                 if ((depth_arr) && (gpd->zdepth_offset > 0.0f)) {
953                         depth_arr[i] *= (1.0f - gpd->zdepth_offset);
954                 }
955
956                 /* convert screen-coordinates to 3D coordinates */
957                 gp_stroke_convertcoords_tpoint(
958                         tgpi->scene, tgpi->ar, tgpi->ob, tgpi->gpl,
959                         p2d, depth_arr ? depth_arr + i : NULL,
960                         &pt->x);
961
962                 pt->pressure = pressure;
963                 pt->strength = strength;
964                 pt->time = 0.0f;
965                 pt->flag = 0;
966                 pt->uv_fac = tpt->uv_fac;
967
968                 if (gps->dvert != NULL) {
969                         MDeformVert *dvert = &gps->dvert[i];
970                         dvert->totweight = 0;
971                         dvert->dw = NULL;
972                 }
973
974                 /* Restore original points */
975                 copy_v2_v2(&p2d->x, tmp_xyp);
976         }
977
978         /* store cps and convert coords */
979         if (tgpi->gpd->runtime.tot_cp_points > 0) {
980                 bGPDcontrolpoint *cps = tgpi->gpd->runtime.cp_points;
981                 for (int i = 0; i < tgpi->gpd->runtime.tot_cp_points; i++) {
982                         bGPDcontrolpoint *cp = &cps[i];
983                         gp_stroke_convertcoords_tpoint(tgpi->scene, tgpi->ar, tgpi->ob, tgpi->gpl, (tGPspoint *)cp, NULL, &cp->x);
984                 }
985         }
986
987         /* reproject to plane */
988         if (!is_depth) {
989                 float origin[3];
990                 ED_gp_get_drawing_reference(tgpi->scene, tgpi->ob, tgpi->gpl,
991                         ts->gpencil_v3d_align, origin);
992                 ED_gp_project_stroke_to_plane(
993                         tgpi->ob, tgpi->rv3d, gps, origin, ts->gp_sculpt.lock_axis - 1);
994         }
995
996         /* if parented change position relative to parent object */
997         for (int i = 0; i < gps->totpoints; i++) {
998                 bGPDspoint *pt = &gps->points[i];
999                 gp_apply_parent_point(tgpi->depsgraph, tgpi->ob, tgpi->gpd, tgpi->gpl, pt);
1000         }
1001
1002         /* if camera view, reproject flat to view to avoid perspective effect */
1003         if (is_camera) {
1004                 ED_gpencil_project_stroke_to_view(C, tgpi->gpl, gps);
1005         }
1006
1007         /* force fill recalc */
1008         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
1009
1010         MEM_SAFE_FREE(depth_arr);
1011
1012         DEG_id_tag_update(&gpd->id, ID_RECALC_COPY_ON_WRITE);
1013         DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
1014         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
1015 }
1016
1017 /* Update screen and stroke */
1018 static void gpencil_primitive_update(bContext *C, wmOperator *op, tGPDprimitive *tgpi)
1019 {
1020         /* update indicator in header */
1021         gpencil_primitive_status_indicators(C, tgpi);
1022         /* apply... */
1023         tgpi->type = RNA_enum_get(op->ptr, "type");
1024         tgpi->tot_edges = RNA_int_get(op->ptr, "edges");
1025         /* update points position */
1026         gp_primitive_update_strokes(C, tgpi);
1027 }
1028
1029 static void gpencil_primitive_interaction_begin(tGPDprimitive *tgpi, const wmEvent *event)
1030 {
1031         copy_v2fl_v2i(tgpi->mval, event->mval);
1032         copy_v2_v2(tgpi->origin, tgpi->mval);
1033         copy_v2_v2(tgpi->start, tgpi->mval);
1034         copy_v2_v2(tgpi->end, tgpi->mval);
1035         copy_v2_v2(tgpi->cp1, tgpi->mval);
1036         copy_v2_v2(tgpi->cp2, tgpi->mval);
1037 }
1038
1039 /* Exit and free memory */
1040 static void gpencil_primitive_exit(bContext *C, wmOperator *op)
1041 {
1042         tGPDprimitive *tgpi = op->customdata;
1043         bGPdata *gpd = tgpi->gpd;
1044
1045         /* don't assume that operator data exists at all */
1046         if (tgpi) {
1047                 /* clear status message area */
1048                 ED_workspace_status_text(C, NULL);
1049
1050                 MEM_SAFE_FREE(tgpi->points);
1051                 tgpi->gpd->runtime.tot_cp_points = 0;
1052                 MEM_SAFE_FREE(tgpi->gpd->runtime.cp_points);
1053                 /* finally, free memory used by temp data */
1054                 BKE_gpencil_free_strokes(tgpi->gpf);
1055                 MEM_SAFE_FREE(tgpi->gpf);
1056
1057                 /* free random seed */
1058                 if (tgpi->rng != NULL) {
1059                         BLI_rng_free(tgpi->rng);
1060                 }
1061
1062                 MEM_freeN(tgpi);
1063         }
1064
1065         /* free stroke buffer */
1066         if ((gpd != NULL) && (gpd->runtime.sbuffer)) {
1067                 MEM_SAFE_FREE(gpd->runtime.sbuffer);
1068                 gpd->runtime.sbuffer = NULL;
1069
1070                 /* clear flags */
1071                 gpd->runtime.sbuffer_size = 0;
1072                 gpd->runtime.sbuffer_sflag = 0;
1073         }
1074
1075         DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_COPY_ON_WRITE);
1076         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
1077
1078         /* clear pointer */
1079         op->customdata = NULL;
1080 }
1081
1082 /* Init new temporary primitive data */
1083 static void gpencil_primitive_init(bContext *C, wmOperator *op)
1084 {
1085         ToolSettings *ts = CTX_data_tool_settings(C);
1086         bGPdata *gpd = CTX_data_gpencil_data(C);
1087         Main *bmain = CTX_data_main(C);
1088         Scene *scene = CTX_data_scene(C);
1089         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1090         int cfra_eval = (int)DEG_get_ctime(depsgraph);
1091
1092         /* create temporary operator data */
1093         tGPDprimitive *tgpi = MEM_callocN(sizeof(tGPDprimitive), "GPencil Primitive Data");
1094         op->customdata = tgpi;
1095
1096         tgpi->points = MEM_callocN(sizeof(tGPspoint), "gp primitive points2D");
1097
1098         /* set current scene and window info */
1099         tgpi->bmain = CTX_data_main(C);
1100         tgpi->scene = scene;
1101         tgpi->ob = CTX_data_active_object(C);
1102         tgpi->sa = CTX_wm_area(C);
1103         tgpi->ar = CTX_wm_region(C);
1104         tgpi->rv3d = tgpi->ar->regiondata;
1105         tgpi->v3d = tgpi->sa->spacedata.first;
1106         tgpi->depsgraph = CTX_data_depsgraph(C);
1107         tgpi->win = CTX_wm_window(C);
1108
1109         /* save original type */
1110         tgpi->orign_type = RNA_enum_get(op->ptr, "type");
1111
1112         /* set current frame number */
1113         tgpi->cframe = cfra_eval;
1114
1115         /* set GP datablock */
1116         tgpi->gpd = gpd;
1117         /* region where paint was originated */
1118         tgpi->gpd->runtime.ar = tgpi->ar;
1119
1120         /* control points */
1121         tgpi->gpd->runtime.cp_points = MEM_callocN(sizeof(bGPDcontrolpoint) * MAX_CP, "gp primitive cpoint");
1122         tgpi->gpd->runtime.tot_cp_points = 0;
1123
1124         /* getcolor info */
1125         tgpi->mat = BKE_gpencil_material_ensure(bmain, tgpi->ob);
1126
1127         /* set parameters */
1128         tgpi->type = RNA_enum_get(op->ptr, "type");
1129
1130         if (ELEM(tgpi->type, GP_STROKE_ARC, GP_STROKE_CURVE)) {
1131                 tgpi->curve = true;
1132         }
1133         else {
1134                 tgpi->curve = false;
1135         }
1136
1137         /* set default edge count */
1138         switch (tgpi->type) {
1139                 case GP_STROKE_LINE:
1140                 {
1141                         RNA_int_set(op->ptr, "edges", 8);
1142                         break;
1143                 }
1144                 case GP_STROKE_BOX:
1145                 {
1146                         RNA_int_set(op->ptr, "edges", 8);
1147                         break;
1148                 }
1149                 case GP_STROKE_CIRCLE:
1150                 {
1151                         RNA_int_set(op->ptr, "edges", 96);
1152                         break;
1153                 }
1154                 default:
1155                 {
1156                         RNA_int_set(op->ptr, "edges", 64);
1157                         break;
1158                 }
1159         }
1160
1161         tgpi->tot_stored_edges = 0;
1162         tgpi->tot_edges = RNA_int_get(op->ptr, "edges");
1163         tgpi->flag = IDLE;
1164         tgpi->lock_axis = ts->gp_sculpt.lock_axis;
1165
1166         /* set temp layer, frame and stroke */
1167         gp_primitive_set_initdata(C, tgpi);
1168 }
1169
1170 /* Invoke handler: Initialize the operator */
1171 static int gpencil_primitive_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1172 {
1173         wmWindow *win = CTX_wm_window(C);
1174         bGPdata *gpd = CTX_data_gpencil_data(C);
1175         tGPDprimitive *tgpi = NULL;
1176
1177         /* initialize operator runtime data */
1178         gpencil_primitive_init(C, op);
1179         tgpi = op->customdata;
1180
1181         const bool is_modal = RNA_boolean_get(op->ptr, "wait_for_input");
1182         if (!is_modal) {
1183                 tgpi->flag = IN_PROGRESS;
1184                 gpencil_primitive_interaction_begin(tgpi, event);
1185         }
1186
1187         /* if in tools region, wait till we get to the main (3d-space)
1188          * region before allowing drawing to take place.
1189          */
1190         op->flag |= OP_IS_MODAL_CURSOR_REGION;
1191
1192         /* set cursor to indicate modal */
1193         WM_cursor_modal_set(win, BC_CROSSCURSOR);
1194
1195         /* update sindicator in header */
1196         gpencil_primitive_status_indicators(C, tgpi);
1197         DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
1198         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
1199
1200         /* add a modal handler for this operator */
1201         WM_event_add_modal_handler(C, op);
1202
1203         return OPERATOR_RUNNING_MODAL;
1204 }
1205
1206 /* Helper to complete a primitive */
1207 static void gpencil_primitive_interaction_end(bContext *C, wmOperator *op, wmWindow *win, tGPDprimitive *tgpi)
1208 {
1209         bGPDframe *gpf;
1210         bGPDstroke *gps;
1211
1212         ToolSettings *ts = tgpi->scene->toolsettings;
1213
1214         const int def_nr = tgpi->ob->actdef - 1;
1215         const bool have_weight = (bool)BLI_findlink(&tgpi->ob->defbase, def_nr);
1216
1217         /* return to normal cursor and header status */
1218         ED_workspace_status_text(C, NULL);
1219         WM_cursor_modal_restore(win);
1220
1221         /* insert keyframes as required... */
1222         short add_frame_mode;
1223         if (ts->gpencil_flags & GP_TOOL_FLAG_RETAIN_LAST) {
1224                 add_frame_mode = GP_GETFRAME_ADD_COPY;
1225         }
1226         else {
1227                 add_frame_mode = GP_GETFRAME_ADD_NEW;
1228         }
1229
1230         gpf = BKE_gpencil_layer_getframe(tgpi->gpl, tgpi->cframe, add_frame_mode);
1231
1232         /* prepare stroke to get transferred */
1233         gps = tgpi->gpf->strokes.first;
1234         if (gps) {
1235                 gps->thickness = tgpi->brush->size;
1236                 gps->flag |= GP_STROKE_RECALC_GEOMETRY;
1237                 gps->tot_triangles = 0;
1238
1239                 /* calculate UVs along the stroke */
1240                 ED_gpencil_calc_stroke_uv(tgpi->ob, gps);
1241         }
1242
1243         /* transfer stroke from temporary buffer to the actual frame */
1244         if (ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) {
1245                 BLI_movelisttolist_reverse(&gpf->strokes, &tgpi->gpf->strokes);
1246         }
1247         else {
1248                 BLI_movelisttolist(&gpf->strokes, &tgpi->gpf->strokes);
1249         }
1250         BLI_assert(BLI_listbase_is_empty(&tgpi->gpf->strokes));
1251
1252         /* add weights if required */
1253         if ((ts->gpencil_flags & GP_TOOL_FLAG_CREATE_WEIGHTS) && (have_weight)) {
1254                 BKE_gpencil_dvert_ensure(gps);
1255                 for (int i = 0; i < gps->totpoints; i++) {
1256                         MDeformVert *ve = &gps->dvert[i];
1257                         MDeformWeight *dw = defvert_verify_index(ve, def_nr);
1258                         if (dw) {
1259                                 dw->weight = ts->vgroup_weight;
1260                         }
1261                 }
1262         }
1263
1264         DEG_id_tag_update(&tgpi->gpd->id, ID_RECALC_COPY_ON_WRITE);
1265         DEG_id_tag_update(&tgpi->gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
1266
1267         /* clean up temp data */
1268         gpencil_primitive_exit(C, op);
1269 }
1270
1271 /* edit event handling */
1272 static void gpencil_primitive_edit_event_handling(bContext *C, wmOperator *op, wmWindow *win, const wmEvent *event, tGPDprimitive *tgpi)
1273 {
1274         /* calculate nearest point then set cursor */
1275         int move = MOVE_NONE;
1276         float a = len_v2v2(tgpi->mval, tgpi->start);
1277         float b = len_v2v2(tgpi->mval, tgpi->end);
1278
1279         float c = len_v2v2(tgpi->mval, tgpi->cp1);
1280         float d = len_v2v2(tgpi->mval, tgpi->cp2);
1281
1282         if (tgpi->flag == IN_CURVE_EDIT) {
1283                 if ((a < BIG_SIZE_CTL && tgpi->tot_stored_edges == 0) || b < BIG_SIZE_CTL) {
1284                         move = MOVE_ENDS;
1285                         WM_cursor_modal_set(win, BC_NSEW_SCROLLCURSOR);
1286                 }
1287                 else if (tgpi->curve) {
1288                         move = MOVE_CP;
1289                         WM_cursor_modal_set(win, BC_HANDCURSOR);
1290                 }
1291                 else {
1292                         WM_cursor_modal_set(win, BC_CROSSCURSOR);
1293                 }
1294         }
1295         else if (tgpi->flag == IN_PROGRESS) {
1296                 WM_cursor_modal_set(win, BC_NSEW_SCROLLCURSOR);
1297         }
1298
1299         switch (event->type) {
1300                 case MOUSEMOVE:
1301                 {
1302                         if ((event->val == KM_PRESS) && tgpi->sel_cp != SELECT_NONE) {
1303                                 if (tgpi->sel_cp == SELECT_START && tgpi->tot_stored_edges == 0) {
1304                                         copy_v2_v2(tgpi->start, tgpi->mval);
1305                                 }
1306                                 else if (tgpi->sel_cp == SELECT_END) {
1307                                         copy_v2_v2(tgpi->end, tgpi->mval);
1308                                 }
1309                                 else if (tgpi->sel_cp == SELECT_CP1 || (tgpi->sel_cp == SELECT_CP2 && tgpi->type != GP_STROKE_CURVE)) {
1310                                         float dx = (tgpi->mval[0] - tgpi->mvalo[0]);
1311                                         float dy = (tgpi->mval[1] - tgpi->mvalo[1]);
1312                                         tgpi->cp1[0] += dx;
1313                                         tgpi->cp1[1] += dy;
1314                                         if (event->shift)
1315                                                 copy_v2_v2(tgpi->cp2, tgpi->cp1);
1316                                 }
1317                                 else if (tgpi->sel_cp == SELECT_CP2) {
1318                                         float dx = (tgpi->mval[0] - tgpi->mvalo[0]);
1319                                         float dy = (tgpi->mval[1] - tgpi->mvalo[1]);
1320                                         tgpi->cp2[0] += dx;
1321                                         tgpi->cp2[1] += dy;
1322                                         if (event->shift)
1323                                                 copy_v2_v2(tgpi->cp1, tgpi->cp2);
1324                                 }
1325                                 /* update screen */
1326                                 gpencil_primitive_update(C, op, tgpi);
1327                         }
1328                         break;
1329                 }
1330                 case LEFTMOUSE:
1331                 {
1332                         if ((event->val == KM_PRESS)) {
1333                                 /* find nearest cp based on stroke end points */
1334                                 if (move == MOVE_ENDS)
1335                                         tgpi->sel_cp = (a < b) ? SELECT_START : SELECT_END;
1336                                 else if (move == MOVE_CP)
1337                                         tgpi->sel_cp = (c < d) ? SELECT_CP1 : SELECT_CP2;
1338                                 else
1339                                         tgpi->sel_cp = SELECT_NONE;
1340                                 break;
1341                         }
1342                         else if ((event->val == KM_RELEASE) && (tgpi->flag == IN_PROGRESS)) {
1343                                 /* set control points and enter edit mode */
1344                                 tgpi->flag = IN_CURVE_EDIT;
1345                                 gp_primitive_update_cps(tgpi);
1346                                 gpencil_primitive_update(C, op, tgpi);
1347                         }
1348                         else {
1349                                 tgpi->sel_cp = SELECT_NONE;
1350                         }
1351                         break;
1352                 }
1353                 case MKEY:
1354                 {
1355                         if ((event->val == KM_PRESS) &&
1356                             (tgpi->curve) &&
1357                             (ELEM(tgpi->orign_type, GP_STROKE_ARC) ))
1358                         {
1359                                 tgpi->flip ^= 1;
1360                                 gp_primitive_update_cps(tgpi);
1361                                 gpencil_primitive_update(C, op, tgpi);
1362                         }
1363                         break;
1364                 }
1365                 case EKEY:
1366                 {
1367                         if (tgpi->flag == IN_CURVE_EDIT && !ELEM(tgpi->type, GP_STROKE_BOX, GP_STROKE_CIRCLE)) {
1368                                 tgpi->flag = IN_PROGRESS;
1369                                 WM_cursor_modal_set(win, BC_NSEW_SCROLLCURSOR);
1370                                 gpencil_primitive_add_segment(tgpi);
1371                                 copy_v2_v2(tgpi->start, tgpi->end);
1372                                 copy_v2_v2(tgpi->origin, tgpi->start);
1373                                 gp_primitive_update_cps(tgpi);
1374                         }
1375                         break;
1376                 }
1377         }
1378 }
1379
1380 /* brush strength */
1381 static void gpencil_primitive_strength(tGPDprimitive *tgpi, bool reset)
1382 {
1383         Brush *brush = tgpi->brush;
1384         if (brush) {
1385                 if (reset) {
1386                         brush->gpencil_settings->draw_strength = tgpi->brush_strength;
1387                         tgpi->brush_strength = 0.0f;
1388                 }
1389                 else {
1390                         if (tgpi->brush_strength == 0.0f) {
1391                                 tgpi->brush_strength = brush->gpencil_settings->draw_strength;
1392                         }
1393                         float move[2];
1394                         sub_v2_v2v2(move, tgpi->mval, tgpi->mvalo);
1395                         float adjust = (move[1] > 0.0f) ? 0.01f : -0.01f;
1396                         brush->gpencil_settings->draw_strength += adjust * fabsf(len_manhattan_v2(move));
1397                 }
1398
1399                 /* limit low limit because below 0.2f the stroke is invisible */
1400                 CLAMP(brush->gpencil_settings->draw_strength, 0.2f, 1.0f);
1401         }
1402 }
1403
1404 /* brush size */
1405 static void gpencil_primitive_size(tGPDprimitive *tgpi, bool reset)
1406 {
1407         Brush *brush = tgpi->brush;
1408         if (brush) {
1409                 if (reset) {
1410                         brush->size = tgpi->brush_size;
1411                         tgpi->brush_size = 0;
1412                 }
1413                 else {
1414                         if (tgpi->brush_size == 0) {
1415                                 tgpi->brush_size = brush->size;
1416                         }
1417                         float move[2];
1418                         sub_v2_v2v2(move, tgpi->mval, tgpi->mvalo);
1419                         int adjust = (move[1] > 0.0f) ? 1 : -1;
1420                         brush->size += adjust * (int)fabsf(len_manhattan_v2(move));
1421                 }
1422                 CLAMP_MIN(brush->size, 1);
1423         }
1424 }
1425
1426 /* move */
1427 static void gpencil_primitive_move(tGPDprimitive *tgpi, bool reset)
1428 {
1429         float move[2];
1430         zero_v2(move);
1431
1432         if (reset) {
1433                 sub_v2_v2(move, tgpi->move);
1434                 zero_v2(tgpi->move);
1435         }
1436         else {
1437                 sub_v2_v2v2(move, tgpi->mval, tgpi->mvalo);
1438                 add_v2_v2(tgpi->move, move);
1439         }
1440
1441         bGPDstroke *gps = tgpi->gpf->strokes.first;
1442         tGPspoint *points2D = tgpi->points;
1443
1444         for (int i = 0; i < gps->totpoints; i++) {
1445                 tGPspoint *p2d = &points2D[i];
1446                 add_v2_v2(&p2d->x, move);
1447         }
1448
1449         add_v2_v2(tgpi->start, move);
1450         add_v2_v2(tgpi->end, move);
1451         add_v2_v2(tgpi->cp1, move);
1452         add_v2_v2(tgpi->cp2, move);
1453         add_v2_v2(tgpi->origin, move);
1454 }
1455
1456 /* Modal handler: Events handling during interactive part */
1457 static int gpencil_primitive_modal(bContext *C, wmOperator *op, const wmEvent *event)
1458 {
1459         tGPDprimitive *tgpi = op->customdata;
1460         wmWindow *win = CTX_wm_window(C);
1461         const bool has_numinput = hasNumInput(&tgpi->num);
1462
1463         copy_v2fl_v2i(tgpi->mval, event->mval);
1464
1465         if (tgpi->flag == IN_MOVE) {
1466
1467                 switch (event->type) {
1468                         case MOUSEMOVE:
1469                         {
1470                                 gpencil_primitive_move(tgpi, false);
1471                                 gpencil_primitive_update(C, op, tgpi);
1472                                 break;
1473                         }
1474                         case ESCKEY:
1475                         case LEFTMOUSE:
1476                         {
1477                                 zero_v2(tgpi->move);
1478                                 tgpi->flag = IN_CURVE_EDIT;
1479                                 break;
1480                         }
1481                         case RIGHTMOUSE:
1482                         {
1483                                 if (event->val == KM_RELEASE) {
1484                                         tgpi->flag = IN_CURVE_EDIT;
1485                                         gpencil_primitive_move(tgpi, true);
1486                                         gpencil_primitive_update(C, op, tgpi);
1487                                 }
1488                                 break;
1489                         }
1490                 }
1491                 copy_v2_v2(tgpi->mvalo, tgpi->mval);
1492                 return OPERATOR_RUNNING_MODAL;
1493         }
1494         else if (tgpi->flag == IN_BRUSH_SIZE) {
1495                 switch (event->type) {
1496                         case MOUSEMOVE:
1497                                 gpencil_primitive_size(tgpi, false);
1498                                 gpencil_primitive_update(C, op, tgpi);
1499                                 break;
1500                         case ESCKEY:
1501                         case MIDDLEMOUSE:
1502                         case LEFTMOUSE:
1503                                 tgpi->brush_size = 0;
1504                                 tgpi->flag = IN_CURVE_EDIT;
1505                                 break;
1506                         case RIGHTMOUSE:
1507                                 if (event->val == KM_RELEASE) {
1508                                         tgpi->flag = IN_CURVE_EDIT;
1509                                         gpencil_primitive_size(tgpi, true);
1510                                         gpencil_primitive_update(C, op, tgpi);
1511                                 }
1512                                 break;
1513                 }
1514                 copy_v2_v2(tgpi->mvalo, tgpi->mval);
1515                 return OPERATOR_RUNNING_MODAL;
1516         }
1517         else if (tgpi->flag == IN_BRUSH_STRENGTH) {
1518                 switch (event->type) {
1519                         case MOUSEMOVE:
1520                                 gpencil_primitive_strength(tgpi, false);
1521                                 gpencil_primitive_update(C, op, tgpi);
1522                                 break;
1523                         case ESCKEY:
1524                         case MIDDLEMOUSE:
1525                         case LEFTMOUSE:
1526                                 tgpi->brush_strength = 0.0f;
1527                                 tgpi->flag = IN_CURVE_EDIT;
1528                                 break;
1529                         case RIGHTMOUSE:
1530                                 if (event->val == KM_RELEASE) {
1531                                         tgpi->flag = IN_CURVE_EDIT;
1532                                         gpencil_primitive_strength(tgpi, true);
1533                                         gpencil_primitive_update(C, op, tgpi);
1534                                 }
1535                                 break;
1536                 }
1537                 copy_v2_v2(tgpi->mvalo, tgpi->mval);
1538                 return OPERATOR_RUNNING_MODAL;
1539         }
1540         else if (tgpi->flag != IDLE) {
1541                 gpencil_primitive_edit_event_handling(C, op, win, event, tgpi);
1542         }
1543
1544         switch (event->type) {
1545                 case LEFTMOUSE:
1546                 {
1547                         if ((event->val == KM_PRESS) && (tgpi->flag == IDLE)) {
1548                                 /* start drawing primitive */
1549                                 /* TODO: Ignore if not in main region yet */
1550                                 tgpi->flag = IN_PROGRESS;
1551                                 gpencil_primitive_interaction_begin(tgpi, event);
1552                         }
1553                         else if ((event->val == KM_RELEASE) && (tgpi->flag == IN_MOVE)) {
1554                                 tgpi->flag = IN_CURVE_EDIT;
1555                         }
1556                         else if ((event->val == KM_RELEASE) && (tgpi->flag == IN_PROGRESS)) {
1557                                 /* set control points and enter edit mode */
1558                                 tgpi->flag = IN_CURVE_EDIT;
1559                                 gp_primitive_update_cps(tgpi);
1560                                 gpencil_primitive_update(C, op, tgpi);
1561                         }
1562                         else if ((event->val == KM_RELEASE) && (tgpi->flag == IN_PROGRESS) && (tgpi->type != GP_STROKE_CURVE)) {
1563                                 /* stop drawing primitive */
1564                                 tgpi->flag = IDLE;
1565                                 gpencil_primitive_interaction_end(C, op, win, tgpi);
1566                                 /* done! */
1567                                 return OPERATOR_FINISHED;
1568                         }
1569                         else {
1570                                 if (G.debug & G_DEBUG) {
1571                                         printf("GP Add Primitive Modal: LEFTMOUSE %d, Status = %d\n", event->val, tgpi->flag);
1572                                 }
1573                         }
1574                         break;
1575                 }
1576                 case SPACEKEY:  /* confirm */
1577                 case MIDDLEMOUSE:
1578                 case RETKEY:
1579                 {
1580                         tgpi->flag = IDLE;
1581                         gpencil_primitive_interaction_end(C, op, win, tgpi);
1582                         /* done! */
1583                         return OPERATOR_FINISHED;
1584                 }
1585                 case RIGHTMOUSE:
1586                 {
1587                         /* exception to cancel current stroke when we have previous strokes in buffer */
1588                         if (tgpi->tot_stored_edges > 0) {
1589                                 tgpi->flag = IDLE;
1590                                 tgpi->tot_edges = 0;
1591                                 gp_primitive_update_strokes(C, tgpi);
1592                                 gpencil_primitive_interaction_end(C, op, win, tgpi);
1593                                 /* done! */
1594                                 return OPERATOR_FINISHED;
1595                         }
1596                         ATTR_FALLTHROUGH;
1597                 }
1598                 case ESCKEY:
1599                 {
1600                         /* return to normal cursor and header status */
1601                         ED_workspace_status_text(C, NULL);
1602                         WM_cursor_modal_restore(win);
1603
1604                         /* clean up temp data */
1605                         gpencil_primitive_exit(C, op);
1606
1607                         /* canceled! */
1608                         return OPERATOR_CANCELLED;
1609                 }
1610                 case PADPLUSKEY:
1611                 case WHEELUPMOUSE:
1612                 {
1613                         if ((event->val != KM_RELEASE)) {
1614                                 tgpi->tot_edges = tgpi->tot_edges + 1;
1615                                 CLAMP(tgpi->tot_edges, MIN_EDGES, MAX_EDGES);
1616                                 RNA_int_set(op->ptr, "edges", tgpi->tot_edges);
1617
1618                                 /* update screen */
1619                                 gpencil_primitive_update(C, op, tgpi);
1620                         }
1621                         break;
1622                 }
1623                 case PADMINUS:
1624                 case WHEELDOWNMOUSE:
1625                 {
1626                         if ((event->val != KM_RELEASE)) {
1627                                 tgpi->tot_edges = tgpi->tot_edges - 1;
1628                                 CLAMP(tgpi->tot_edges, MIN_EDGES, MAX_EDGES);
1629                                 RNA_int_set(op->ptr, "edges", tgpi->tot_edges);
1630
1631                                 /* update screen */
1632                                 gpencil_primitive_update(C, op, tgpi);
1633                         }
1634                         break;
1635                 }
1636                 case GKEY: /* grab mode */
1637                 {
1638                         if ((event->val == KM_PRESS)) {
1639                                 tgpi->flag = IN_MOVE;
1640                                 WM_cursor_modal_set(win, BC_NSEW_SCROLLCURSOR);
1641                         }
1642                         break;
1643                 }
1644                 case FKEY: /* brush thickness/ brush strength */
1645                 {
1646                         if ((event->val == KM_PRESS)) {
1647                                 if (event->shift) {
1648                                         tgpi->flag = IN_BRUSH_STRENGTH;
1649                                 }
1650                                 else {
1651                                         tgpi->flag = IN_BRUSH_SIZE;
1652                                 }
1653                                 WM_cursor_modal_set(win, BC_NS_SCROLLCURSOR);
1654                         }
1655                         break;
1656                 }
1657                 case CKEY: /* curve mode */
1658                 {
1659                         if ((event->val == KM_PRESS) &&
1660                             (tgpi->orign_type == GP_STROKE_CURVE))
1661                         {
1662                                 switch (tgpi->type) {
1663                                         case GP_STROKE_CURVE:
1664                                                 tgpi->type = GP_STROKE_ARC;
1665                                                 break;
1666                                         default:
1667                                         case GP_STROKE_ARC:
1668                                                 tgpi->type = GP_STROKE_CURVE;
1669                                                 break;
1670                                 }
1671
1672                                 RNA_enum_set(op->ptr, "type", tgpi->type);
1673                                 gp_primitive_update_cps(tgpi);
1674                                 gpencil_primitive_update(C, op, tgpi);
1675                         }
1676                         break;
1677                 }
1678                 case TABKEY:
1679                 {
1680                         if (tgpi->flag == IN_CURVE_EDIT) {
1681                                 tgpi->flag = IN_PROGRESS;
1682                                 WM_cursor_modal_set(win, BC_NSEW_SCROLLCURSOR);
1683                                 gp_primitive_update_cps(tgpi);
1684                                 gpencil_primitive_update(C, op, tgpi);
1685                         }
1686                         break;
1687                 }
1688                 case MOUSEMOVE: /* calculate new position */
1689                 {
1690                         if (tgpi->flag == IN_CURVE_EDIT) {
1691                                 break;
1692                         }
1693                         /* only handle mousemove if not doing numinput */
1694                         if (has_numinput == false) {
1695                                 /* update position of mouse */
1696                                 copy_v2_v2(tgpi->end, tgpi->mval);
1697                                 copy_v2_v2(tgpi->start, tgpi->origin);
1698                                 if (tgpi->flag == IDLE) {
1699                                         copy_v2_v2(tgpi->origin, tgpi->mval);
1700                                 }
1701                                 /* Keep square if shift key */
1702                                 if (event->shift) {
1703                                         float x = tgpi->end[0] - tgpi->origin[0];
1704                                         float y = tgpi->end[1] - tgpi->origin[1];
1705                                         if (tgpi->type == GP_STROKE_LINE || tgpi->curve) {
1706                                                 float angle = fabsf(atan2f(y, x));
1707                                                 if (angle < 0.4f || angle > (M_PI - 0.4f)) {
1708                                                         tgpi->end[1] = tgpi->origin[1];
1709                                                 }
1710                                                 else if (angle > (M_PI_2 - 0.4f) && angle < (M_PI_2 + 0.4f)) {
1711                                                         tgpi->end[0] = tgpi->origin[0];
1712                                                 }
1713                                                 else {
1714                                                         gpencil_primitive_to_square(tgpi, x, y);
1715                                                 }
1716                                         }
1717                                         else {
1718                                                 gpencil_primitive_to_square(tgpi, x, y);
1719                                         }
1720                                 }
1721                                 /* Center primitive if alt key */
1722                                 if (event->alt) {
1723                                         tgpi->start[0] = tgpi->origin[0] - (tgpi->end[0] - tgpi->origin[0]);
1724                                         tgpi->start[1] = tgpi->origin[1] - (tgpi->end[1] - tgpi->origin[1]);
1725                                 }
1726                                 gp_primitive_update_cps(tgpi);
1727                                 /* update screen */
1728                                 gpencil_primitive_update(C, op, tgpi);
1729                         }
1730                         break;
1731                 }
1732                 default:
1733                 {
1734                         if (tgpi->flag != IN_CURVE_EDIT && (event->val == KM_PRESS) && handleNumInput(C, &tgpi->num, event)) {
1735                                 float value;
1736
1737                                 /* Grab data from numeric input, and store this new value (the user see an int) */
1738                                 value = tgpi->tot_edges;
1739                                 applyNumInput(&tgpi->num, &value);
1740                                 tgpi->tot_edges = value;
1741
1742                                 CLAMP(tgpi->tot_edges, MIN_EDGES, MAX_EDGES);
1743                                 RNA_int_set(op->ptr, "edges", tgpi->tot_edges);
1744
1745                                 /* update screen */
1746                                 gpencil_primitive_update(C, op, tgpi);
1747
1748                                 break;
1749                         }
1750                         else {
1751                                 /* unhandled event - allow to pass through */
1752                                 return OPERATOR_RUNNING_MODAL | OPERATOR_PASS_THROUGH;
1753                         }
1754                 }
1755         }
1756
1757         copy_v2_v2(tgpi->mvalo, tgpi->mval);
1758         /* still running... */
1759         return OPERATOR_RUNNING_MODAL;
1760 }
1761
1762 /* Cancel handler */
1763 static void gpencil_primitive_cancel(bContext *C, wmOperator *op)
1764 {
1765         /* this is just a wrapper around exit() */
1766         gpencil_primitive_exit(C, op);
1767 }
1768
1769 void GPENCIL_OT_primitive(wmOperatorType *ot)
1770 {
1771         static EnumPropertyItem primitive_type[] = {
1772                 {GP_STROKE_BOX, "BOX", 0, "Box", ""},
1773                 {GP_STROKE_LINE, "LINE", 0, "Line", ""},
1774                 {GP_STROKE_CIRCLE, "CIRCLE", 0, "Circle", ""},
1775                 {GP_STROKE_ARC, "ARC", 0, "Arc", ""},
1776                 {GP_STROKE_CURVE, "CURVE", 0, "Curve", ""},
1777                 {0, NULL, 0, NULL, NULL},
1778         };
1779
1780         /* identifiers */
1781         ot->name = "Grease Pencil Shapes";
1782         ot->idname = "GPENCIL_OT_primitive";
1783         ot->description = "Create predefined grease pencil stroke shapes";
1784
1785         /* callbacks */
1786         ot->invoke = gpencil_primitive_invoke;
1787         ot->modal = gpencil_primitive_modal;
1788         ot->cancel = gpencil_primitive_cancel;
1789         ot->poll = gpencil_primitive_add_poll;
1790
1791         /* flags */
1792         ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
1793
1794         /* properties */
1795         PropertyRNA *prop;
1796
1797         prop = RNA_def_int(ot->srna, "edges", 4, MIN_EDGES, MAX_EDGES, "Edges", "Number of polygon edges", MIN_EDGES, MAX_EDGES);
1798         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1799
1800         RNA_def_enum(ot->srna, "type", primitive_type, GP_STROKE_BOX, "Type", "Type of shape");
1801
1802         prop = RNA_def_boolean(ot->srna, "wait_for_input", true, "Wait for Input", "");
1803         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1804 }