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