Fix T56199: Crash on Annotation in (VSE) Image Preview
[blender.git] / source / blender / editors / gpencil / annotate_paint.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) 2008/2018, Blender Foundation
19  * This is a new part of Blender
20  *
21  * Contributor(s): Joshua Leung
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/gpencil/annotate_paint.c
27  *  \ingroup edgpencil
28  */
29
30
31 #include <stdio.h>
32 #include <stddef.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <math.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_blenlib.h"
40 #include "BLI_math.h"
41 #include "BLI_utildefines.h"
42 #include "BLI_math_geom.h"
43
44 #include "BLT_translation.h"
45
46 #include "PIL_time.h"
47
48 #include "BKE_colortools.h"
49 #include "BKE_context.h"
50 #include "BKE_global.h"
51 #include "BKE_gpencil.h"
52 #include "BKE_main.h"
53 #include "BKE_report.h"
54 #include "BKE_screen.h"
55 #include "BKE_tracking.h"
56
57 #include "DNA_object_types.h"
58 #include "DNA_scene_types.h"
59 #include "DNA_gpencil_types.h"
60 #include "DNA_windowmanager_types.h"
61
62 #include "UI_view2d.h"
63
64 #include "ED_gpencil.h"
65 #include "ED_screen.h"
66 #include "ED_view3d.h"
67 #include "ED_clip.h"
68
69 #include "BIF_glutil.h"
70
71 #include "GPU_immediate.h"
72 #include "GPU_immediate_util.h"
73 #include "GPU_state.h"
74
75 #include "RNA_access.h"
76 #include "RNA_define.h"
77
78 #include "WM_api.h"
79 #include "WM_types.h"
80
81 #include "DEG_depsgraph.h"
82
83 #include "gpencil_intern.h"
84
85 /* ******************************************* */
86 /* 'Globals' and Defines */
87
88 /* values for tGPsdata->status */
89 typedef enum eGPencil_PaintStatus {
90         GP_STATUS_IDLING = 0,   /* stroke isn't in progress yet */
91         GP_STATUS_PAINTING,     /* a stroke is in progress */
92         GP_STATUS_ERROR,        /* something wasn't correctly set up */
93         GP_STATUS_DONE          /* painting done */
94 } eGPencil_PaintStatus;
95
96 /* Return flags for adding points to stroke buffer */
97 typedef enum eGP_StrokeAdd_Result {
98         GP_STROKEADD_INVALID    = -2,       /* error occurred - insufficient info to do so */
99         GP_STROKEADD_OVERFLOW   = -1,       /* error occurred - cannot fit any more points */
100         GP_STROKEADD_NORMAL,                /* point was successfully added */
101         GP_STROKEADD_FULL                   /* cannot add any more points to buffer */
102 } eGP_StrokeAdd_Result;
103
104 /* Runtime flags */
105 typedef enum eGPencil_PaintFlags {
106         GP_PAINTFLAG_FIRSTRUN       = (1 << 0),    /* operator just started */
107         GP_PAINTFLAG_STROKEADDED    = (1 << 1),
108         GP_PAINTFLAG_V3D_ERASER_DEPTH = (1 << 2),
109         GP_PAINTFLAG_SELECTMASK     = (1 << 3),
110 } eGPencil_PaintFlags;
111
112
113 /* Temporary 'Stroke' Operation data
114  *   "p" = op->customdata
115  */
116 typedef struct tGPsdata {
117         Main *bmain;
118         Scene *scene;       /* current scene from context */
119         struct Depsgraph *depsgraph;
120
121         wmWindow *win;      /* window where painting originated */
122         ScrArea *sa;        /* area where painting originated */
123         ARegion *ar;        /* region where painting originated */
124         View2D *v2d;        /* needed for GP_STROKE_2DSPACE */
125         rctf *subrect;      /* for using the camera rect within the 3d view */
126         rctf subrect_data;
127
128         GP_SpaceConversion gsc; /* settings to pass to gp_points_to_xy() */
129
130         PointerRNA ownerPtr; /* pointer to owner of gp-datablock */
131         bGPdata *gpd;       /* gp-datablock layer comes from */
132         bGPDlayer *gpl;     /* layer we're working on */
133         bGPDframe *gpf;     /* frame we're working on */
134
135         char *align_flag;   /* projection-mode flags (toolsettings - eGPencil_Placement_Flags) */
136
137         eGPencil_PaintStatus status;     /* current status of painting */
138         eGPencil_PaintModes  paintmode;  /* mode for painting */
139         eGPencil_PaintFlags  flags;      /* flags that can get set during runtime (eGPencil_PaintFlags) */
140
141         short radius;       /* radius of influence for eraser */
142
143         int mval[2];        /* current mouse-position */
144         int mvalo[2];       /* previous recorded mouse-position */
145
146         float pressure;     /* current stylus pressure */
147         float opressure;    /* previous stylus pressure */
148
149         /* These need to be doubles, as (at least under unix) they are in seconds since epoch,
150          * float (and its 7 digits precision) is definitively not enough here!
151          * double, with its 15 digits precision, ensures us millisecond precision for a few centuries at least.
152          */
153         double inittime;    /* Used when converting to path */
154         double curtime;     /* Used when converting to path */
155         double ocurtime;    /* Used when converting to path */
156
157         float imat[4][4];   /* inverted transformation matrix applying when converting coords from screen-space
158                              * to region space */
159         float mat[4][4];
160
161         float custom_color[4]; /* custom color - hack for enforcing a particular color for track/mask editing */
162
163         void *erasercursor; /* radial cursor data for drawing eraser */
164
165         short straight[2];   /* 1: line horizontal, 2: line vertical, other: not defined, second element position */
166         int lock_axis;       /* lock drawing to one axis */
167
168         short keymodifier;   /* key used for invoking the operator */
169 } tGPsdata;
170
171 /* ------ */
172
173 /* Macros for accessing sensitivity thresholds... */
174 /* minimum number of pixels mouse should move before new point created */
175 #define MIN_MANHATTEN_PX    (U.gp_manhattendist)
176 /* minimum length of new segment before new point can be added */
177 #define MIN_EUCLIDEAN_PX    (U.gp_euclideandist)
178
179 static bool gp_stroke_added_check(tGPsdata *p)
180 {
181         return (p->gpf && p->gpf->strokes.last && p->flags & GP_PAINTFLAG_STROKEADDED);
182 }
183
184 static void gp_stroke_added_enable(tGPsdata *p)
185 {
186         BLI_assert(p->gpf->strokes.last != NULL);
187         p->flags |= GP_PAINTFLAG_STROKEADDED;
188 }
189
190 /* ------ */
191 /* Forward defines for some functions... */
192
193 static void gp_session_validatebuffer(tGPsdata *p);
194
195 /* ******************************************* */
196 /* Context Wrangling... */
197
198 /* check if context is suitable for drawing */
199 static bool gpencil_draw_poll(bContext *C)
200 {
201         if (ED_operator_regionactive(C)) {
202                 /* check if current context can support GPencil data */
203                 if (ED_gpencil_data_get_pointers(C, NULL) != NULL) {
204                         /* check if Grease Pencil isn't already running */
205                         if (ED_gpencil_session_active() == 0)
206                                 return 1;
207                         else
208                                 CTX_wm_operator_poll_msg_set(C, "Annotation operator is already active");
209                 }
210                 else {
211                         CTX_wm_operator_poll_msg_set(C, "Failed to find Grease Pencil data to draw into");
212                 }
213         }
214         else {
215                 CTX_wm_operator_poll_msg_set(C, "Active region not set");
216         }
217
218         return 0;
219 }
220
221 /* check if projecting strokes into 3d-geometry in the 3D-View */
222 static bool gpencil_project_check(tGPsdata *p)
223 {
224         bGPdata *gpd = p->gpd;
225         return ((gpd->runtime.sbuffer_sflag & GP_STROKE_3DSPACE) && (*p->align_flag & (GP_PROJECT_DEPTH_VIEW | GP_PROJECT_DEPTH_STROKE)));
226 }
227
228 /* ******************************************* */
229 /* Calculations/Conversions */
230
231 /* Utilities --------------------------------- */
232
233 /* get the reference point for stroke-point conversions */
234 static void gp_get_3d_reference(tGPsdata *p, float vec[3])
235 {
236         View3D *v3d = p->sa->spacedata.first;
237         const float *fp = ED_view3d_cursor3d_get(p->scene, v3d)->location;
238
239         /* use 3D-cursor */
240         copy_v3_v3(vec, fp);
241 }
242
243 /* Stroke Editing ---------------------------- */
244
245 /* check if the current mouse position is suitable for adding a new point */
246 static bool gp_stroke_filtermval(tGPsdata *p, const int mval[2], int pmval[2])
247 {
248         int dx = abs(mval[0] - pmval[0]);
249         int dy = abs(mval[1] - pmval[1]);
250
251         /* if buffer is empty, just let this go through (i.e. so that dots will work) */
252         if (p->gpd->runtime.sbuffer_size == 0)
253                 return true;
254
255         /* check if mouse moved at least certain distance on both axes (best case)
256          *      - aims to eliminate some jitter-noise from input when trying to draw straight lines freehand
257          */
258         else if ((dx > MIN_MANHATTEN_PX) && (dy > MIN_MANHATTEN_PX))
259                 return true;
260
261         /* check if the distance since the last point is significant enough
262          *      - prevents points being added too densely
263          *      - distance here doesn't use sqrt to prevent slowness... we should still be safe from overflows though
264          */
265         else if ((dx * dx + dy * dy) > MIN_EUCLIDEAN_PX * MIN_EUCLIDEAN_PX)
266                 return true;
267
268         /* mouse 'didn't move' */
269         else
270                 return false;
271 }
272
273 /* reproject the points of the stroke to a plane locked to axis to avoid stroke offset */
274 static void gp_project_points_to_plane(RegionView3D *rv3d, bGPDstroke *gps, const float origin[3], const int axis)
275 {
276         float plane_normal[3];
277         float vn[3];
278
279         float ray[3];
280         float rpoint[3];
281
282         /* normal vector for a plane locked to axis */
283         zero_v3(plane_normal);
284         plane_normal[axis] = 1.0f;
285
286         /* Reproject the points in the plane */
287         for (int i = 0; i < gps->totpoints; i++) {
288                 bGPDspoint *pt = &gps->points[i];
289
290                 /* get a vector from the point with the current view direction of the viewport */
291                 ED_view3d_global_to_vector(rv3d, &pt->x, vn);
292
293                 /* calculate line extrem point to create a ray that cross the plane */
294                 mul_v3_fl(vn, -50.0f);
295                 add_v3_v3v3(ray, &pt->x, vn);
296
297                 /* if the line never intersect, the point is not changed */
298                 if (isect_line_plane_v3(rpoint, &pt->x, ray, origin, plane_normal)) {
299                         copy_v3_v3(&pt->x, rpoint);
300                 }
301         }
302 }
303
304 /* reproject stroke to plane locked to axis in 3d cursor location */
305 static void gp_reproject_toplane(tGPsdata *p, bGPDstroke *gps)
306 {
307         bGPdata *gpd = p->gpd;
308         float origin[3];
309         float cursor[3];
310         RegionView3D *rv3d = p->ar->regiondata;
311
312         /* verify the stroke mode is CURSOR 3d space mode */
313         if ((gpd->runtime.sbuffer_sflag & GP_STROKE_3DSPACE) == 0) {
314                 return;
315         }
316         if ((*p->align_flag & GP_PROJECT_VIEWSPACE) == 0) {
317                 return;
318         }
319         if ((*p->align_flag & GP_PROJECT_DEPTH_VIEW) || (*p->align_flag & GP_PROJECT_DEPTH_STROKE)) {
320                 return;
321         }
322
323         /* get 3d cursor and set origin for locked axis only. Uses axis-1 because the enum for XYZ start with 1 */
324         gp_get_3d_reference(p, cursor);
325         zero_v3(origin);
326         origin[p->lock_axis - 1] = cursor[p->lock_axis - 1];
327
328         gp_project_points_to_plane(rv3d, gps, origin, p->lock_axis - 1);
329 }
330
331 /* convert screen-coordinates to buffer-coordinates */
332 /* XXX this method needs a total overhaul! */
333 static void gp_stroke_convertcoords(tGPsdata *p, const int mval[2], float out[3], float *depth)
334 {
335         bGPdata *gpd = p->gpd;
336
337         /* in 3d-space - pt->x/y/z are 3 side-by-side floats */
338         if (gpd->runtime.sbuffer_sflag & GP_STROKE_3DSPACE) {
339                 if (gpencil_project_check(p) && (ED_view3d_autodist_simple(p->ar, mval, out, 0, depth))) {
340                         /* projecting onto 3D-Geometry
341                          *      - nothing more needs to be done here, since view_autodist_simple() has already done it
342                          */
343                 }
344                 else {
345                         float mval_prj[2];
346                         float rvec[3], dvec[3];
347                         float mval_f[2] = {UNPACK2(mval)};
348                         float zfac;
349
350                         /* Current method just converts each point in screen-coordinates to
351                          * 3D-coordinates using the 3D-cursor as reference. In general, this
352                          * works OK, but it could of course be improved.
353                          *
354                          * TODO:
355                          *      - investigate using nearest point(s) on a previous stroke as
356                          *        reference point instead or as offset, for easier stroke matching
357                          */
358
359                         gp_get_3d_reference(p, rvec);
360                         zfac = ED_view3d_calc_zfac(p->ar->regiondata, rvec, NULL);
361
362                         if (ED_view3d_project_float_global(p->ar, rvec, mval_prj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
363                                 sub_v2_v2v2(mval_f, mval_prj, mval_f);
364                                 ED_view3d_win_to_delta(p->ar, mval_f, dvec, zfac);
365                                 sub_v3_v3v3(out, rvec, dvec);
366                         }
367                         else {
368                                 zero_v3(out);
369                         }
370                 }
371         }
372
373         /* 2d - on 'canvas' (assume that p->v2d is set) */
374         else if ((gpd->runtime.sbuffer_sflag & GP_STROKE_2DSPACE) && (p->v2d)) {
375                 UI_view2d_region_to_view(p->v2d, mval[0], mval[1], &out[0], &out[1]);
376                 mul_v3_m4v3(out, p->imat, out);
377         }
378
379         /* 2d - relative to screen (viewport area) */
380         else {
381                 if (p->subrect == NULL) { /* normal 3D view */
382                         out[0] = (float)(mval[0]) / (float)(p->ar->winx) * 100;
383                         out[1] = (float)(mval[1]) / (float)(p->ar->winy) * 100;
384                 }
385                 else { /* camera view, use subrect */
386                         out[0] = ((mval[0] - p->subrect->xmin) / BLI_rctf_size_x(p->subrect)) * 100;
387                         out[1] = ((mval[1] - p->subrect->ymin) / BLI_rctf_size_y(p->subrect)) * 100;
388                 }
389         }
390 }
391
392 /* add current stroke-point to buffer (returns whether point was successfully added) */
393 static short gp_stroke_addpoint(
394         tGPsdata *p, const int mval[2], float pressure, double curtime)
395 {
396         bGPdata *gpd = p->gpd;
397         tGPspoint *pt;
398         ToolSettings *ts = p->scene->toolsettings;
399
400         /* check painting mode */
401         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
402                 /* straight lines only - i.e. only store start and end point in buffer */
403                 if (gpd->runtime.sbuffer_size == 0) {
404                         /* first point in buffer (start point) */
405                         pt = (tGPspoint *)(gpd->runtime.sbuffer);
406
407                         /* store settings */
408                         copy_v2_v2_int(&pt->x, mval);
409                         pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
410                         pt->strength = 1.0f;
411                         pt->time = (float)(curtime - p->inittime);
412
413                         /* increment buffer size */
414                         gpd->runtime.sbuffer_size++;
415                 }
416                 else {
417                         /* just reset the endpoint to the latest value
418                          *      - assume that pointers for this are always valid...
419                          */
420                         pt = ((tGPspoint *)(gpd->runtime.sbuffer) + 1);
421
422                         /* store settings */
423                         copy_v2_v2_int(&pt->x, mval);
424                         pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
425                         pt->strength = 1.0f;
426                         pt->time = (float)(curtime - p->inittime);
427
428                         /* now the buffer has 2 points (and shouldn't be allowed to get any larger) */
429                         gpd->runtime.sbuffer_size = 2;
430                 }
431
432                 /* can keep carrying on this way :) */
433                 return GP_STROKEADD_NORMAL;
434         }
435         else if (p->paintmode == GP_PAINTMODE_DRAW) { /* normal drawing */
436                 /* check if still room in buffer */
437                 if (gpd->runtime.sbuffer_size >= GP_STROKE_BUFFER_MAX)
438                         return GP_STROKEADD_OVERFLOW;
439
440                 /* get pointer to destination point */
441                 pt = ((tGPspoint *)(gpd->runtime.sbuffer) + gpd->runtime.sbuffer_size);
442
443                 /* store settings */
444                 copy_v2_v2_int(&pt->x, mval);
445                 pt->pressure = pressure;
446                 pt->strength = 1.0f;  /* unused for annotations, but initialise for easier conversions to GP Object */
447
448                 /* point time */
449                 pt->time = (float)(curtime - p->inittime);
450
451                 /* increment counters */
452                 gpd->runtime.sbuffer_size++;
453
454                 /* check if another operation can still occur */
455                 if (gpd->runtime.sbuffer_size == GP_STROKE_BUFFER_MAX)
456                         return GP_STROKEADD_FULL;
457                 else
458                         return GP_STROKEADD_NORMAL;
459         }
460         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
461                 /* get pointer to destination point */
462                 pt = (tGPspoint *)(gpd->runtime.sbuffer);
463
464                 /* store settings */
465                 copy_v2_v2_int(&pt->x, mval);
466                 pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
467                 pt->strength = 1.0f;
468                 pt->time = (float)(curtime - p->inittime);
469
470                 /* if there's stroke for this poly line session add (or replace last) point
471                  * to stroke. This allows to draw lines more interactively (see new segment
472                  * during mouse slide, e.g.)
473                  */
474                 if (gp_stroke_added_check(p)) {
475                         bGPDstroke *gps = p->gpf->strokes.last;
476                         bGPDspoint *pts;
477
478                         /* first time point is adding to temporary buffer -- need to allocate new point in stroke */
479                         if (gpd->runtime.sbuffer_size == 0) {
480                                 gps->points = MEM_reallocN(gps->points, sizeof(bGPDspoint) * (gps->totpoints + 1));
481                                 gps->totpoints++;
482                         }
483
484                         pts = &gps->points[gps->totpoints - 1];
485
486                         /* special case for poly lines: normally,
487                          * depth is needed only when creating new stroke from buffer,
488                          * but poly lines are converting to stroke instantly,
489                          * so initialize depth buffer before converting coordinates
490                          */
491                         if (gpencil_project_check(p)) {
492                                 View3D *v3d = p->sa->spacedata.first;
493
494                                 view3d_region_operator_needs_opengl(p->win, p->ar);
495                                 ED_view3d_autodist_init(
496                                         p->depsgraph, p->ar, v3d, (ts->annotate_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
497                         }
498
499                         /* convert screen-coordinates to appropriate coordinates (and store them) */
500                         gp_stroke_convertcoords(p, &pt->x, &pts->x, NULL);
501                         /* if axis locked, reproject to plane locked (only in 3d space) */
502                         if (p->lock_axis > GP_LOCKAXIS_NONE) {
503                                 gp_reproject_toplane(p, gps);
504                         }
505
506                         /* copy pressure and time */
507                         pts->pressure = pt->pressure;
508                         pts->strength = pt->strength;
509                         pts->time = pt->time;
510
511                         /* force fill recalc */
512                         gps->flag |= GP_STROKE_RECALC_CACHES;
513                 }
514
515                 /* increment counters */
516                 if (gpd->runtime.sbuffer_size == 0)
517                         gpd->runtime.sbuffer_size++;
518
519                 return GP_STROKEADD_NORMAL;
520         }
521
522         /* return invalid state for now... */
523         return GP_STROKEADD_INVALID;
524 }
525
526 /* simplify a stroke (in buffer) before storing it
527  *      - applies a reverse Chaikin filter
528  *      - code adapted from etch-a-ton branch
529  */
530 static void gp_stroke_simplify(tGPsdata *p)
531 {
532         bGPdata *gpd = p->gpd;
533         tGPspoint *old_points = (tGPspoint *)gpd->runtime.sbuffer;
534         short num_points = gpd->runtime.sbuffer_size;
535         short flag = gpd->runtime.sbuffer_sflag;
536         short i, j;
537
538         /* only simplify if simplification is enabled, and we're not doing a straight line */
539         if (!(U.gp_settings & GP_PAINT_DOSIMPLIFY) || (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT))
540                 return;
541
542         /* don't simplify if less than 4 points in buffer */
543         if ((num_points <= 4) || (old_points == NULL))
544                 return;
545
546         /* clear buffer (but don't free mem yet) so that we can write to it
547          *      - firstly set sbuffer to NULL, so a new one is allocated
548          *      - secondly, reset flag after, as it gets cleared auto
549          */
550         gpd->runtime.sbuffer = NULL;
551         gp_session_validatebuffer(p);
552         gpd->runtime.sbuffer_sflag = flag;
553
554 /* macro used in loop to get position of new point
555  *      - used due to the mixture of datatypes in use here
556  */
557 #define GP_SIMPLIFY_AVPOINT(offs, sfac) \
558         { \
559                 co[0] += (float)(old_points[offs].x * sfac); \
560                 co[1] += (float)(old_points[offs].y * sfac); \
561                 pressure += old_points[offs].pressure * sfac; \
562                 time += old_points[offs].time * sfac; \
563         } (void)0
564
565         /* XXX Here too, do not lose start and end points! */
566         gp_stroke_addpoint(p, &old_points->x, old_points->pressure, p->inittime + (double)old_points->time);
567         for (i = 0, j = 0; i < num_points; i++) {
568                 if (i - j == 3) {
569                         float co[2], pressure, time;
570                         int mco[2];
571
572                         /* initialize values */
573                         co[0] = 0.0f;
574                         co[1] = 0.0f;
575                         pressure = 0.0f;
576                         time = 0.0f;
577
578                         /* using macro, calculate new point */
579                         GP_SIMPLIFY_AVPOINT(j, -0.25f);
580                         GP_SIMPLIFY_AVPOINT(j + 1, 0.75f);
581                         GP_SIMPLIFY_AVPOINT(j + 2, 0.75f);
582                         GP_SIMPLIFY_AVPOINT(j + 3, -0.25f);
583
584                         /* set values for adding */
585                         mco[0] = (int)co[0];
586                         mco[1] = (int)co[1];
587
588                         /* ignore return values on this... assume to be ok for now */
589                         gp_stroke_addpoint(p, mco, pressure, p->inittime + (double)time);
590
591                         j += 2;
592                 }
593         }
594         gp_stroke_addpoint(p, &old_points[num_points - 1].x, old_points[num_points - 1].pressure,
595                            p->inittime + (double)old_points[num_points - 1].time);
596
597         /* free old buffer */
598         MEM_freeN(old_points);
599 }
600
601 /* make a new stroke from the buffer data */
602 static void gp_stroke_newfrombuffer(tGPsdata *p)
603 {
604         bGPdata *gpd = p->gpd;
605         bGPDlayer *gpl = p->gpl;
606         bGPDstroke *gps;
607         bGPDspoint *pt;
608         tGPspoint *ptc;
609         ToolSettings *ts = p->scene->toolsettings;
610
611         int i, totelem;
612         /* since strokes are so fine, when using their depth we need a margin otherwise they might get missed */
613         int depth_margin = (ts->annotate_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 4 : 0;
614
615         /* get total number of points to allocate space for
616          *      - drawing straight-lines only requires the endpoints
617          */
618         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT)
619                 totelem = (gpd->runtime.sbuffer_size >= 2) ? 2 : gpd->runtime.sbuffer_size;
620         else
621                 totelem = gpd->runtime.sbuffer_size;
622
623         /* exit with error if no valid points from this stroke */
624         if (totelem == 0) {
625                 if (G.debug & G_DEBUG)
626                         printf("Error: No valid points in stroke buffer to convert (tot=%d)\n", gpd->runtime.sbuffer_size);
627                 return;
628         }
629
630         /* special case for poly line -- for already added stroke during session
631          * coordinates are getting added to stroke immediately to allow more
632          * interactive behavior
633          */
634         if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
635                 if (gp_stroke_added_check(p)) {
636                         return;
637                 }
638         }
639
640         /* allocate memory for a new stroke */
641         gps = MEM_callocN(sizeof(bGPDstroke), "gp_stroke");
642
643         /* copy appropriate settings for stroke */
644         gps->totpoints = totelem;
645         gps->thickness = gpl->thickness;
646         gps->flag = gpd->runtime.sbuffer_sflag;
647         gps->inittime = p->inittime;
648
649         /* enable recalculation flag by default (only used if hq fill) */
650         gps->flag |= GP_STROKE_RECALC_CACHES;
651
652         /* allocate enough memory for a continuous array for storage points */
653         gps->points = MEM_callocN(sizeof(bGPDspoint) * gps->totpoints, "gp_stroke_points");
654         gps->tot_triangles = 0;
655
656         /* set pointer to first non-initialized point */
657         pt = gps->points + (gps->totpoints - totelem);
658
659         /* copy points from the buffer to the stroke */
660         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
661                 /* straight lines only -> only endpoints */
662                 {
663                         /* first point */
664                         ptc = gpd->runtime.sbuffer;
665
666                         /* convert screen-coordinates to appropriate coordinates (and store them) */
667                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
668                         /* if axis locked, reproject to plane locked (only in 3d space) */
669                         if (p->lock_axis > GP_LOCKAXIS_NONE) {
670                                 gp_reproject_toplane(p, gps);
671                         }
672                         /* copy pressure and time */
673                         pt->pressure = ptc->pressure;
674                         pt->strength = ptc->strength;
675                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
676                         pt->time = ptc->time;
677
678                         pt++;
679                 }
680
681                 if (totelem == 2) {
682                         /* last point if applicable */
683                         ptc = ((tGPspoint *)gpd->runtime.sbuffer) + (gpd->runtime.sbuffer_size - 1);
684
685                         /* convert screen-coordinates to appropriate coordinates (and store them) */
686                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
687                         /* if axis locked, reproject to plane locked (only in 3d space) */
688                         if (p->lock_axis > GP_LOCKAXIS_NONE) {
689                                 gp_reproject_toplane(p, gps);
690                         }
691
692                         /* copy pressure and time */
693                         pt->pressure = ptc->pressure;
694                         pt->strength = ptc->strength;
695                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
696                         pt->time = ptc->time;
697                 }
698         }
699         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
700                 /* first point */
701                 ptc = gpd->runtime.sbuffer;
702
703                 /* convert screen-coordinates to appropriate coordinates (and store them) */
704                 gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
705                 /* if axis locked, reproject to plane locked (only in 3d space) */
706                 if (p->lock_axis > GP_LOCKAXIS_NONE) {
707                         gp_reproject_toplane(p, gps);
708                 }
709                 /* copy pressure and time */
710                 pt->pressure = ptc->pressure;
711                 pt->strength = ptc->strength;
712                 pt->time = ptc->time;
713         }
714         else {
715                 float *depth_arr = NULL;
716
717                 /* get an array of depths, far depths are blended */
718                 if (gpencil_project_check(p)) {
719                         int mval[2], mval_prev[2] = { 0 };
720                         int interp_depth = 0;
721                         int found_depth = 0;
722
723                         depth_arr = MEM_mallocN(sizeof(float) * gpd->runtime.sbuffer_size, "depth_points");
724
725                         for (i = 0, ptc = gpd->runtime.sbuffer; i < gpd->runtime.sbuffer_size; i++, ptc++, pt++) {
726                                 copy_v2_v2_int(mval, &ptc->x);
727
728                                 if ((ED_view3d_autodist_depth(p->ar, mval, depth_margin, depth_arr + i) == 0) &&
729                                     (i && (ED_view3d_autodist_depth_seg(p->ar, mval, mval_prev, depth_margin + 1, depth_arr + i) == 0)))
730                                 {
731                                         interp_depth = true;
732                                 }
733                                 else {
734                                         found_depth = true;
735                                 }
736
737                                 copy_v2_v2_int(mval_prev, mval);
738                         }
739
740                         if (found_depth == false) {
741                                 /* eeh... not much we can do.. :/, ignore depth in this case, use the 3D cursor */
742                                 for (i = gpd->runtime.sbuffer_size - 1; i >= 0; i--)
743                                         depth_arr[i] = 0.9999f;
744                         }
745                         else {
746                                 if (ts->annotate_v3d_align & GP_PROJECT_DEPTH_STROKE_ENDPOINTS) {
747                                         /* remove all info between the valid endpoints */
748                                         int first_valid = 0;
749                                         int last_valid = 0;
750
751                                         for (i = 0; i < gpd->runtime.sbuffer_size; i++) {
752                                                 if (depth_arr[i] != FLT_MAX)
753                                                         break;
754                                         }
755                                         first_valid = i;
756
757                                         for (i = gpd->runtime.sbuffer_size - 1; i >= 0; i--) {
758                                                 if (depth_arr[i] != FLT_MAX)
759                                                         break;
760                                         }
761                                         last_valid = i;
762
763                                         /* invalidate non-endpoints, so only blend between first and last */
764                                         for (i = first_valid + 1; i < last_valid; i++)
765                                                 depth_arr[i] = FLT_MAX;
766
767                                         interp_depth = true;
768                                 }
769
770                                 if (interp_depth) {
771                                         interp_sparse_array(depth_arr, gpd->runtime.sbuffer_size, FLT_MAX);
772                                 }
773                         }
774                 }
775
776
777                 pt = gps->points;
778
779                 /* convert all points (normal behavior) */
780                 for (i = 0, ptc = gpd->runtime.sbuffer; i < gpd->runtime.sbuffer_size && ptc; i++, ptc++, pt++) {
781                         /* convert screen-coordinates to appropriate coordinates (and store them) */
782                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, depth_arr ? depth_arr + i : NULL);
783
784                         /* copy pressure and time */
785                         pt->pressure = ptc->pressure;
786                         pt->strength = ptc->strength;
787                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
788                         pt->time = ptc->time;
789                 }
790
791                 /* if axis locked, reproject to plane locked (only in 3d space) */
792                 if (p->lock_axis > GP_LOCKAXIS_NONE) {
793                         gp_reproject_toplane(p, gps);
794                 }
795
796                 if (depth_arr)
797                         MEM_freeN(depth_arr);
798         }
799
800         /* add stroke to frame */
801         BLI_addtail(&p->gpf->strokes, gps);
802         gp_stroke_added_enable(p);
803 }
804
805 /* --- 'Eraser' for 'Paint' Tool ------ */
806
807 /* helper to free a stroke
808  * NOTE: gps->dvert and gps->triangles should be NULL, but check anyway for good measure
809  */
810 static void gp_free_stroke(bGPdata *UNUSED(gpd), bGPDframe *gpf, bGPDstroke *gps)
811 {
812         if (gps->points) {
813                 MEM_freeN(gps->points);
814         }
815
816         if (gps->dvert) {
817                 BKE_gpencil_free_stroke_weights(gps);
818                 MEM_freeN(gps->dvert);
819         }
820
821         if (gps->triangles) {
822                 MEM_freeN(gps->triangles);
823         }
824
825         BLI_freelinkN(&gpf->strokes, gps);
826 }
827
828
829 /* which which point is infront (result should only be used for comparison) */
830 static float view3d_point_depth(const RegionView3D *rv3d, const float co[3])
831 {
832         if (rv3d->is_persp) {
833                 return ED_view3d_calc_zfac(rv3d, co, NULL);
834         }
835         else {
836                 return -dot_v3v3(rv3d->viewinv[2], co);
837         }
838 }
839
840 /* only erase stroke points that are visible (3d view) */
841 static bool gp_stroke_eraser_is_occluded(tGPsdata *p, const bGPDspoint *pt, const int x, const int y)
842 {
843         if ((p->sa->spacetype == SPACE_VIEW3D) &&
844             (p->flags & GP_PAINTFLAG_V3D_ERASER_DEPTH))
845         {
846                 RegionView3D *rv3d = p->ar->regiondata;
847                 const int mval[2] = {x, y};
848                 float mval_3d[3];
849
850                 if (ED_view3d_autodist_simple(p->ar, mval, mval_3d, 0, NULL)) {
851                         const float depth_mval = view3d_point_depth(rv3d, mval_3d);
852                         const float depth_pt   = view3d_point_depth(rv3d, &pt->x);
853
854                         if (depth_pt > depth_mval) {
855                                 return true;
856                         }
857                 }
858         }
859         return false;
860 }
861
862 /* eraser tool - evaluation per stroke */
863 /* TODO: this could really do with some optimization (KD-Tree/BVH?) */
864 static void gp_stroke_eraser_dostroke(tGPsdata *p,
865                                       bGPDframe *gpf, bGPDstroke *gps,
866                                       const int mval[2], const int mvalo[2],
867                                       const int radius, const rcti *rect)
868 {
869         bGPDspoint *pt1, *pt2;
870         int pc1[2] = {0};
871         int pc2[2] = {0};
872         int i;
873
874         if (gps->totpoints == 0) {
875                 /* just free stroke */
876                 gp_free_stroke(p->gpd, gpf, gps);
877         }
878         else if (gps->totpoints == 1) {
879                 /* only process if it hasn't been masked out... */
880                 if (!(p->flags & GP_PAINTFLAG_SELECTMASK) || (gps->points->flag & GP_SPOINT_SELECT)) {
881                         gp_point_to_xy(&p->gsc, gps, gps->points, &pc1[0], &pc1[1]);
882
883                         /* do boundbox check first */
884                         if ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) {
885                                 /* only check if point is inside */
886                                 if (len_v2v2_int(mval, pc1) <= radius) {
887                                         /* free stroke */
888                                         gp_free_stroke(p->gpd, gpf, gps);
889                                 }
890                         }
891                 }
892         }
893         else {
894                 /* Perform culling? */
895                 bool do_cull = false;
896
897                 /* Clear Tags
898                  *
899                  * Note: It's better this way, as we are sure that
900                  * we don't miss anything, though things will be
901                  * slightly slower as a result
902                  */
903                 for (i = 0; i < gps->totpoints; i++) {
904                         bGPDspoint *pt = &gps->points[i];
905                         pt->flag &= ~GP_SPOINT_TAG;
906                 }
907
908                 /* First Pass: Loop over the points in the stroke
909                  *   1) Thin out parts of the stroke under the brush
910                  *   2) Tag "too thin" parts for removal (in second pass)
911                  */
912                 for (i = 0; (i + 1) < gps->totpoints; i++) {
913                         /* get points to work with */
914                         pt1 = gps->points + i;
915                         pt2 = gps->points + i + 1;
916
917                         /* only process if it hasn't been masked out... */
918                         if ((p->flags & GP_PAINTFLAG_SELECTMASK) && !(gps->points->flag & GP_SPOINT_SELECT))
919                                 continue;
920
921                         gp_point_to_xy(&p->gsc, gps, pt1, &pc1[0], &pc1[1]);
922                         gp_point_to_xy(&p->gsc, gps, pt2, &pc2[0], &pc2[1]);
923
924                         /* Check that point segment of the boundbox of the eraser stroke */
925                         if (((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) ||
926                             ((!ELEM(V2D_IS_CLIPPED, pc2[0], pc2[1])) && BLI_rcti_isect_pt(rect, pc2[0], pc2[1])))
927                         {
928                                 /* Check if point segment of stroke had anything to do with
929                                  * eraser region  (either within stroke painted, or on its lines)
930                                  *  - this assumes that linewidth is irrelevant
931                                  */
932                                 if (gp_stroke_inside_circle(mval, mvalo, radius, pc1[0], pc1[1], pc2[0], pc2[1])) {
933                                         if ((gp_stroke_eraser_is_occluded(p, pt1, pc1[0], pc1[1]) == false) ||
934                                             (gp_stroke_eraser_is_occluded(p, pt2, pc2[0], pc2[1]) == false))
935                                         {
936                                                 /* Edge is affected - Check individual points now */
937                                                 if (len_v2v2_int(mval, pc1) <= radius) {
938                                                         pt1->flag |= GP_SPOINT_TAG;
939                                                 }
940                                                 if (len_v2v2_int(mval, pc2) <= radius) {
941                                                         pt2->flag |= GP_SPOINT_TAG;
942                                                 }
943                                                 do_cull = true;
944                                         }
945                                 }
946                         }
947                 }
948
949                 /* Second Pass: Remove any points that are tagged */
950                 if (do_cull) {
951                         gp_stroke_delete_tagged_points(gpf, gps, gps->next, GP_SPOINT_TAG, false);
952                 }
953         }
954 }
955
956 /* erase strokes which fall under the eraser strokes */
957 static void gp_stroke_doeraser(tGPsdata *p)
958 {
959         bGPDframe *gpf = p->gpf;
960         bGPDstroke *gps, *gpn;
961         rcti rect;
962
963         /* rect is rectangle of eraser */
964         rect.xmin = p->mval[0] - p->radius;
965         rect.ymin = p->mval[1] - p->radius;
966         rect.xmax = p->mval[0] + p->radius;
967         rect.ymax = p->mval[1] + p->radius;
968
969         if (p->sa->spacetype == SPACE_VIEW3D) {
970                 if (p->flags & GP_PAINTFLAG_V3D_ERASER_DEPTH) {
971                         View3D *v3d = p->sa->spacedata.first;
972                         view3d_region_operator_needs_opengl(p->win, p->ar);
973                         ED_view3d_autodist_init(p->depsgraph, p->ar, v3d, 0);
974                 }
975         }
976
977         /* loop over strokes of active layer only (session init already took care of ensuring validity),
978          * checking segments for intersections to remove
979          */
980         for (gps = gpf->strokes.first; gps; gps = gpn) {
981                 gpn = gps->next;
982                 /* Not all strokes in the datablock may be valid in the current editor/context
983                  * (e.g. 2D space strokes in the 3D view, if the same datablock is shared)
984                  */
985                 if (ED_gpencil_stroke_can_use_direct(p->sa, gps)) {
986                         gp_stroke_eraser_dostroke(p, gpf, gps, p->mval, p->mvalo, p->radius, &rect);
987                 }
988         }
989 }
990
991 /* ******************************************* */
992 /* Sketching Operator */
993
994 /* clear the session buffers (call this before AND after a paint operation) */
995 static void gp_session_validatebuffer(tGPsdata *p)
996 {
997         bGPdata *gpd = p->gpd;
998
999         /* clear memory of buffer (or allocate it if starting a new session) */
1000         if (gpd->runtime.sbuffer) {
1001                 /* printf("\t\tGP - reset sbuffer\n"); */
1002                 memset(gpd->runtime.sbuffer, 0, sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX);
1003         }
1004         else {
1005                 /* printf("\t\tGP - allocate sbuffer\n"); */
1006                 gpd->runtime.sbuffer = MEM_callocN(sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX, "gp_session_strokebuffer");
1007         }
1008
1009         /* reset indices */
1010         gpd->runtime.sbuffer_size = 0;
1011
1012         /* reset flags */
1013         gpd->runtime.sbuffer_sflag = 0;
1014
1015         /* reset inittime */
1016         p->inittime = 0.0;
1017 }
1018
1019 /* (re)init new painting data */
1020 static bool gp_session_initdata(bContext *C, tGPsdata *p)
1021 {
1022         Main *bmain = CTX_data_main(C);
1023         bGPdata **gpd_ptr = NULL;
1024         ScrArea *curarea = CTX_wm_area(C);
1025         ARegion *ar = CTX_wm_region(C);
1026         ToolSettings *ts = CTX_data_tool_settings(C);
1027
1028         /* make sure the active view (at the starting time) is a 3d-view */
1029         if (curarea == NULL) {
1030                 p->status = GP_STATUS_ERROR;
1031                 if (G.debug & G_DEBUG)
1032                         printf("Error: No active view for painting\n");
1033                 return 0;
1034         }
1035
1036         /* pass on current scene and window */
1037         p->bmain = CTX_data_main(C);
1038         p->scene = CTX_data_scene(C);
1039         p->depsgraph = CTX_data_depsgraph(C);
1040         p->win = CTX_wm_window(C);
1041
1042         unit_m4(p->imat);
1043         unit_m4(p->mat);
1044
1045         switch (curarea->spacetype) {
1046                 /* supported views first */
1047                 case SPACE_VIEW3D:
1048                 {
1049                         /* View3D *v3d = curarea->spacedata.first; */
1050                         /* RegionView3D *rv3d = ar->regiondata; */
1051
1052                         /* set current area
1053                          *      - must verify that region data is 3D-view (and not something else)
1054                          */
1055                         /* CAUTION: If this is the "toolbar", then this will change on the first stroke */
1056                         p->sa = curarea;
1057                         p->ar = ar;
1058                         p->align_flag = &ts->annotate_v3d_align;
1059
1060                         if (ar->regiondata == NULL) {
1061                                 p->status = GP_STATUS_ERROR;
1062                                 if (G.debug & G_DEBUG)
1063                                         printf("Error: 3D-View active region doesn't have any region data, so cannot be drawable\n");
1064                                 return 0;
1065                         }
1066                         break;
1067                 }
1068                 case SPACE_NODE:
1069                 {
1070                         /* SpaceNode *snode = curarea->spacedata.first; */
1071
1072                         /* set current area */
1073                         p->sa = curarea;
1074                         p->ar = ar;
1075                         p->v2d = &ar->v2d;
1076                         p->align_flag = &ts->gpencil_v2d_align;
1077                         break;
1078                 }
1079                 case SPACE_SEQ:
1080                 {
1081                         SpaceSeq *sseq = curarea->spacedata.first;
1082
1083                         /* set current area */
1084                         p->sa = curarea;
1085                         p->ar = ar;
1086                         p->v2d = &ar->v2d;
1087                         p->align_flag = &ts->gpencil_seq_align;
1088
1089                         /* check that gpencil data is allowed to be drawn */
1090                         if (sseq->mainb == SEQ_DRAW_SEQUENCE) {
1091                                 p->status = GP_STATUS_ERROR;
1092                                 if (G.debug & G_DEBUG)
1093                                         printf("Error: In active view (sequencer), active mode doesn't support Grease Pencil\n");
1094                                 return 0;
1095                         }
1096                         break;
1097                 }
1098                 case SPACE_IMAGE:
1099                 {
1100                         /* SpaceImage *sima = curarea->spacedata.first; */
1101
1102                         /* set the current area */
1103                         p->sa = curarea;
1104                         p->ar = ar;
1105                         p->v2d = &ar->v2d;
1106                         p->align_flag = &ts->gpencil_ima_align;
1107                         break;
1108                 }
1109                 case SPACE_CLIP:
1110                 {
1111                         SpaceClip *sc = curarea->spacedata.first;
1112                         MovieClip *clip = ED_space_clip_get_clip(sc);
1113
1114                         if (clip == NULL) {
1115                                 p->status = GP_STATUS_ERROR;
1116                                 return false;
1117                         }
1118
1119                         /* set the current area */
1120                         p->sa = curarea;
1121                         p->ar = ar;
1122                         p->v2d = &ar->v2d;
1123                         p->align_flag = &ts->gpencil_v2d_align;
1124
1125                         invert_m4_m4(p->imat, sc->unistabmat);
1126
1127                         /* custom color for new layer */
1128                         p->custom_color[0] = 1.0f;
1129                         p->custom_color[1] = 0.0f;
1130                         p->custom_color[2] = 0.5f;
1131                         p->custom_color[3] = 0.9f;
1132
1133                         if (sc->gpencil_src == SC_GPENCIL_SRC_TRACK) {
1134                                 int framenr = ED_space_clip_get_clip_frame_number(sc);
1135                                 MovieTrackingTrack *track = BKE_tracking_track_get_active(&clip->tracking);
1136                                 MovieTrackingMarker *marker = track ? BKE_tracking_marker_get(track, framenr) : NULL;
1137
1138                                 if (marker) {
1139                                         p->imat[3][0] -= marker->pos[0];
1140                                         p->imat[3][1] -= marker->pos[1];
1141                                 }
1142                                 else {
1143                                         p->status = GP_STATUS_ERROR;
1144                                         return false;
1145                                 }
1146                         }
1147
1148                         invert_m4_m4(p->mat, p->imat);
1149                         copy_m4_m4(p->gsc.mat, p->mat);
1150                         break;
1151                 }
1152                 /* unsupported views */
1153                 default:
1154                 {
1155                         p->status = GP_STATUS_ERROR;
1156                         if (G.debug & G_DEBUG)
1157                                 printf("Error: Annotations are not supported in this editor\n");
1158                         return 0;
1159                 }
1160         }
1161
1162         /* get gp-data */
1163         gpd_ptr = ED_gpencil_data_get_pointers(C, &p->ownerPtr);
1164         if ((gpd_ptr == NULL) || !ED_gpencil_data_owner_is_annotation(&p->ownerPtr)) {
1165                 p->status = GP_STATUS_ERROR;
1166                 if (G.debug & G_DEBUG)
1167                         printf("Error: Current context doesn't allow for any Annotation data\n");
1168                 return 0;
1169         }
1170         else {
1171                 /* if no existing GPencil block exists, add one */
1172                 if (*gpd_ptr == NULL) {
1173                         bGPdata *gpd = BKE_gpencil_data_addnew(bmain, "Annotations");
1174                         *gpd_ptr = gpd;
1175
1176                         /* mark datablock as being used for annotations */
1177                         gpd->flag |= GP_DATA_ANNOTATIONS;
1178
1179                         /* annotations always in front of all objects */
1180                         gpd->xray_mode = GP_XRAY_FRONT;
1181                 }
1182                 p->gpd = *gpd_ptr;
1183         }
1184
1185         if (ED_gpencil_session_active() == 0) {
1186                 /* initialize undo stack,
1187                  * also, existing undo stack would make buffer drawn
1188                  */
1189                 gpencil_undo_init(p->gpd);
1190         }
1191
1192         /* clear out buffer (stored in gp-data), in case something contaminated it */
1193         gp_session_validatebuffer(p);
1194
1195         /* lock axis */
1196         p->lock_axis = ts->gp_sculpt.lock_axis;
1197
1198         return 1;
1199 }
1200
1201 /* init new painting session */
1202 static tGPsdata *gp_session_initpaint(bContext *C)
1203 {
1204         tGPsdata *p = NULL;
1205
1206         /* create new context data */
1207         p = MEM_callocN(sizeof(tGPsdata), "Annotation Drawing Data");
1208
1209         /* Try to initialise context data
1210          * WARNING: This may not always succeed (e.g. using GP in an annotation-only context)
1211          */
1212         if (gp_session_initdata(C, p) == 0) {
1213                 /* Invalid state - Exit
1214                  * NOTE: It should be safe to just free the data, since failing context checks should
1215                  * only happen when no data has been allocated.
1216                  */
1217                 MEM_freeN(p);
1218                 return NULL;
1219         }
1220
1221         /* Radius for eraser circle is defined in userprefs */
1222         /* NOTE: we do this here, so that if we exit immediately,
1223          *       erase size won't get lost
1224          */
1225         p->radius = U.gp_eraser;
1226
1227         /* return context data for running paint operator */
1228         return p;
1229 }
1230
1231 /* cleanup after a painting session */
1232 static void gp_session_cleanup(tGPsdata *p)
1233 {
1234         bGPdata *gpd = (p) ? p->gpd : NULL;
1235
1236         /* error checking */
1237         if (gpd == NULL)
1238                 return;
1239
1240         /* free stroke buffer */
1241         if (gpd->runtime.sbuffer) {
1242                 /* printf("\t\tGP - free sbuffer\n"); */
1243                 MEM_freeN(gpd->runtime.sbuffer);
1244                 gpd->runtime.sbuffer = NULL;
1245         }
1246
1247         /* clear flags */
1248         gpd->runtime.sbuffer_size = 0;
1249         gpd->runtime.sbuffer_sflag = 0;
1250         p->inittime = 0.0;
1251 }
1252
1253 static void gp_session_free(tGPsdata *p)
1254 {
1255         MEM_freeN(p);
1256 }
1257
1258
1259 /* init new stroke */
1260 static void gp_paint_initstroke(tGPsdata *p, eGPencil_PaintModes paintmode, Depsgraph *depsgraph)
1261 {
1262         Scene *scene = p->scene;
1263         ToolSettings *ts = scene->toolsettings;
1264
1265         /* get active layer (or add a new one if non-existent) */
1266         p->gpl = BKE_gpencil_layer_getactive(p->gpd);
1267         if (p->gpl == NULL) {
1268                 p->gpl = BKE_gpencil_layer_addnew(p->gpd, DATA_("Note"), true);
1269
1270                 if (p->custom_color[3])
1271                         copy_v3_v3(p->gpl->color, p->custom_color);
1272         }
1273         if (p->gpl->flag & GP_LAYER_LOCKED) {
1274                 p->status = GP_STATUS_ERROR;
1275                 if (G.debug & G_DEBUG)
1276                         printf("Error: Cannot paint on locked layer\n");
1277                 return;
1278         }
1279
1280         /* get active frame (add a new one if not matching frame) */
1281         if (paintmode == GP_PAINTMODE_ERASER) {
1282                 /* Eraser mode:
1283                  * 1) Only allow erasing on the active layer (unlike for 3d-art Grease Pencil),
1284                  *    since we won't be exposing layer locking in the UI
1285                  * 2) Ensure that p->gpf refers to the frame used for the active layer
1286                  *    (to avoid problems with other tools which expect it to exist)
1287                  */
1288                 bool has_layer_to_erase = false;
1289
1290                 if (gpencil_layer_is_editable(p->gpl)) {
1291                         /* Ensure that there's stuff to erase here (not including selection mask below)... */
1292                         if (p->gpl->actframe && p->gpl->actframe->strokes.first) {
1293                                 has_layer_to_erase = true;
1294                         }
1295                 }
1296
1297                 /* Ensure active frame is set correctly... */
1298                 p->gpf = p->gpl->actframe;
1299
1300                 /* Restrict eraser to only affecting selected strokes, if the "selection mask" is on
1301                  * (though this is only available in editmode)
1302                  */
1303                 if (p->gpd->flag & GP_DATA_STROKE_EDITMODE) {
1304                         if (ts->gp_sculpt.flag & GP_BRUSHEDIT_FLAG_SELECT_MASK) {
1305                                 p->flags |= GP_PAINTFLAG_SELECTMASK;
1306                         }
1307                 }
1308
1309                 if (has_layer_to_erase == false) {
1310                         p->status = GP_STATUS_ERROR;
1311                         //if (G.debug & G_DEBUG)
1312                                 printf("Error: Eraser will not be affecting anything (gpencil_paint_init)\n");
1313                         return;
1314                 }
1315         }
1316         else {
1317                 /* Drawing Modes - Add a new frame if needed on the active layer */
1318                 short add_frame_mode = GP_GETFRAME_ADD_NEW;
1319
1320                 if (ts->gpencil_flags & GP_TOOL_FLAG_RETAIN_LAST)
1321                         add_frame_mode = GP_GETFRAME_ADD_COPY;
1322                 else
1323                         add_frame_mode = GP_GETFRAME_ADD_NEW;
1324
1325                 p->gpf = BKE_gpencil_layer_getframe(p->gpl, CFRA, add_frame_mode);
1326
1327                 if (p->gpf == NULL) {
1328                         p->status = GP_STATUS_ERROR;
1329                         if (G.debug & G_DEBUG)
1330                                 printf("Error: No frame created (gpencil_paint_init)\n");
1331                         return;
1332                 }
1333                 else {
1334                         p->gpf->flag |= GP_FRAME_PAINT;
1335                 }
1336         }
1337
1338         /* set 'eraser' for this stroke if using eraser */
1339         p->paintmode = paintmode;
1340         if (p->paintmode == GP_PAINTMODE_ERASER) {
1341                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_ERASER;
1342
1343                 /* check if we should respect depth while erasing */
1344                 if (p->sa->spacetype == SPACE_VIEW3D) {
1345                         if (p->gpl->flag & GP_LAYER_NO_XRAY) {
1346                                 p->flags |= GP_PAINTFLAG_V3D_ERASER_DEPTH;
1347                         }
1348                 }
1349         }
1350         else {
1351                 /* disable eraser flags - so that we can switch modes during a session */
1352                 p->gpd->runtime.sbuffer_sflag &= ~GP_STROKE_ERASER;
1353
1354                 if (p->sa->spacetype == SPACE_VIEW3D) {
1355                         if (p->gpl->flag & GP_LAYER_NO_XRAY) {
1356                                 p->flags &= ~GP_PAINTFLAG_V3D_ERASER_DEPTH;
1357                         }
1358                 }
1359         }
1360
1361         /* set 'initial run' flag, which is only used to denote when a new stroke is starting */
1362         p->flags |= GP_PAINTFLAG_FIRSTRUN;
1363
1364
1365         /* when drawing in the camera view, in 2D space, set the subrect */
1366         p->subrect = NULL;
1367         if ((*p->align_flag & GP_PROJECT_VIEWSPACE) == 0) {
1368                 if (p->sa->spacetype == SPACE_VIEW3D) {
1369                         View3D *v3d = p->sa->spacedata.first;
1370                         RegionView3D *rv3d = p->ar->regiondata;
1371
1372                         /* for camera view set the subrect */
1373                         if (rv3d->persp == RV3D_CAMOB) {
1374                                 ED_view3d_calc_camera_border(p->scene, depsgraph, p->ar, v3d, rv3d, &p->subrect_data, true); /* no shift */
1375                                 p->subrect = &p->subrect_data;
1376                         }
1377                 }
1378         }
1379
1380         /* init stroke point space-conversion settings... */
1381         p->gsc.gpd = p->gpd;
1382         p->gsc.gpl = p->gpl;
1383
1384         p->gsc.sa = p->sa;
1385         p->gsc.ar = p->ar;
1386         p->gsc.v2d = p->v2d;
1387
1388         p->gsc.subrect_data = p->subrect_data;
1389         p->gsc.subrect = p->subrect;
1390
1391         copy_m4_m4(p->gsc.mat, p->mat);
1392
1393
1394         /* check if points will need to be made in view-aligned space */
1395         if (*p->align_flag & GP_PROJECT_VIEWSPACE) {
1396                 switch (p->sa->spacetype) {
1397                         case SPACE_VIEW3D:
1398                         {
1399                                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_3DSPACE;
1400                                 break;
1401                         }
1402                         case SPACE_NODE:
1403                         {
1404                                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_2DSPACE;
1405                                 break;
1406                         }
1407                         case SPACE_SEQ:
1408                         {
1409                                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_2DSPACE;
1410                                 break;
1411                         }
1412                         case SPACE_IMAGE:
1413                         {
1414                                 SpaceImage *sima = (SpaceImage *)p->sa->spacedata.first;
1415
1416                                 /* only set these flags if the image editor doesn't have an image active,
1417                                  * otherwise user will be confused by strokes not appearing after they're drawn
1418                                  *
1419                                  * Admittedly, this is a bit hacky, but it works much nicer from an ergonomic standpoint!
1420                                  */
1421                                 if (ELEM(NULL, sima, sima->image)) {
1422                                         /* make strokes be drawn in screen space */
1423                                         p->gpd->runtime.sbuffer_sflag &= ~GP_STROKE_2DSPACE;
1424                                         *(p->align_flag) &= ~GP_PROJECT_VIEWSPACE;
1425                                 }
1426                                 else {
1427                                         p->gpd->runtime.sbuffer_sflag |= GP_STROKE_2DSPACE;
1428                                 }
1429                                 break;
1430                         }
1431                         case SPACE_CLIP:
1432                         {
1433                                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_2DSPACE;
1434                                 break;
1435                         }
1436                 }
1437         }
1438 }
1439
1440 /* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
1441 static void gp_paint_strokeend(tGPsdata *p)
1442 {
1443         ToolSettings *ts = p->scene->toolsettings;
1444         /* for surface sketching, need to set the right OpenGL context stuff so that
1445          * the conversions will project the values correctly...
1446          */
1447         if (gpencil_project_check(p)) {
1448                 View3D *v3d = p->sa->spacedata.first;
1449
1450                 /* need to restore the original projection settings before packing up */
1451                 view3d_region_operator_needs_opengl(p->win, p->ar);
1452                 ED_view3d_autodist_init(p->depsgraph, p->ar, v3d, (ts->annotate_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
1453         }
1454
1455         /* check if doing eraser or not */
1456         if ((p->gpd->runtime.sbuffer_sflag & GP_STROKE_ERASER) == 0) {
1457                 /* simplify stroke before transferring? */
1458                 gp_stroke_simplify(p);
1459
1460                 /* transfer stroke to frame */
1461                 gp_stroke_newfrombuffer(p);
1462         }
1463
1464         /* clean up buffer now */
1465         gp_session_validatebuffer(p);
1466 }
1467
1468 /* finish off stroke painting operation */
1469 static void gp_paint_cleanup(tGPsdata *p)
1470 {
1471         /* p->gpd==NULL happens when stroke failed to initialize,
1472          * for example when GP is hidden in current space (sergey)
1473          */
1474         if (p->gpd) {
1475                 /* finish off a stroke */
1476                 gp_paint_strokeend(p);
1477         }
1478
1479         /* "unlock" frame */
1480         if (p->gpf)
1481                 p->gpf->flag &= ~GP_FRAME_PAINT;
1482 }
1483
1484 /* ------------------------------- */
1485
1486 /* Helper callback for drawing the cursor itself */
1487 static void gpencil_draw_eraser(bContext *UNUSED(C), int x, int y, void *p_ptr)
1488 {
1489         tGPsdata *p = (tGPsdata *)p_ptr;
1490
1491         if (p->paintmode == GP_PAINTMODE_ERASER) {
1492                 GPUVertFormat *format = immVertexFormat();
1493                 const uint shdr_pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
1494                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
1495
1496                 GPU_line_smooth(true);
1497                 GPU_blend(true);
1498                 GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
1499
1500                 immUniformColor4ub(255, 100, 100, 20);
1501                 imm_draw_circle_fill_2d(shdr_pos, x, y, p->radius, 40);
1502
1503                 immUnbindProgram();
1504
1505                 immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
1506
1507                 float viewport_size[4];
1508                 GPU_viewport_size_get_f(viewport_size);
1509                 immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
1510
1511                 immUniformColor4f(1.0f, 0.39f, 0.39f, 0.78f);
1512                 immUniform1i("colors_len", 0);  /* "simple" mode */
1513                 immUniform1f("dash_width", 12.0f);
1514                 immUniform1f("dash_factor", 0.5f);
1515
1516                 imm_draw_circle_wire_2d(shdr_pos, x, y, p->radius,
1517                                      /* XXX Dashed shader gives bad results with sets of small segments currently,
1518                                       *     temp hack around the issue. :( */
1519                                      max_ii(8, p->radius / 2));  /* was fixed 40 */
1520
1521                 immUnbindProgram();
1522
1523                 GPU_blend(false);
1524                 GPU_line_smooth(false);
1525         }
1526 }
1527
1528 /* Turn brush cursor in 3D view on/off */
1529 static void gpencil_draw_toggle_eraser_cursor(bContext *C, tGPsdata *p, short enable)
1530 {
1531         if (p->erasercursor && !enable) {
1532                 /* clear cursor */
1533                 WM_paint_cursor_end(CTX_wm_manager(C), p->erasercursor);
1534                 p->erasercursor = NULL;
1535         }
1536         else if (enable && !p->erasercursor) {
1537                 /* enable cursor */
1538                 p->erasercursor = WM_paint_cursor_activate(CTX_wm_manager(C),
1539                                                            NULL, /* XXX */
1540                                                            gpencil_draw_eraser, p);
1541         }
1542 }
1543
1544 /* Check if tablet eraser is being used (when processing events) */
1545 static bool gpencil_is_tablet_eraser_active(const wmEvent *event)
1546 {
1547         if (event->tablet_data) {
1548                 const wmTabletData *wmtab = event->tablet_data;
1549                 return (wmtab->Active == EVT_TABLET_ERASER);
1550         }
1551
1552         return false;
1553 }
1554
1555 /* ------------------------------- */
1556
1557 static void gpencil_draw_exit(bContext *C, wmOperator *op)
1558 {
1559         tGPsdata *p = op->customdata;
1560
1561         /* restore cursor to indicate end of drawing */
1562         WM_cursor_modal_restore(CTX_wm_window(C));
1563
1564         /* don't assume that operator data exists at all */
1565         if (p) {
1566                 /* check size of buffer before cleanup, to determine if anything happened here */
1567                 if (p->paintmode == GP_PAINTMODE_ERASER) {
1568                         /* turn off radial brush cursor */
1569                         gpencil_draw_toggle_eraser_cursor(C, p, false);
1570                 }
1571
1572                 /* always store the new eraser size to be used again next time
1573                  * NOTE: Do this even when not in eraser mode, as eraser may
1574                  *       have been toggled at some point.
1575                  */
1576                 U.gp_eraser = p->radius;
1577
1578                 /* clear undo stack */
1579                 gpencil_undo_finish();
1580
1581                 /* cleanup */
1582                 gp_paint_cleanup(p);
1583                 gp_session_cleanup(p);
1584                 gp_session_free(p);
1585                 p = NULL;
1586         }
1587
1588         op->customdata = NULL;
1589 }
1590
1591 static void gpencil_draw_cancel(bContext *C, wmOperator *op)
1592 {
1593         /* this is just a wrapper around exit() */
1594         gpencil_draw_exit(C, op);
1595 }
1596
1597 /* ------------------------------- */
1598
1599
1600 static int gpencil_draw_init(bContext *C, wmOperator *op, const wmEvent *event)
1601 {
1602         tGPsdata *p;
1603         eGPencil_PaintModes paintmode = RNA_enum_get(op->ptr, "mode");
1604
1605         /* check context */
1606         p = op->customdata = gp_session_initpaint(C);
1607         if ((p == NULL) || (p->status == GP_STATUS_ERROR)) {
1608                 /* something wasn't set correctly in context */
1609                 gpencil_draw_exit(C, op);
1610                 return 0;
1611         }
1612
1613         /* init painting data */
1614         gp_paint_initstroke(p, paintmode, CTX_data_depsgraph(C));
1615         if (p->status == GP_STATUS_ERROR) {
1616                 gpencil_draw_exit(C, op);
1617                 return 0;
1618         }
1619
1620         if (event != NULL) {
1621                 p->keymodifier = event->keymodifier;
1622         }
1623         else {
1624                 p->keymodifier = -1;
1625         }
1626
1627         /* everything is now setup ok */
1628         return 1;
1629 }
1630
1631
1632 /* ------------------------------- */
1633
1634 /* ensure that the correct cursor icon is set */
1635 static void gpencil_draw_cursor_set(tGPsdata *p)
1636 {
1637         if (p->paintmode == GP_PAINTMODE_ERASER)
1638                 WM_cursor_modal_set(p->win, BC_CROSSCURSOR);  /* XXX need a better cursor */
1639         else
1640                 WM_cursor_modal_set(p->win, BC_PAINTBRUSHCURSOR);
1641 }
1642
1643 /* update UI indicators of status, including cursor and header prints */
1644 static void gpencil_draw_status_indicators(bContext *C, tGPsdata *p)
1645 {
1646         /* header prints */
1647         switch (p->status) {
1648                 case GP_STATUS_PAINTING:
1649                         switch (p->paintmode) {
1650                                 case GP_PAINTMODE_DRAW_POLY:
1651                                         /* Provide usage tips, since this is modal, and unintuitive without hints */
1652                                         ED_workspace_status_text(C, IFACE_("Annotation Create Poly: LMB click to place next stroke vertex | "
1653                                                                           "ESC/Enter to end  (or click outside this area)"));
1654                                         break;
1655                                 default:
1656                                         /* Do nothing - the others are self explanatory, exit quickly once the mouse is released
1657                                          * Showing any text would just be annoying as it would flicker.
1658                                          */
1659                                         break;
1660                         }
1661                         break;
1662
1663                 case GP_STATUS_IDLING:
1664                         /* print status info */
1665                         switch (p->paintmode) {
1666                                 case GP_PAINTMODE_ERASER:
1667                                         ED_workspace_status_text(C, IFACE_("Annotation Eraser: Hold and drag LMB or RMB to erase | "
1668                                                                           "ESC/Enter to end  (or click outside this area)"));
1669                                         break;
1670                                 case GP_PAINTMODE_DRAW_STRAIGHT:
1671                                         ED_workspace_status_text(C, IFACE_("Annotation Line Draw: Hold and drag LMB to draw | "
1672                                                                           "ESC/Enter to end  (or click outside this area)"));
1673                                         break;
1674                                 case GP_PAINTMODE_DRAW:
1675                                         ED_workspace_status_text(C, IFACE_("Annotation Freehand Draw: Hold and drag LMB to draw | "
1676                                                                           "E/ESC/Enter to end  (or click outside this area)"));
1677                                         break;
1678                                 case GP_PAINTMODE_DRAW_POLY:
1679                                         ED_workspace_status_text(C, IFACE_("Annotation Create Poly: LMB click to place next stroke vertex | "
1680                                                                           "ESC/Enter to end  (or click outside this area)"));
1681                                         break;
1682
1683                                 default: /* unhandled future cases */
1684                                         ED_workspace_status_text(C, IFACE_("Annotation Session: ESC/Enter to end   (or click outside this area)"));
1685                                         break;
1686                         }
1687                         break;
1688
1689                 case GP_STATUS_ERROR:
1690                 case GP_STATUS_DONE:
1691                         /* clear status string */
1692                         ED_workspace_status_text(C, NULL);
1693                         break;
1694         }
1695 }
1696
1697 /* ------------------------------- */
1698
1699 /* create a new stroke point at the point indicated by the painting context */
1700 static void gpencil_draw_apply(wmOperator *op, tGPsdata *p, Depsgraph *depsgraph)
1701 {
1702         /* handle drawing/erasing -> test for erasing first */
1703         if (p->paintmode == GP_PAINTMODE_ERASER) {
1704                 /* do 'live' erasing now */
1705                 gp_stroke_doeraser(p);
1706
1707                 /* store used values */
1708                 p->mvalo[0] = p->mval[0];
1709                 p->mvalo[1] = p->mval[1];
1710                 p->opressure = p->pressure;
1711         }
1712         /* only add current point to buffer if mouse moved (even though we got an event, it might be just noise) */
1713         else if (gp_stroke_filtermval(p, p->mval, p->mvalo)) {
1714                 /* try to add point */
1715                 short ok = gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
1716
1717                 /* handle errors while adding point */
1718                 if ((ok == GP_STROKEADD_FULL) || (ok == GP_STROKEADD_OVERFLOW)) {
1719                         /* finish off old stroke */
1720                         gp_paint_strokeend(p);
1721                         /* And start a new one!!! Else, projection errors! */
1722                         gp_paint_initstroke(p, p->paintmode, depsgraph);
1723
1724                         /* start a new stroke, starting from previous point */
1725                         /* XXX Must manually reset inittime... */
1726                         /* XXX We only need to reuse previous point if overflow! */
1727                         if (ok == GP_STROKEADD_OVERFLOW) {
1728                                 p->inittime = p->ocurtime;
1729                                 gp_stroke_addpoint(p, p->mvalo, p->opressure, p->ocurtime);
1730                         }
1731                         else {
1732                                 p->inittime = p->curtime;
1733                         }
1734                         gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
1735                 }
1736                 else if (ok == GP_STROKEADD_INVALID) {
1737                         /* the painting operation cannot continue... */
1738                         BKE_report(op->reports, RPT_ERROR, "Cannot paint stroke");
1739                         p->status = GP_STATUS_ERROR;
1740
1741                         if (G.debug & G_DEBUG)
1742                                 printf("Error: Grease-Pencil Paint - Add Point Invalid\n");
1743                         return;
1744                 }
1745
1746                 /* store used values */
1747                 p->mvalo[0] = p->mval[0];
1748                 p->mvalo[1] = p->mval[1];
1749                 p->opressure = p->pressure;
1750                 p->ocurtime = p->curtime;
1751         }
1752 }
1753
1754 /* handle draw event */
1755 static void gpencil_draw_apply_event(wmOperator *op, const wmEvent *event, Depsgraph *depsgraph)
1756 {
1757         tGPsdata *p = op->customdata;
1758         PointerRNA itemptr;
1759         float mousef[2];
1760         int tablet = 0;
1761
1762         /* convert from window-space to area-space mouse coordinates
1763          * NOTE: float to ints conversions, +1 factor is probably used to ensure a bit more accurate rounding...
1764          */
1765         p->mval[0] = event->mval[0] + 1;
1766         p->mval[1] = event->mval[1] + 1;
1767
1768         /* verify key status for straight lines */
1769         if ((event->ctrl > 0) || (event->alt > 0)) {
1770                 if (p->straight[0] == 0) {
1771                         int dx = abs(p->mval[0] - p->mvalo[0]);
1772                         int dy = abs(p->mval[1] - p->mvalo[1]);
1773                         if ((dx > 0) || (dy > 0)) {
1774                                 /* check mouse direction to replace the other coordinate with previous values */
1775                                 if (dx >= dy) {
1776                                         /* horizontal */
1777                                         p->straight[0] = 1;
1778                                         p->straight[1] = p->mval[1]; /* save y */
1779                                 }
1780                                 else {
1781                                         /* vertical */
1782                                         p->straight[0] = 2;
1783                                         p->straight[1] = p->mval[0]; /* save x */
1784                                 }
1785                         }
1786                 }
1787         }
1788         else {
1789                 p->straight[0] = 0;
1790         }
1791
1792         p->curtime = PIL_check_seconds_timer();
1793
1794         /* handle pressure sensitivity (which is supplied by tablets) */
1795         if (event->tablet_data) {
1796                 const wmTabletData *wmtab = event->tablet_data;
1797
1798                 tablet = (wmtab->Active != EVT_TABLET_NONE);
1799                 p->pressure = wmtab->Pressure;
1800
1801                 /* Hack for pressure sensitive eraser on D+RMB when using a tablet:
1802                  *  The pen has to float over the tablet surface, resulting in
1803                  *  zero pressure (T47101). Ignore pressure values if floating
1804                  *  (i.e. "effectively zero" pressure), and only when the "active"
1805                  *  end is the stylus (i.e. the default when not eraser)
1806                  */
1807                 if (p->paintmode == GP_PAINTMODE_ERASER) {
1808                         if ((wmtab->Active != EVT_TABLET_ERASER) && (p->pressure < 0.001f)) {
1809                                 p->pressure = 1.0f;
1810                         }
1811                 }
1812         }
1813         else {
1814                 /* No tablet data -> No pressure info is available */
1815                 p->pressure = 1.0f;
1816         }
1817
1818         /* special exception for start of strokes (i.e. maybe for just a dot) */
1819         if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1820                 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1821
1822                 p->mvalo[0] = p->mval[0];
1823                 p->mvalo[1] = p->mval[1];
1824                 p->opressure = p->pressure;
1825                 p->inittime = p->ocurtime = p->curtime;
1826                 p->straight[0] = 0;
1827                 p->straight[1] = 0;
1828
1829                 /* special exception here for too high pressure values on first touch in
1830                  *  windows for some tablets, then we just skip first touch...
1831                  */
1832                 if (tablet && (p->pressure >= 0.99f))
1833                         return;
1834         }
1835
1836         /* check if alt key is pressed and limit to straight lines */
1837         if (p->straight[0] != 0) {
1838                 if (p->straight[0] == 1) {
1839                         /* horizontal */
1840                         p->mval[1] = p->straight[1]; /* replace y */
1841                 }
1842                 else {
1843                         /* vertical */
1844                         p->mval[0] = p->straight[1]; /* replace x */
1845                 }
1846         }
1847
1848         /* fill in stroke data (not actually used directly by gpencil_draw_apply) */
1849         RNA_collection_add(op->ptr, "stroke", &itemptr);
1850
1851         mousef[0] = p->mval[0];
1852         mousef[1] = p->mval[1];
1853         RNA_float_set_array(&itemptr, "mouse", mousef);
1854         RNA_float_set(&itemptr, "pressure", p->pressure);
1855         RNA_boolean_set(&itemptr, "is_start", (p->flags & GP_PAINTFLAG_FIRSTRUN) != 0);
1856
1857         RNA_float_set(&itemptr, "time", p->curtime - p->inittime);
1858
1859         /* apply the current latest drawing point */
1860         gpencil_draw_apply(op, p, depsgraph);
1861
1862         /* force refresh */
1863         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
1864 }
1865
1866 /* ------------------------------- */
1867
1868 /* operator 'redo' (i.e. after changing some properties, but also for repeat last) */
1869 static int gpencil_draw_exec(bContext *C, wmOperator *op)
1870 {
1871         tGPsdata *p = NULL;
1872         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1873
1874         /* printf("GPencil - Starting Re-Drawing\n"); */
1875
1876         /* try to initialize context data needed while drawing */
1877         if (!gpencil_draw_init(C, op, NULL)) {
1878                 if (op->customdata) MEM_freeN(op->customdata);
1879                 /* printf("\tGP - no valid data\n"); */
1880                 return OPERATOR_CANCELLED;
1881         }
1882         else
1883                 p = op->customdata;
1884
1885         /* printf("\tGP - Start redrawing stroke\n"); */
1886
1887         /* loop over the stroke RNA elements recorded (i.e. progress of mouse movement),
1888          * setting the relevant values in context at each step, then applying
1889          */
1890         RNA_BEGIN (op->ptr, itemptr, "stroke")
1891         {
1892                 float mousef[2];
1893
1894                 /* printf("\t\tGP - stroke elem\n"); */
1895
1896                 /* get relevant data for this point from stroke */
1897                 RNA_float_get_array(&itemptr, "mouse", mousef);
1898                 p->mval[0] = (int)mousef[0];
1899                 p->mval[1] = (int)mousef[1];
1900                 p->pressure = RNA_float_get(&itemptr, "pressure");
1901                 p->curtime = (double)RNA_float_get(&itemptr, "time") + p->inittime;
1902
1903                 if (RNA_boolean_get(&itemptr, "is_start")) {
1904                         /* if first-run flag isn't set already (i.e. not true first stroke),
1905                          * then we must terminate the previous one first before continuing
1906                          */
1907                         if ((p->flags & GP_PAINTFLAG_FIRSTRUN) == 0) {
1908                                 /* TODO: both of these ops can set error-status, but we probably don't need to worry */
1909                                 gp_paint_strokeend(p);
1910                                 gp_paint_initstroke(p, p->paintmode, depsgraph);
1911                         }
1912                 }
1913
1914                 /* if first run, set previous data too */
1915                 if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1916                         p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1917
1918                         p->mvalo[0] = p->mval[0];
1919                         p->mvalo[1] = p->mval[1];
1920                         p->opressure = p->pressure;
1921                         p->ocurtime = p->curtime;
1922                 }
1923
1924                 /* apply this data as necessary now (as per usual) */
1925                 gpencil_draw_apply(op, p, depsgraph);
1926         }
1927         RNA_END;
1928
1929         /* printf("\tGP - done\n"); */
1930
1931         /* cleanup */
1932         gpencil_draw_exit(C, op);
1933
1934         /* refreshes */
1935         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
1936
1937         /* done */
1938         return OPERATOR_FINISHED;
1939 }
1940
1941 /* ------------------------------- */
1942
1943 /* start of interactive drawing part of operator */
1944 static int gpencil_draw_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1945 {
1946         Object *ob = CTX_data_active_object(C);
1947         tGPsdata *p = NULL;
1948
1949         /* GPXX Need a better solution */
1950         if ((ob != NULL) && (ob->type == OB_GPENCIL)) {
1951                 BKE_report(op->reports, RPT_ERROR, "Cannot draw annotation with a Grease Pencil object active");
1952                 return OPERATOR_CANCELLED;
1953         }
1954
1955         if (G.debug & G_DEBUG)
1956                 printf("GPencil - Starting Drawing\n");
1957
1958         /* try to initialize context data needed while drawing */
1959         if (!gpencil_draw_init(C, op, event)) {
1960                 if (op->customdata)
1961                         MEM_freeN(op->customdata);
1962                 if (G.debug & G_DEBUG)
1963                         printf("\tGP - no valid data\n");
1964                 return OPERATOR_CANCELLED;
1965         }
1966         else
1967                 p = op->customdata;
1968
1969         /* TODO: set any additional settings that we can take from the events?
1970          * TODO? if tablet is erasing, force eraser to be on? */
1971
1972         /* TODO: move cursor setting stuff to stroke-start so that paintmode can be changed midway... */
1973
1974         /* if eraser is on, draw radial aid */
1975         if (p->paintmode == GP_PAINTMODE_ERASER) {
1976                 gpencil_draw_toggle_eraser_cursor(C, p, true);
1977         }
1978         /* set cursor
1979          * NOTE: This may change later (i.e. intentionally via brush toggle,
1980          *       or unintentionally if the user scrolls outside the area)...
1981          */
1982         gpencil_draw_cursor_set(p);
1983
1984         /* only start drawing immediately if we're allowed to do so... */
1985         if (RNA_boolean_get(op->ptr, "wait_for_input") == false) {
1986                 /* hotkey invoked - start drawing */
1987                 /* printf("\tGP - set first spot\n"); */
1988                 p->status = GP_STATUS_PAINTING;
1989
1990                 /* handle the initial drawing - i.e. for just doing a simple dot */
1991                 gpencil_draw_apply_event(op, event, CTX_data_depsgraph(C));
1992                 op->flag |= OP_IS_MODAL_CURSOR_REGION;
1993         }
1994         else {
1995                 /* toolbar invoked - don't start drawing yet... */
1996                 /* printf("\tGP - hotkey invoked... waiting for click-drag\n"); */
1997                 op->flag |= OP_IS_MODAL_CURSOR_REGION;
1998         }
1999
2000         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2001         /* add a modal handler for this operator, so that we can then draw continuous strokes */
2002         WM_event_add_modal_handler(C, op);
2003         return OPERATOR_RUNNING_MODAL;
2004 }
2005
2006 /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
2007 static bool gpencil_area_exists(bContext *C, ScrArea *sa_test)
2008 {
2009         bScreen *sc = CTX_wm_screen(C);
2010         return (BLI_findindex(&sc->areabase, sa_test) != -1);
2011 }
2012
2013 static tGPsdata *gpencil_stroke_begin(bContext *C, wmOperator *op)
2014 {
2015         tGPsdata *p = op->customdata;
2016
2017         /* we must check that we're still within the area that we're set up to work from
2018          * otherwise we could crash (see bug #20586)
2019          */
2020         if (CTX_wm_area(C) != p->sa) {
2021                 printf("\t\t\tGP - wrong area execution abort!\n");
2022                 p->status = GP_STATUS_ERROR;
2023         }
2024
2025         /* printf("\t\tGP - start stroke\n"); */
2026
2027         /* we may need to set up paint env again if we're resuming */
2028         /* XXX: watch it with the paintmode! in future,
2029          *      it'd be nice to allow changing paint-mode when in sketching-sessions */
2030
2031         if (gp_session_initdata(C, p))
2032                 gp_paint_initstroke(p, p->paintmode, CTX_data_depsgraph(C));
2033
2034         if (p->status != GP_STATUS_ERROR) {
2035                 p->status = GP_STATUS_PAINTING;
2036                 op->flag &= ~OP_IS_MODAL_CURSOR_REGION;
2037         }
2038
2039         return op->customdata;
2040 }
2041
2042 static void gpencil_stroke_end(wmOperator *op)
2043 {
2044         tGPsdata *p = op->customdata;
2045
2046         gp_paint_cleanup(p);
2047
2048         gpencil_undo_push(p->gpd);
2049
2050         gp_session_cleanup(p);
2051
2052         p->status = GP_STATUS_IDLING;
2053         op->flag |= OP_IS_MODAL_CURSOR_REGION;
2054
2055         p->gpd = NULL;
2056         p->gpl = NULL;
2057         p->gpf = NULL;
2058 }
2059
2060 /* events handling during interactive drawing part of operator */
2061 static int gpencil_draw_modal(bContext *C, wmOperator *op, const wmEvent *event)
2062 {
2063         tGPsdata *p = op->customdata;
2064         int estate = OPERATOR_PASS_THROUGH; /* default exit state - pass through to support MMB view nav, etc. */
2065
2066         /* if (event->type == NDOF_MOTION)
2067          *    return OPERATOR_PASS_THROUGH;
2068          * -------------------------------
2069          * [mce] Not quite what I was looking
2070          * for, but a good start! GP continues to
2071          * draw on the screen while the 3D mouse
2072          * moves the viewpoint. Problem is that
2073          * the stroke is converted to 3D only after
2074          * it is finished. This approach should work
2075          * better in tools that immediately apply
2076          * in 3D space.
2077          */
2078
2079         if (p->status == GP_STATUS_IDLING) {
2080                 ARegion *ar = CTX_wm_region(C);
2081                 p->ar = ar;
2082         }
2083
2084         /* we don't pass on key events, GP is used with key-modifiers - prevents Dkey to insert drivers */
2085         if (ISKEYBOARD(event->type)) {
2086                 if (ELEM(event->type, LEFTARROWKEY, DOWNARROWKEY, RIGHTARROWKEY, UPARROWKEY, ZKEY)) {
2087                         /* allow some keys:
2088                          *   - for frame changing [#33412]
2089                          *   - for undo (during sketching sessions)
2090                          */
2091                 }
2092                 else if (ELEM(event->type, PAD0, PAD1, PAD2, PAD3, PAD4, PAD5, PAD6, PAD7, PAD8, PAD9)) {
2093                         /* allow numpad keys so that camera/view manipulations can still take place
2094                          * - PAD0 in particular is really important for Grease Pencil drawing,
2095                          *   as animators may be working "to camera", so having this working
2096                          *   is essential for ensuring that they can quickly return to that view
2097                          */
2098                 }
2099                 else if ((event->type == BKEY) && (event->val == KM_RELEASE)) {
2100                         /* Add Blank Frame
2101                          * - Since this operator is non-modal, we can just call it here, and keep going...
2102                          * - This operator is especially useful when animating
2103                          */
2104                         WM_operator_name_call(C, "GPENCIL_OT_blank_frame_add", WM_OP_EXEC_DEFAULT, NULL);
2105                         estate = OPERATOR_RUNNING_MODAL;
2106                 }
2107                 else {
2108                         estate = OPERATOR_RUNNING_MODAL;
2109                 }
2110         }
2111
2112         //printf("\tGP - handle modal event...\n");
2113
2114         /* exit painting mode (and/or end current stroke)
2115          * NOTE: cannot do RIGHTMOUSE (as is standard for canceling) as that would break polyline [#32647]
2116          */
2117         if (ELEM(event->type, RETKEY, PADENTER, ESCKEY, SPACEKEY, EKEY)) {
2118                 /* exit() ends the current stroke before cleaning up */
2119                 /* printf("\t\tGP - end of paint op + end of stroke\n"); */
2120                 p->status = GP_STATUS_DONE;
2121                 estate = OPERATOR_FINISHED;
2122         }
2123
2124         /* toggle painting mode upon mouse-button movement
2125          *  - LEFTMOUSE  = standard drawing (all) / straight line drawing (all) / polyline (toolbox only)
2126          *  - RIGHTMOUSE = polyline (hotkey) / eraser (all)
2127          *    (Disabling RIGHTMOUSE case here results in bugs like [#32647])
2128          * also making sure we have a valid event value, to not exit too early
2129          */
2130         if (ELEM(event->type, LEFTMOUSE, RIGHTMOUSE) && (ELEM(event->val, KM_PRESS, KM_RELEASE))) {
2131                 /* if painting, end stroke */
2132                 if (p->status == GP_STATUS_PAINTING) {
2133                         int sketch = 0;
2134
2135                         /* basically, this should be mouse-button up = end stroke
2136                          * BUT, polyline drawing is an exception -- all knots should be added during one session
2137                          */
2138                         sketch |= (p->paintmode == GP_PAINTMODE_DRAW_POLY);
2139
2140                         if (sketch) {
2141                                 /* end stroke only, and then wait to resume painting soon */
2142                                 /* printf("\t\tGP - end stroke only\n"); */
2143                                 gpencil_stroke_end(op);
2144
2145                                 /* If eraser mode is on, turn it off after the stroke finishes
2146                                  * NOTE: This just makes it nicer to work with drawing sessions
2147                                  */
2148                                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2149                                         p->paintmode = RNA_enum_get(op->ptr, "mode");
2150
2151                                         /* if the original mode was *still* eraser,
2152                                          * we'll let it say for now, since this gives
2153                                          * users an opportunity to have visual feedback
2154                                          * when adjusting eraser size
2155                                          */
2156                                         if (p->paintmode != GP_PAINTMODE_ERASER) {
2157                                                 /* turn off cursor...
2158                                                  * NOTE: this should be enough for now
2159                                                  *       Just hiding this makes it seem like
2160                                                  *       you can paint again...
2161                                                  */
2162                                                 gpencil_draw_toggle_eraser_cursor(C, p, false);
2163                                         }
2164                                 }
2165
2166                                 /* we've just entered idling state, so this event was processed (but no others yet) */
2167                                 estate = OPERATOR_RUNNING_MODAL;
2168
2169                                 /* stroke could be smoothed, send notifier to refresh screen */
2170                                 WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2171                         }
2172                         else {
2173                                 /* printf("\t\tGP - end of stroke + op\n"); */
2174                                 p->status = GP_STATUS_DONE;
2175                                 estate = OPERATOR_FINISHED;
2176                         }
2177                 }
2178                 else if (event->val == KM_PRESS) {
2179                         bool in_bounds = false;
2180
2181                         /* Check if we're outside the bounds of the active region
2182                          * NOTE: An exception here is that if launched from the toolbar,
2183                          *       whatever region we're now in should become the new region
2184                          */
2185                         if ((p->ar) && (p->ar->regiontype == RGN_TYPE_TOOLS)) {
2186                                 /* Change to whatever region is now under the mouse */
2187                                 ARegion *current_region = BKE_area_find_region_xy(p->sa, RGN_TYPE_ANY, event->x, event->y);
2188
2189                                 if (G.debug & G_DEBUG) {
2190                                         printf("found alternative region %p (old was %p) - at %d %d (sa: %d %d -> %d %d)\n",
2191                                                 current_region, p->ar, event->x, event->y,
2192                                                 p->sa->totrct.xmin, p->sa->totrct.ymin, p->sa->totrct.xmax, p->sa->totrct.ymax);
2193                                 }
2194
2195                                 if (current_region) {
2196                                         /* Assume that since we found the cursor in here, it is in bounds
2197                                          * and that this should be the region that we begin drawing in
2198                                          */
2199                                         p->ar = current_region;
2200                                         in_bounds = true;
2201                                 }
2202                                 else {
2203                                         /* Out of bounds, or invalid in some other way */
2204                                         p->status = GP_STATUS_ERROR;
2205                                         estate = OPERATOR_CANCELLED;
2206
2207                                         if (G.debug & G_DEBUG)
2208                                                 printf("%s: Region under cursor is out of bounds, so cannot be drawn on\n", __func__);
2209                                 }
2210                         }
2211                         else if (p->ar) {
2212                                 rcti region_rect;
2213
2214                                 /* Perform bounds check using  */
2215                                 ED_region_visible_rect(p->ar, &region_rect);
2216                                 in_bounds = BLI_rcti_isect_pt_v(&region_rect, event->mval);
2217                         }
2218                         else {
2219                                 /* No region */
2220                                 p->status = GP_STATUS_ERROR;
2221                                 estate = OPERATOR_CANCELLED;
2222
2223                                 if (G.debug & G_DEBUG)
2224                                         printf("%s: No active region found in GP Paint session data\n", __func__);
2225                         }
2226
2227                         if (in_bounds) {
2228                                 /* Switch paintmode (temporarily if need be) based on which button was used
2229                                  * NOTE: This is to make it more convenient to erase strokes when using drawing sessions
2230                                  */
2231                                 if ((event->type == RIGHTMOUSE) || gpencil_is_tablet_eraser_active(event)) {
2232                                         /* turn on eraser */
2233                                         p->paintmode = GP_PAINTMODE_ERASER;
2234                                 }
2235                                 else if (event->type == LEFTMOUSE) {
2236                                         /* restore drawmode to default */
2237                                         p->paintmode = RNA_enum_get(op->ptr, "mode");
2238                                 }
2239
2240                                 gpencil_draw_toggle_eraser_cursor(C, p, p->paintmode == GP_PAINTMODE_ERASER);
2241
2242                                 /* not painting, so start stroke (this should be mouse-button down) */
2243                                 p = gpencil_stroke_begin(C, op);
2244
2245                                 if (p->status == GP_STATUS_ERROR) {
2246                                         estate = OPERATOR_CANCELLED;
2247                                 }
2248                         }
2249                         else if (p->status != GP_STATUS_ERROR) {
2250                                 /* User clicked outside bounds of window while idling, so exit paintmode
2251                                  * NOTE: Don't enter this case if an error occurred while finding the
2252                                  *       region (as above)
2253                                  */
2254                                 p->status = GP_STATUS_DONE;
2255                                 estate = OPERATOR_FINISHED;
2256                         }
2257                 }
2258                 else if (event->val == KM_RELEASE) {
2259                         p->status = GP_STATUS_IDLING;
2260                         op->flag |= OP_IS_MODAL_CURSOR_REGION;
2261                 }
2262         }
2263
2264         /* handle mode-specific events */
2265         if (p->status == GP_STATUS_PAINTING) {
2266                 /* handle painting mouse-movements? */
2267                 if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) || (p->flags & GP_PAINTFLAG_FIRSTRUN)) {
2268                         /* handle drawing event */
2269                         /* printf("\t\tGP - add point\n"); */
2270                         gpencil_draw_apply_event(op, event, CTX_data_depsgraph(C));
2271
2272                         /* finish painting operation if anything went wrong just now */
2273                         if (p->status == GP_STATUS_ERROR) {
2274                                 printf("\t\t\t\tGP - add error done!\n");
2275                                 estate = OPERATOR_CANCELLED;
2276                         }
2277                         else {
2278                                 /* event handled, so just tag as running modal */
2279                                 /* printf("\t\t\t\tGP - add point handled!\n"); */
2280                                 estate = OPERATOR_RUNNING_MODAL;
2281                         }
2282                 }
2283                 /* eraser size */
2284                 else if ((p->paintmode == GP_PAINTMODE_ERASER) &&
2285                          ELEM(event->type, WHEELUPMOUSE, WHEELDOWNMOUSE, PADPLUSKEY, PADMINUS))
2286                 {
2287                         /* just resize the brush (local version)
2288                          * TODO: fix the hardcoded size jumps (set to make a visible difference) and hardcoded keys
2289                          */
2290                         /* printf("\t\tGP - resize eraser\n"); */
2291                         switch (event->type) {
2292                                 case WHEELDOWNMOUSE: /* larger */
2293                                 case PADPLUSKEY:
2294                                         p->radius += 5;
2295                                         break;
2296
2297                                 case WHEELUPMOUSE: /* smaller */
2298                                 case PADMINUS:
2299                                         p->radius -= 5;
2300
2301                                         if (p->radius <= 0)
2302                                                 p->radius = 1;
2303                                         break;
2304                         }
2305
2306                         /* force refresh */
2307                         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
2308
2309                         /* event handled, so just tag as running modal */
2310                         estate = OPERATOR_RUNNING_MODAL;
2311                 }
2312                 /* there shouldn't be any other events, but just in case there are, let's swallow them
2313                  * (i.e. to prevent problems with undo)
2314                  */
2315                 else {
2316                         /* swallow event to save ourselves trouble */
2317                         estate = OPERATOR_RUNNING_MODAL;
2318                 }
2319         }
2320
2321         /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
2322         if (0 == gpencil_area_exists(C, p->sa))
2323                 estate = OPERATOR_CANCELLED;
2324         else {
2325                 /* update status indicators - cursor, header, etc. */
2326                 gpencil_draw_status_indicators(C, p);
2327                 gpencil_draw_cursor_set(p); /* cursor may have changed outside our control - T44084 */
2328         }
2329
2330         /* process last operations before exiting */
2331         switch (estate) {
2332                 case OPERATOR_FINISHED:
2333                         /* one last flush before we're done */
2334                         gpencil_draw_exit(C, op);
2335                         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2336                         break;
2337
2338                 case OPERATOR_CANCELLED:
2339                         gpencil_draw_exit(C, op);
2340                         break;
2341
2342                 case OPERATOR_RUNNING_MODAL | OPERATOR_PASS_THROUGH:
2343                         /* event doesn't need to be handled */
2344 #if 0
2345                         printf("unhandled event -> %d (mmb? = %d | mmv? = %d)\n",
2346                                event->type, event->type == MIDDLEMOUSE, event->type==MOUSEMOVE);
2347 #endif
2348                         break;
2349         }
2350
2351         /* return status code */
2352         return estate;
2353 }
2354
2355 /* ------------------------------- */
2356
2357 static const EnumPropertyItem prop_gpencil_drawmodes[] = {
2358         {GP_PAINTMODE_DRAW, "DRAW", 0, "Draw Freehand", "Draw freehand stroke(s)"},
2359         {GP_PAINTMODE_DRAW_STRAIGHT, "DRAW_STRAIGHT", 0, "Draw Straight Lines", "Draw straight line segment(s)"},
2360         {GP_PAINTMODE_DRAW_POLY, "DRAW_POLY", 0, "Draw Poly Line", "Click to place endpoints of straight line segments (connected)"},
2361         {GP_PAINTMODE_ERASER, "ERASER", 0, "Eraser", "Erase Annotation strokes"},
2362         {0, NULL, 0, NULL, NULL}
2363 };
2364
2365 void GPENCIL_OT_annotate(wmOperatorType *ot)
2366 {
2367         PropertyRNA *prop;
2368
2369         /* identifiers */
2370         ot->name = "Annotation Draw";
2371         ot->idname = "GPENCIL_OT_annotate";
2372         ot->description = "Make annotations on the active data";
2373
2374         /* api callbacks */
2375         ot->exec = gpencil_draw_exec;
2376         ot->invoke = gpencil_draw_invoke;
2377         ot->modal = gpencil_draw_modal;
2378         ot->cancel = gpencil_draw_cancel;
2379         ot->poll = gpencil_draw_poll;
2380
2381         /* flags */
2382         ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
2383
2384         /* settings for drawing */
2385         ot->prop = RNA_def_enum(ot->srna, "mode", prop_gpencil_drawmodes, 0, "Mode", "Way to interpret mouse movements");
2386
2387         prop = RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2388         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
2389
2390         /* NOTE: wait for input is enabled by default, so that all UI code can work properly without needing users to know about this */
2391         prop = RNA_def_boolean(ot->srna, "wait_for_input", true, "Wait for Input", "Wait for first click instead of painting immediately");
2392         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2393 }