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