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