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