GP: Primitive: Fix flickering when using a noise brush
[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                         if (p2d->rnd[0] > 0.5f) {
830                                 add_v2_fl(&p2d->x, -fac);
831                         }
832                         else {
833                                 add_v2_fl(&p2d->x, fac);
834                         }
835                 }
836
837                 /* apply randomness to pressure */
838                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
839                     (brush->gpencil_settings->draw_random_press > 0.0f))
840                 {
841                         if (p2d->rnd[0] > 0.5f) {
842                                 pressure -= brush->gpencil_settings->draw_random_press * p2d->rnd[0];
843                         }
844                         else {
845                                 pressure += brush->gpencil_settings->draw_random_press * p2d->rnd[0];
846                         }
847                 }
848
849                 /* color strength */
850                 if (brush->gpencil_settings->flag & GP_BRUSH_USE_STENGTH_PRESSURE) {
851                         float curvef = curvemapping_evaluateF(brush->gpencil_settings->curve_strength, 0, curve_pressure);
852                         strength *= curvef * brush->gpencil_settings->draw_sensitivity;
853                         strength *= brush->gpencil_settings->draw_strength;
854                 }
855
856                 CLAMP(strength, GPENCIL_STRENGTH_MIN, 1.0f);
857
858                 /* apply randomness to color strength */
859                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
860                     (brush->gpencil_settings->draw_random_strength > 0.0f))
861                 {
862                         if (p2d->rnd[1] > 0.5f) {
863                                 strength -= strength * brush->gpencil_settings->draw_random_strength * p2d->rnd[1];
864                         }
865                         else {
866                                 strength += strength * brush->gpencil_settings->draw_random_strength * p2d->rnd[1];
867                         }
868                         CLAMP(strength, GPENCIL_STRENGTH_MIN, 1.0f);
869                 }
870
871                 copy_v2_v2(&tpt->x, &p2d->x);
872
873                 CLAMP_MIN(pressure, 0.1f);
874
875                 tpt->pressure = pressure;
876                 tpt->strength = strength;
877                 tpt->time = p2d->time;
878                 tpt->uv_fac = 1.0f;
879                 tpt->uv_rot = p2d->uv_rot;
880
881                 gpd->runtime.sbuffer_size++;
882
883                 /* add small offset to keep stroke over the surface */
884                 if ((depth_arr) && (gpd->zdepth_offset > 0.0f)) {
885                         depth_arr[i] *= (1.0f - gpd->zdepth_offset);
886                 }
887
888                 /* convert screen-coordinates to 3D coordinates */
889                 gp_stroke_convertcoords_tpoint(
890                         tgpi->scene, tgpi->ar, tgpi->ob, tgpi->gpl,
891                         p2d, depth_arr ? depth_arr + i : NULL,
892                         &pt->x);
893
894                 pt->pressure = pressure;
895                 pt->strength = strength;
896                 pt->time = 0.0f;
897                 pt->flag = 0;
898                 pt->uv_fac = 1.0f;
899
900                 if (gps->dvert != NULL) {
901                         MDeformVert *dvert = &gps->dvert[i];
902                         dvert->totweight = 0;
903                         dvert->dw = NULL;
904                 }
905
906                 /* Restore original points */
907                 copy_v2_v2(&p2d->x, tmp_xyp);
908         }
909
910         /* store cps and convert coords */
911         if (tgpi->gpd->runtime.tot_cp_points > 0) {
912                 bGPDcontrolpoint *cps = tgpi->gpd->runtime.cp_points;
913                 for (int i = 0; i < tgpi->gpd->runtime.tot_cp_points; i++) {
914                         bGPDcontrolpoint *cp = &cps[i];
915                         gp_stroke_convertcoords_tpoint(tgpi->scene, tgpi->ar, tgpi->ob, tgpi->gpl, (tGPspoint *)cp, NULL, &cp->x);
916                 }
917         }
918
919         /* reproject to plane */
920         if (!is_depth) {
921                 float origin[3];
922                 ED_gp_get_drawing_reference(tgpi->scene, tgpi->ob, tgpi->gpl,
923                         ts->gpencil_v3d_align, origin);
924                 ED_gp_project_stroke_to_plane(
925                         tgpi->ob, tgpi->rv3d, gps, origin, ts->gp_sculpt.lock_axis - 1);
926         }
927
928         /* if parented change position relative to parent object */
929         for (int i = 0; i < gps->totpoints; i++) {
930                 bGPDspoint *pt = &gps->points[i];
931                 gp_apply_parent_point(tgpi->depsgraph, tgpi->ob, tgpi->gpd, tgpi->gpl, pt);
932         }
933
934         /* force fill recalc */
935         gps->flag |= GP_STROKE_RECALC_CACHES;
936
937         MEM_SAFE_FREE(depth_arr);
938
939         DEG_id_tag_update(&gpd->id, ID_RECALC_COPY_ON_WRITE);
940         DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
941         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
942 }
943
944 /* Update screen and stroke */
945 static void gpencil_primitive_update(bContext *C, wmOperator *op, tGPDprimitive *tgpi)
946 {
947         /* update indicator in header */
948         gpencil_primitive_status_indicators(C, tgpi);
949         /* apply... */
950         tgpi->type = RNA_enum_get(op->ptr, "type");
951         tgpi->tot_edges = RNA_int_get(op->ptr, "edges");
952         /* update points position */
953         gp_primitive_update_strokes(C, tgpi);
954 }
955
956 static void gpencil_primitive_interaction_begin(tGPDprimitive *tgpi, const wmEvent *event)
957 {
958         copy_v2fl_v2i(tgpi->mval, event->mval);
959         copy_v2_v2(tgpi->origin, tgpi->mval);
960         copy_v2_v2(tgpi->start, tgpi->mval);
961         copy_v2_v2(tgpi->end, tgpi->mval);
962         copy_v2_v2(tgpi->cp1, tgpi->mval);
963         copy_v2_v2(tgpi->cp2, tgpi->mval);
964 }
965
966 /* Exit and free memory */
967 static void gpencil_primitive_exit(bContext *C, wmOperator *op)
968 {
969         tGPDprimitive *tgpi = op->customdata;
970         bGPdata *gpd = tgpi->gpd;
971
972         /* don't assume that operator data exists at all */
973         if (tgpi) {
974                 /* clear status message area */
975                 ED_workspace_status_text(C, NULL);
976
977                 MEM_SAFE_FREE(tgpi->points);
978                 tgpi->gpd->runtime.tot_cp_points = 0;
979                 MEM_SAFE_FREE(tgpi->gpd->runtime.cp_points);
980                 /* finally, free memory used by temp data */
981                 BKE_gpencil_free_strokes(tgpi->gpf);
982                 MEM_SAFE_FREE(tgpi->gpf);
983
984                 /* free random seed */
985                 if (tgpi->rng != NULL) {
986                         BLI_rng_free(tgpi->rng);
987                 }
988
989                 MEM_freeN(tgpi);
990         }
991
992         /* free stroke buffer */
993         if ((gpd != NULL) && (gpd->runtime.sbuffer)) {
994                 MEM_SAFE_FREE(gpd->runtime.sbuffer);
995                 gpd->runtime.sbuffer = NULL;
996
997                 /* clear flags */
998                 gpd->runtime.sbuffer_size = 0;
999                 gpd->runtime.sbuffer_sflag = 0;
1000         }
1001
1002         DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_COPY_ON_WRITE);
1003         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
1004
1005         /* clear pointer */
1006         op->customdata = NULL;
1007 }
1008
1009 /* Init new temporary primitive data */
1010 static void gpencil_primitive_init(bContext *C, wmOperator *op)
1011 {
1012         ToolSettings *ts = CTX_data_tool_settings(C);
1013         bGPdata *gpd = CTX_data_gpencil_data(C);
1014         Main *bmain = CTX_data_main(C);
1015         Scene *scene = CTX_data_scene(C);
1016         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1017         int cfra_eval = (int)DEG_get_ctime(depsgraph);
1018
1019         /* create temporary operator data */
1020         tGPDprimitive *tgpi = MEM_callocN(sizeof(tGPDprimitive), "GPencil Primitive Data");
1021         op->customdata = tgpi;
1022
1023         tgpi->points = MEM_callocN(sizeof(tGPspoint), "gp primitive points2D");
1024
1025         /* set current scene and window info */
1026         tgpi->bmain = CTX_data_main(C);
1027         tgpi->scene = scene;
1028         tgpi->ob = CTX_data_active_object(C);
1029         tgpi->sa = CTX_wm_area(C);
1030         tgpi->ar = CTX_wm_region(C);
1031         tgpi->rv3d = tgpi->ar->regiondata;
1032         tgpi->v3d = tgpi->sa->spacedata.first;
1033         tgpi->depsgraph = CTX_data_depsgraph(C);
1034         tgpi->win = CTX_wm_window(C);
1035
1036         /* save original type */
1037         tgpi->orign_type = RNA_enum_get(op->ptr, "type");
1038
1039         /* set current frame number */
1040         tgpi->cframe = cfra_eval;
1041
1042         /* set GP datablock */
1043         tgpi->gpd = gpd;
1044         /* region where paint was originated */
1045         tgpi->gpd->runtime.ar = tgpi->ar;
1046
1047         /* control points */
1048         tgpi->gpd->runtime.cp_points = MEM_callocN(sizeof(bGPDcontrolpoint) * MAX_CP, "gp primitive cpoint");
1049         tgpi->gpd->runtime.tot_cp_points = 0;
1050
1051         /* getcolor info */
1052         tgpi->mat = BKE_gpencil_material_ensure(bmain, tgpi->ob);
1053
1054         /* set parameters */
1055         tgpi->type = RNA_enum_get(op->ptr, "type");
1056
1057         if (ELEM(tgpi->type, GP_STROKE_ARC, GP_STROKE_CURVE)) {
1058                 tgpi->curve = true;
1059         }
1060         else {
1061                 tgpi->curve = false;
1062         }
1063
1064         /* set default edge count */
1065         switch (tgpi->type) {
1066                 case GP_STROKE_LINE:
1067                 {
1068                         RNA_int_set(op->ptr, "edges", 8);
1069                         break;
1070                 }
1071                 case GP_STROKE_BOX:
1072                 {
1073                         RNA_int_set(op->ptr, "edges", 8);
1074                         break;
1075                 }
1076                 case GP_STROKE_CIRCLE:
1077                 {
1078                         RNA_int_set(op->ptr, "edges", 96);
1079                         break;
1080                 }
1081                 default:
1082                 {
1083                         RNA_int_set(op->ptr, "edges", 64);
1084                         break;
1085                 }
1086         }
1087
1088         tgpi->tot_stored_edges = 0;
1089         tgpi->tot_edges = RNA_int_get(op->ptr, "edges");
1090         tgpi->flag = IDLE;
1091         tgpi->lock_axis = ts->gp_sculpt.lock_axis;
1092
1093         /* set temp layer, frame and stroke */
1094         gp_primitive_set_initdata(C, tgpi);
1095 }
1096
1097 /* Invoke handler: Initialize the operator */
1098 static int gpencil_primitive_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1099 {
1100         wmWindow *win = CTX_wm_window(C);
1101         bGPdata *gpd = CTX_data_gpencil_data(C);
1102         tGPDprimitive *tgpi = NULL;
1103
1104         /* initialize operator runtime data */
1105         gpencil_primitive_init(C, op);
1106         tgpi = op->customdata;
1107
1108         const bool is_modal = RNA_boolean_get(op->ptr, "wait_for_input");
1109         if (!is_modal) {
1110                 tgpi->flag = IN_PROGRESS;
1111                 gpencil_primitive_interaction_begin(tgpi, event);
1112         }
1113
1114         /* if in tools region, wait till we get to the main (3d-space)
1115          * region before allowing drawing to take place.
1116          */
1117         op->flag |= OP_IS_MODAL_CURSOR_REGION;
1118
1119         /* set cursor to indicate modal */
1120         WM_cursor_modal_set(win, BC_CROSSCURSOR);
1121
1122         /* update sindicator in header */
1123         gpencil_primitive_status_indicators(C, tgpi);
1124         DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
1125         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
1126
1127         /* add a modal handler for this operator */
1128         WM_event_add_modal_handler(C, op);
1129
1130         return OPERATOR_RUNNING_MODAL;
1131 }
1132
1133 /* Helper to complete a primitive */
1134 static void gpencil_primitive_interaction_end(bContext *C, wmOperator *op, wmWindow *win, tGPDprimitive *tgpi)
1135 {
1136         bGPDframe *gpf;
1137         bGPDstroke *gps;
1138
1139         ToolSettings *ts = tgpi->scene->toolsettings;
1140
1141         const int def_nr = tgpi->ob->actdef - 1;
1142         const bool have_weight = (bool)BLI_findlink(&tgpi->ob->defbase, def_nr);
1143
1144         /* return to normal cursor and header status */
1145         ED_workspace_status_text(C, NULL);
1146         WM_cursor_modal_restore(win);
1147
1148         /* insert keyframes as required... */
1149         short add_frame_mode;
1150         if (ts->gpencil_flags & GP_TOOL_FLAG_RETAIN_LAST) {
1151                 add_frame_mode = GP_GETFRAME_ADD_COPY;
1152         }
1153         else {
1154                 add_frame_mode = GP_GETFRAME_ADD_NEW;
1155         }
1156
1157         gpf = BKE_gpencil_layer_getframe(tgpi->gpl, tgpi->cframe, add_frame_mode);
1158
1159         /* prepare stroke to get transferred */
1160         gps = tgpi->gpf->strokes.first;
1161         if (gps) {
1162                 gps->thickness = tgpi->brush->size;
1163                 gps->flag |= GP_STROKE_RECALC_CACHES;
1164                 gps->tot_triangles = 0;
1165         }
1166
1167         /* transfer stroke from temporary buffer to the actual frame */
1168         if (ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) {
1169                 BLI_movelisttolist_reverse(&gpf->strokes, &tgpi->gpf->strokes);
1170         }
1171         else {
1172                 BLI_movelisttolist(&gpf->strokes, &tgpi->gpf->strokes);
1173         }
1174         BLI_assert(BLI_listbase_is_empty(&tgpi->gpf->strokes));
1175
1176         /* add weights if required */
1177         if ((ts->gpencil_flags & GP_TOOL_FLAG_CREATE_WEIGHTS) && (have_weight)) {
1178                 BKE_gpencil_dvert_ensure(gps);
1179                 for (int i = 0; i < gps->totpoints; i++) {
1180                         MDeformVert *ve = &gps->dvert[i];
1181                         MDeformWeight *dw = defvert_verify_index(ve, def_nr);
1182                         if (dw) {
1183                                 dw->weight = ts->vgroup_weight;
1184                         }
1185                 }
1186         }
1187
1188         DEG_id_tag_update(&tgpi->gpd->id, ID_RECALC_COPY_ON_WRITE);
1189         DEG_id_tag_update(&tgpi->gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
1190
1191         /* clean up temp data */
1192         gpencil_primitive_exit(C, op);
1193 }
1194
1195 /* edit event handling */
1196 static void gpencil_primitive_edit_event_handling(bContext *C, wmOperator *op, wmWindow *win, const wmEvent *event, tGPDprimitive *tgpi)
1197 {
1198         /* calculate nearest point then set cursor */
1199         int move = MOVE_NONE;
1200         float a = len_v2v2(tgpi->mval, tgpi->start);
1201         float b = len_v2v2(tgpi->mval, tgpi->end);
1202
1203         float c = len_v2v2(tgpi->mval, tgpi->cp1);
1204         float d = len_v2v2(tgpi->mval, tgpi->cp2);
1205
1206         if (tgpi->flag == IN_CURVE_EDIT) {
1207                 if ((a < BIG_SIZE_CTL && tgpi->tot_stored_edges == 0) || b < BIG_SIZE_CTL) {
1208                         move = MOVE_ENDS;
1209                         WM_cursor_modal_set(win, BC_NSEW_SCROLLCURSOR);
1210                 }
1211                 else if (tgpi->curve) {
1212                         move = MOVE_CP;
1213                         WM_cursor_modal_set(win, BC_HANDCURSOR);
1214                 }
1215                 else {
1216                         WM_cursor_modal_set(win, BC_CROSSCURSOR);
1217                 }
1218         }
1219         else if (tgpi->flag == IN_PROGRESS) {
1220                 WM_cursor_modal_set(win, BC_NSEW_SCROLLCURSOR);
1221         }
1222
1223         switch (event->type) {
1224                 case MOUSEMOVE:
1225                 {
1226                         if ((event->val == KM_PRESS) && tgpi->sel_cp != SELECT_NONE) {
1227                                 if (tgpi->sel_cp == SELECT_START && tgpi->tot_stored_edges == 0) {
1228                                         copy_v2_v2(tgpi->start, tgpi->mval);
1229                                 }
1230                                 else if (tgpi->sel_cp == SELECT_END) {
1231                                         copy_v2_v2(tgpi->end, tgpi->mval);
1232                                 }
1233                                 else if (tgpi->sel_cp == SELECT_CP1 || (tgpi->sel_cp == SELECT_CP2 && tgpi->type != GP_STROKE_CURVE)) {
1234                                         float dx = (tgpi->mval[0] - tgpi->mvalo[0]);
1235                                         float dy = (tgpi->mval[1] - tgpi->mvalo[1]);
1236                                         tgpi->cp1[0] += dx;
1237                                         tgpi->cp1[1] += dy;
1238                                         if (event->shift)
1239                                                 copy_v2_v2(tgpi->cp2, tgpi->cp1);
1240                                 }
1241                                 else if (tgpi->sel_cp == SELECT_CP2) {
1242                                         float dx = (tgpi->mval[0] - tgpi->mvalo[0]);
1243                                         float dy = (tgpi->mval[1] - tgpi->mvalo[1]);
1244                                         tgpi->cp2[0] += dx;
1245                                         tgpi->cp2[1] += dy;
1246                                         if (event->shift)
1247                                                 copy_v2_v2(tgpi->cp1, tgpi->cp2);
1248                                 }
1249                                 /* update screen */
1250                                 gpencil_primitive_update(C, op, tgpi);
1251                         }
1252                         break;
1253                 }
1254                 case LEFTMOUSE:
1255                 {
1256                         if ((event->val == KM_PRESS)) {
1257                                 /* find nearest cp based on stroke end points */
1258                                 if (move == MOVE_ENDS)
1259                                         tgpi->sel_cp = (a < b) ? SELECT_START : SELECT_END;
1260                                 else if (move == MOVE_CP)
1261                                         tgpi->sel_cp = (c < d) ? SELECT_CP1 : SELECT_CP2;
1262                                 else
1263                                         tgpi->sel_cp = SELECT_NONE;
1264                                 break;
1265                         }
1266                         else if ((event->val == KM_RELEASE) && (tgpi->flag == IN_PROGRESS)) {
1267                                 /* set control points and enter edit mode */
1268                                 tgpi->flag = IN_CURVE_EDIT;
1269                                 gp_primitive_update_cps(tgpi);
1270                                 gpencil_primitive_update(C, op, tgpi);
1271                         }
1272                         else {
1273                                 tgpi->sel_cp = SELECT_NONE;
1274                         }
1275                         break;
1276                 }
1277                 case MKEY:
1278                 {
1279                         if ((event->val == KM_PRESS) &&
1280                             (tgpi->curve) &&
1281                             (tgpi->orign_type == GP_STROKE_ARC))
1282                         {
1283                                 tgpi->flip ^= 1;
1284                                 gp_primitive_update_cps(tgpi);
1285                                 gpencil_primitive_update(C, op, tgpi);
1286                         }
1287                         break;
1288                 }
1289                 case EKEY:
1290                 {
1291                         if (tgpi->flag == IN_CURVE_EDIT && !ELEM(tgpi->type, GP_STROKE_BOX, GP_STROKE_CIRCLE)) {
1292                                 tgpi->flag = IN_PROGRESS;
1293                                 WM_cursor_modal_set(win, BC_NSEW_SCROLLCURSOR);
1294                                 gpencil_primitive_add_segment(tgpi);
1295                                 copy_v2_v2(tgpi->start, tgpi->end);
1296                                 copy_v2_v2(tgpi->origin, tgpi->start);
1297                                 gp_primitive_update_cps(tgpi);
1298                         }
1299                         break;
1300                 }
1301         }
1302 }
1303
1304 /* move */
1305 static void gpencil_primitive_move(tGPDprimitive *tgpi)
1306 {
1307         float move[2];
1308         sub_v2_v2v2(move, tgpi->mval, tgpi->mvalo);
1309
1310         bGPDstroke *gps = tgpi->gpf->strokes.first;
1311         tGPspoint *points2D = tgpi->points;
1312
1313         for (int i = 0; i < gps->totpoints; i++) {
1314                 tGPspoint *p2d = &points2D[i];
1315                 add_v2_v2(&p2d->x, move);
1316         }
1317
1318         add_v2_v2(tgpi->start, move);
1319         add_v2_v2(tgpi->end, move);
1320         add_v2_v2(tgpi->cp1, move);
1321         add_v2_v2(tgpi->cp2, move);
1322         add_v2_v2(tgpi->origin, move);
1323 }
1324
1325 /* Modal handler: Events handling during interactive part */
1326 static int gpencil_primitive_modal(bContext *C, wmOperator *op, const wmEvent *event)
1327 {
1328         tGPDprimitive *tgpi = op->customdata;
1329         wmWindow *win = CTX_wm_window(C);
1330         const bool has_numinput = hasNumInput(&tgpi->num);
1331
1332         copy_v2fl_v2i(tgpi->mval, event->mval);
1333
1334         if (tgpi->flag == IN_MOVE) {
1335
1336                 switch (event->type) {
1337                         case MOUSEMOVE:
1338                                 gpencil_primitive_move(tgpi);
1339                                 gpencil_primitive_update(C, op, tgpi);
1340                                 break;
1341                         case ESCKEY:
1342                         case RIGHTMOUSE:
1343                         case LEFTMOUSE:
1344                                 tgpi->flag = IN_CURVE_EDIT;
1345                                 break;
1346                 }
1347                 copy_v2_v2(tgpi->mvalo, tgpi->mval);
1348                 return OPERATOR_RUNNING_MODAL;
1349         }
1350         else if (tgpi->flag != IDLE) {
1351                 gpencil_primitive_edit_event_handling(C, op, win, event, tgpi);
1352         }
1353
1354         switch (event->type) {
1355                 case LEFTMOUSE:
1356                 {
1357                         if ((event->val == KM_PRESS) && (tgpi->flag == IDLE)) {
1358                                 /* start drawing primitive */
1359                                 /* TODO: Ignore if not in main region yet */
1360                                 tgpi->flag = IN_PROGRESS;
1361                                 gpencil_primitive_interaction_begin(tgpi, event);
1362                         }
1363                         else if ((event->val == KM_RELEASE) && (tgpi->flag == IN_MOVE)) {
1364                                 tgpi->flag = IN_CURVE_EDIT;
1365                         }
1366                         else if ((event->val == KM_RELEASE) && (tgpi->flag == IN_PROGRESS)) {
1367                                 /* set control points and enter edit mode */
1368                                 tgpi->flag = IN_CURVE_EDIT;
1369                                 gp_primitive_update_cps(tgpi);
1370                                 gpencil_primitive_update(C, op, tgpi);
1371                         }
1372                         else if ((event->val == KM_RELEASE) && (tgpi->flag == IN_PROGRESS) && (tgpi->type != GP_STROKE_CURVE)) {
1373                                 /* stop drawing primitive */
1374                                 tgpi->flag = IDLE;
1375                                 gpencil_primitive_interaction_end(C, op, win, tgpi);
1376                                 /* done! */
1377                                 return OPERATOR_FINISHED;
1378                         }
1379                         else {
1380                                 if (G.debug & G_DEBUG) {
1381                                         printf("GP Add Primitive Modal: LEFTMOUSE %d, Status = %d\n", event->val, tgpi->flag);
1382                                 }
1383                         }
1384                         break;
1385                 }
1386                 case SPACEKEY:  /* confirm */
1387                 case RETKEY:
1388                 {
1389                         tgpi->flag = IDLE;
1390                         gpencil_primitive_interaction_end(C, op, win, tgpi);
1391                         /* done! */
1392                         return OPERATOR_FINISHED;
1393                 }
1394                 case RIGHTMOUSE: /* cancel */
1395                 case ESCKEY:
1396                 {
1397                         /* return to normal cursor and header status */
1398                         ED_workspace_status_text(C, NULL);
1399                         WM_cursor_modal_restore(win);
1400
1401                         /* clean up temp data */
1402                         gpencil_primitive_exit(C, op);
1403
1404                         /* canceled! */
1405                         return OPERATOR_CANCELLED;
1406                 }
1407                 case PADPLUSKEY:
1408                 case WHEELUPMOUSE:
1409                 {
1410                         if ((event->val != KM_RELEASE)) {
1411                                 tgpi->tot_edges = tgpi->tot_edges + 1;
1412                                 CLAMP(tgpi->tot_edges, MIN_EDGES, MAX_EDGES);
1413                                 RNA_int_set(op->ptr, "edges", tgpi->tot_edges);
1414
1415                                 /* update screen */
1416                                 gpencil_primitive_update(C, op, tgpi);
1417                         }
1418                         break;
1419                 }
1420                 case PADMINUS:
1421                 case WHEELDOWNMOUSE:
1422                 {
1423                         if ((event->val != KM_RELEASE)) {
1424                                 tgpi->tot_edges = tgpi->tot_edges - 1;
1425                                 CLAMP(tgpi->tot_edges, MIN_EDGES, MAX_EDGES);
1426                                 RNA_int_set(op->ptr, "edges", tgpi->tot_edges);
1427
1428                                 /* update screen */
1429                                 gpencil_primitive_update(C, op, tgpi);
1430                         }
1431                         break;
1432                 }
1433                 case GKEY: /* grab mode */
1434                 {
1435                         if ((event->val == KM_PRESS)) {
1436                                 tgpi->flag = IN_MOVE;
1437                                 WM_cursor_modal_set(win, BC_NSEW_SCROLLCURSOR);
1438                         }
1439                         break;
1440                 }
1441                 case CKEY: /* curve mode */
1442                 {
1443                         if ((event->val == KM_PRESS) &&
1444                             (tgpi->orign_type == GP_STROKE_CURVE))
1445                         {
1446                                 switch (tgpi->type) {
1447                                         case GP_STROKE_CURVE:
1448                                                 tgpi->type = GP_STROKE_ARC;
1449                                                 break;
1450                                         default:
1451                                         case GP_STROKE_ARC:
1452                                                 tgpi->type = GP_STROKE_CURVE;
1453                                                 break;
1454                                 }
1455
1456                                 RNA_enum_set(op->ptr, "type", tgpi->type);
1457                                 gp_primitive_update_cps(tgpi);
1458                                 gpencil_primitive_update(C, op, tgpi);
1459                         }
1460                         break;
1461                 }
1462                 case TABKEY:
1463                 {
1464                         if (tgpi->flag == IN_CURVE_EDIT) {
1465                                 tgpi->flag = IN_PROGRESS;
1466                                 WM_cursor_modal_set(win, BC_NSEW_SCROLLCURSOR);
1467                                 gp_primitive_update_cps(tgpi);
1468                                 gpencil_primitive_update(C, op, tgpi);
1469                         }
1470                         break;
1471                 }
1472                 case MOUSEMOVE: /* calculate new position */
1473                 {
1474                         if (tgpi->flag == IN_CURVE_EDIT) {
1475                                 break;
1476                         }
1477                         /* only handle mousemove if not doing numinput */
1478                         if (has_numinput == false) {
1479                                 /* update position of mouse */
1480                                 copy_v2_v2(tgpi->end, tgpi->mval);
1481                                 copy_v2_v2(tgpi->start, tgpi->origin);
1482                                 if (tgpi->flag == IDLE) {
1483                                         copy_v2_v2(tgpi->origin, tgpi->mval);
1484                                 }
1485                                 /* Keep square if shift key */
1486                                 if (event->shift) {
1487                                         float x = tgpi->end[0] - tgpi->origin[0];
1488                                         float y = tgpi->end[1] - tgpi->origin[1];
1489                                         if (tgpi->type == GP_STROKE_LINE || tgpi->curve) {
1490                                                 float angle = fabsf(atan2f(y, x));
1491                                                 if (angle < 0.4f || angle > (M_PI - 0.4f)) {
1492                                                         tgpi->end[1] = tgpi->origin[1];
1493                                                 }
1494                                                 else if (angle > (M_PI_2 - 0.4f) && angle < (M_PI_2 + 0.4f)) {
1495                                                         tgpi->end[0] = tgpi->origin[0];
1496                                                 }
1497                                                 else {
1498                                                         gpencil_primitive_to_square(tgpi, x, y);
1499                                                 }
1500                                         }
1501                                         else {
1502                                                 gpencil_primitive_to_square(tgpi, x, y);
1503                                         }
1504                                 }
1505                                 /* Center primitive if alt key */
1506                                 if (event->alt) {
1507                                         tgpi->start[0] = tgpi->origin[0] - (tgpi->end[0] - tgpi->origin[0]);
1508                                         tgpi->start[1] = tgpi->origin[1] - (tgpi->end[1] - tgpi->origin[1]);
1509                                 }
1510                                 gp_primitive_update_cps(tgpi);
1511                                 /* update screen */
1512                                 gpencil_primitive_update(C, op, tgpi);
1513                         }
1514                         break;
1515                 }
1516                 default:
1517                 {
1518                         if (tgpi->flag != IN_CURVE_EDIT && (event->val == KM_PRESS) && handleNumInput(C, &tgpi->num, event)) {
1519                                 float value;
1520
1521                                 /* Grab data from numeric input, and store this new value (the user see an int) */
1522                                 value = tgpi->tot_edges;
1523                                 applyNumInput(&tgpi->num, &value);
1524                                 tgpi->tot_edges = value;
1525
1526                                 CLAMP(tgpi->tot_edges, MIN_EDGES, MAX_EDGES);
1527                                 RNA_int_set(op->ptr, "edges", tgpi->tot_edges);
1528
1529                                 /* update screen */
1530                                 gpencil_primitive_update(C, op, tgpi);
1531
1532                                 break;
1533                         }
1534                         else {
1535                                 /* unhandled event - allow to pass through */
1536                                 return OPERATOR_RUNNING_MODAL | OPERATOR_PASS_THROUGH;
1537                         }
1538                 }
1539         }
1540
1541         copy_v2_v2(tgpi->mvalo, tgpi->mval);
1542         /* still running... */
1543         return OPERATOR_RUNNING_MODAL;
1544 }
1545
1546 /* Cancel handler */
1547 static void gpencil_primitive_cancel(bContext *C, wmOperator *op)
1548 {
1549         /* this is just a wrapper around exit() */
1550         gpencil_primitive_exit(C, op);
1551 }
1552
1553 void GPENCIL_OT_primitive(wmOperatorType *ot)
1554 {
1555         static EnumPropertyItem primitive_type[] = {
1556                 {GP_STROKE_BOX, "BOX", 0, "Box", ""},
1557                 {GP_STROKE_LINE, "LINE", 0, "Line", ""},
1558                 {GP_STROKE_CIRCLE, "CIRCLE", 0, "Circle", ""},
1559                 {GP_STROKE_ARC, "ARC", 0, "Arc", ""},
1560                 {GP_STROKE_CURVE, "CURVE", 0, "Curve", ""},
1561                 {0, NULL, 0, NULL, NULL}
1562         };
1563
1564         /* identifiers */
1565         ot->name = "Grease Pencil Shapes";
1566         ot->idname = "GPENCIL_OT_primitive";
1567         ot->description = "Create predefined grease pencil stroke shapes";
1568
1569         /* callbacks */
1570         ot->invoke = gpencil_primitive_invoke;
1571         ot->modal = gpencil_primitive_modal;
1572         ot->cancel = gpencil_primitive_cancel;
1573         ot->poll = gpencil_primitive_add_poll;
1574
1575         /* flags */
1576         ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
1577
1578         /* properties */
1579         PropertyRNA *prop;
1580
1581         prop = RNA_def_int(ot->srna, "edges", 4, MIN_EDGES, MAX_EDGES, "Edges", "Number of polygon edges", MIN_EDGES, MAX_EDGES);
1582         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1583
1584         RNA_def_enum(ot->srna, "type", primitive_type, GP_STROKE_BOX, "Type", "Type of shape");
1585
1586         prop = RNA_def_boolean(ot->srna, "wait_for_input", true, "Wait for Input", "");
1587         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1588 }