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