Cleanup: style
[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 #include "BLI_math_geom.h"
44
45 #include "BLT_translation.h"
46
47 #include "PIL_time.h"
48
49 #include "DNA_meshdata_types.h"
50 #include "DNA_object_types.h"
51 #include "DNA_scene_types.h"
52 #include "DNA_gpencil_types.h"
53 #include "DNA_material_types.h"
54 #include "DNA_brush_types.h"
55 #include "DNA_windowmanager_types.h"
56
57 #include "BKE_colortools.h"
58 #include "BKE_main.h"
59 #include "BKE_brush.h"
60 #include "BKE_paint.h"
61 #include "BKE_context.h"
62 #include "BKE_deform.h"
63 #include "BKE_global.h"
64 #include "BKE_gpencil.h"
65 #include "BKE_report.h"
66 #include "BKE_layer.h"
67 #include "BKE_material.h"
68 #include "BKE_screen.h"
69 #include "BKE_tracking.h"
70
71 #include "UI_view2d.h"
72
73 #include "ED_gpencil.h"
74 #include "ED_screen.h"
75 #include "ED_object.h"
76 #include "ED_view3d.h"
77 #include "ED_clip.h"
78
79 #include "BIF_glutil.h"
80
81 #include "GPU_immediate.h"
82 #include "GPU_immediate_util.h"
83 #include "GPU_state.h"
84
85 #include "RNA_access.h"
86 #include "RNA_define.h"
87
88 #include "WM_api.h"
89 #include "WM_types.h"
90
91 #include "DEG_depsgraph.h"
92 #include "DEG_depsgraph_query.h"
93
94 #include "gpencil_intern.h"
95
96   /* ******************************************* */
97   /* 'Globals' and Defines */
98
99   /* values for tGPsdata->status */
100 typedef enum eGPencil_PaintStatus {
101         GP_STATUS_IDLING = 0,   /* stroke isn't in progress yet */
102         GP_STATUS_PAINTING,     /* a stroke is in progress */
103         GP_STATUS_ERROR,        /* something wasn't correctly set up */
104         GP_STATUS_DONE          /* painting done */
105 } eGPencil_PaintStatus;
106
107 /* Return flags for adding points to stroke buffer */
108 typedef enum eGP_StrokeAdd_Result {
109         GP_STROKEADD_INVALID    = -2,       /* error occurred - insufficient info to do so */
110         GP_STROKEADD_OVERFLOW   = -1,       /* error occurred - cannot fit any more points */
111         GP_STROKEADD_NORMAL,                /* point was successfully added */
112         GP_STROKEADD_FULL                   /* cannot add any more points to buffer */
113 } eGP_StrokeAdd_Result;
114
115 /* Runtime flags */
116 typedef enum eGPencil_PaintFlags {
117         GP_PAINTFLAG_FIRSTRUN       = (1 << 0),    /* operator just started */
118         GP_PAINTFLAG_STROKEADDED    = (1 << 1),
119         GP_PAINTFLAG_V3D_ERASER_DEPTH = (1 << 2),
120         GP_PAINTFLAG_SELECTMASK     = (1 << 3),
121         GP_PAINTFLAG_HARD_ERASER    = (1 << 4),
122         GP_PAINTFLAG_STROKE_ERASER  = (1 << 5),
123 } eGPencil_PaintFlags;
124
125
126 /* Temporary 'Stroke' Operation data
127  *   "p" = op->customdata
128  */
129 typedef struct tGPsdata {
130         bContext *C;
131
132         Main *bmain;        /* main database pointer */
133         Scene *scene;       /* current scene from context */
134         struct Depsgraph *depsgraph;
135
136         Object *ob;         /* current object */
137         wmWindow *win;      /* window where painting originated */
138         ScrArea *sa;        /* area where painting originated */
139         ARegion *ar;        /* region where painting originated */
140         View2D *v2d;        /* needed for GP_STROKE_2DSPACE */
141         rctf *subrect;      /* for using the camera rect within the 3d view */
142         rctf subrect_data;
143
144         GP_SpaceConversion gsc; /* settings to pass to gp_points_to_xy() */
145
146         PointerRNA ownerPtr; /* pointer to owner of gp-datablock */
147         bGPdata *gpd;       /* gp-datablock layer comes from */
148         bGPDlayer *gpl;     /* layer we're working on */
149         bGPDframe *gpf;     /* frame we're working on */
150
151         char *align_flag;   /* projection-mode flags (toolsettings - eGPencil_Placement_Flags) */
152
153         eGPencil_PaintStatus status;     /* current status of painting */
154         eGPencil_PaintModes  paintmode;  /* mode for painting */
155         eGPencil_PaintFlags  flags;      /* flags that can get set during runtime (eGPencil_PaintFlags) */
156
157         short radius;       /* radius of influence for eraser */
158
159         float mval[2];        /* current mouse-position */
160         float mvalo[2];       /* previous recorded mouse-position */
161
162         float pressure;     /* current stylus pressure */
163         float opressure;    /* previous stylus pressure */
164
165         /* These need to be doubles, as (at least under unix) they are in seconds since epoch,
166          * float (and its 7 digits precision) is definitively not enough here!
167          * double, with its 15 digits precision, ensures us millisecond precision for a few centuries at least.
168          */
169         double inittime;    /* Used when converting to path */
170         double curtime;     /* Used when converting to path */
171         double ocurtime;    /* Used when converting to path */
172
173         float imat[4][4];   /* inverted transformation matrix applying when converting coords from screen-space
174                                                  * to region space */
175         float mat[4][4];
176
177         float custom_color[4]; /* custom color - hack for enforcing a particular color for track/mask editing */
178
179         void *erasercursor; /* radial cursor data for drawing eraser */
180
181         /* mat settings are only used for 3D view */
182         Material *material;   /* current material */
183
184         Brush *brush;    /* current drawing brush */
185         Brush *eraser;   /* default eraser brush */
186         short straight[2];   /* 1: line horizontal, 2: line vertical, other: not defined, second element position */
187         int lock_axis;       /* lock drawing to one axis */
188         bool disable_fill;   /* the stroke is no fill mode */
189
190         RNG *rng;
191
192         short keymodifier;   /* key used for invoking the operator */
193         short shift;         /* shift modifier flag */
194
195         float totpixlen;     /* size in pixels for uv calculation */
196
197         ReportList *reports;
198 } tGPsdata;
199
200 /* ------ */
201
202 /* Macros for accessing sensitivity thresholds... */
203 /* minimum number of pixels mouse should move before new point created */
204 #define MIN_MANHATTEN_PX    (U.gp_manhattendist)
205 /* minimum length of new segment before new point can be added */
206 #define MIN_EUCLIDEAN_PX    (U.gp_euclideandist)
207
208 static void gp_update_cache(bGPdata *gpd)
209 {
210         if (gpd) {
211                 DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
212                 gpd->flag |= GP_DATA_CACHE_IS_DIRTY;
213         }
214 }
215
216 static bool gp_stroke_added_check(tGPsdata *p)
217 {
218         return (p->gpf && p->gpf->strokes.last && p->flags & GP_PAINTFLAG_STROKEADDED);
219 }
220
221 static void gp_stroke_added_enable(tGPsdata *p)
222 {
223         BLI_assert(p->gpf->strokes.last != NULL);
224         p->flags |= GP_PAINTFLAG_STROKEADDED;
225
226         /* drawing batch cache is dirty now */
227         gp_update_cache(p->gpd);
228 }
229
230 /* ------ */
231 /* Forward defines for some functions... */
232
233 static void gp_session_validatebuffer(tGPsdata *p);
234
235 /* ******************************************* */
236 /* Context Wrangling... */
237
238 /* check if context is suitable for drawing */
239 static bool gpencil_draw_poll(bContext *C)
240 {
241         if (ED_operator_regionactive(C)) {
242                 ScrArea *sa = CTX_wm_area(C);
243                 if (!ELEM(sa->spacetype, SPACE_VIEW3D)) {
244                         /* check if current context can support GPencil data */
245                         if (ED_gpencil_data_get_pointers(C, NULL) != NULL) {
246                                 /* check if Grease Pencil isn't already running */
247                                 if (ED_gpencil_session_active() == 0)
248                                         return 1;
249                                 else
250                                         CTX_wm_operator_poll_msg_set(C, "Grease Pencil operator is already active");
251                         }
252                         else {
253                                 CTX_wm_operator_poll_msg_set(C, "Failed to find Grease Pencil data to draw into");
254                         }
255                         return 0;
256                 }
257                 /* 3D Viewport */
258                 else {
259                         if (ED_gpencil_session_active() == 0) {
260                                 return 1;
261                         }
262                         else {
263                                 return 0;
264                         }
265                 }
266         }
267         else {
268                 CTX_wm_operator_poll_msg_set(C, "Active region not set");
269                 return 0;
270         }
271 }
272
273 /* check if projecting strokes into 3d-geometry in the 3D-View */
274 static bool gpencil_project_check(tGPsdata *p)
275 {
276         bGPdata *gpd = p->gpd;
277         return ((gpd->runtime.sbuffer_sflag & GP_STROKE_3DSPACE) && (*p->align_flag & (GP_PROJECT_DEPTH_VIEW | GP_PROJECT_DEPTH_STROKE)));
278 }
279
280 /* ******************************************* */
281 /* Calculations/Conversions */
282
283 /* Utilities --------------------------------- */
284
285 /* get the reference point for stroke-point conversions */
286 static void gp_get_3d_reference(tGPsdata *p, float vec[3])
287 {
288         Object *ob = NULL;
289         if (p->ownerPtr.type == &RNA_Object) {
290                 ob = (Object *)p->ownerPtr.data;
291         }
292         ED_gp_get_drawing_reference(p->scene, ob, p->gpl, *p->align_flag, vec);
293 }
294
295 /* Stroke Editing ---------------------------- */
296 /* check if the current mouse position is suitable for adding a new point */
297 static bool gp_stroke_filtermval(tGPsdata *p, const float mval[2], float pmval[2])
298 {
299         Brush *brush = p->brush;
300         int dx = (int)fabsf(mval[0] - pmval[0]);
301         int dy = (int)fabsf(mval[1] - pmval[1]);
302         brush->gpencil_settings->flag &= ~GP_BRUSH_STABILIZE_MOUSE_TEMP;
303
304         /* if buffer is empty, just let this go through (i.e. so that dots will work) */
305         if (p->gpd->runtime.sbuffer_size == 0) {
306                 return true;
307         }
308         /* if lazy mouse, check minimum distance */
309         else if (GPENCIL_LAZY_MODE(brush, p->shift)) {
310                 brush->gpencil_settings->flag |= GP_BRUSH_STABILIZE_MOUSE_TEMP;
311                 if ((dx * dx + dy * dy) > (brush->smooth_stroke_radius * brush->smooth_stroke_radius)) {
312                         return true;
313                 }
314                 else {
315                         /* If the mouse is moving within the radius of the last move,
316                          * don't update the mouse position. This allows sharp turns. */
317                         copy_v2_v2(p->mval, p->mvalo);
318                         return false;
319                 }
320         }
321         /* check if mouse moved at least certain distance on both axes (best case)
322          * - aims to eliminate some jitter-noise from input when trying to draw straight lines freehand
323          */
324         else if ((dx > MIN_MANHATTEN_PX) && (dy > MIN_MANHATTEN_PX))
325                 return true;
326
327         /* check if the distance since the last point is significant enough
328          * - prevents points being added too densely
329          * - distance here doesn't use sqrt to prevent slowness... we should still be safe from overflows though
330          */
331         else if ((dx * dx + dy * dy) > MIN_EUCLIDEAN_PX * MIN_EUCLIDEAN_PX)
332                 return true;
333
334         /* mouse 'didn't move' */
335         else
336                 return false;
337 }
338
339 /* reproject stroke to plane locked to axis in 3d cursor location */
340 static void gp_reproject_toplane(tGPsdata *p, bGPDstroke *gps)
341 {
342         bGPdata *gpd = p->gpd;
343         Object *obact = (Object *)p->ownerPtr.data;
344
345         float origin[3];
346         RegionView3D *rv3d = p->ar->regiondata;
347
348         /* verify the stroke mode is CURSOR 3d space mode */
349         if ((gpd->runtime.sbuffer_sflag & GP_STROKE_3DSPACE) == 0) {
350                 return;
351         }
352         if ((*p->align_flag & GP_PROJECT_VIEWSPACE) == 0) {
353                 return;
354         }
355         if ((*p->align_flag & GP_PROJECT_DEPTH_VIEW) || (*p->align_flag & GP_PROJECT_DEPTH_STROKE)) {
356                 return;
357         }
358
359         /* get drawing origin */
360         gp_get_3d_reference(p, origin);
361         ED_gp_project_stroke_to_plane(obact, rv3d, gps, origin, p->lock_axis - 1);
362 }
363
364 /* convert screen-coordinates to buffer-coordinates */
365 /* XXX this method needs a total overhaul! */
366 static void gp_stroke_convertcoords(tGPsdata *p, const float mval[2], float out[3], float *depth)
367 {
368         bGPdata *gpd = p->gpd;
369
370         /* in 3d-space - pt->x/y/z are 3 side-by-side floats */
371         if (gpd->runtime.sbuffer_sflag & GP_STROKE_3DSPACE) {
372
373                 /* add small offset to keep stroke over the surface */
374                 if ((depth) && (gpd->zdepth_offset > 0.0f)) {
375                         *depth *= (1.0f - gpd->zdepth_offset);
376                 }
377
378                 int mval_i[2];
379                 round_v2i_v2fl(mval_i, mval);
380
381                 if (gpencil_project_check(p) && (ED_view3d_autodist_simple(p->ar, mval_i, out, 0, depth))) {
382                         /* projecting onto 3D-Geometry
383                          * - nothing more needs to be done here, since view_autodist_simple() has already done it
384                          */
385
386                          /* verify valid zdepth, if it's wrong, the default darwing mode is used
387                           * and the function doesn't return now */
388                         if ((depth == NULL) || (*depth <= 1.0f)) {
389                                 return;
390                         }
391                 }
392
393                 float mval_prj[2];
394                 float rvec[3], dvec[3];
395                 float mval_f[2];
396                 float zfac;
397
398                 /* Current method just converts each point in screen-coordinates to
399                  * 3D-coordinates using the 3D-cursor as reference. In general, this
400                  * works OK, but it could of course be improved.
401                  *
402                  * TODO:
403                  * - investigate using nearest point(s) on a previous stroke as
404                  *   reference point instead or as offset, for easier stroke matching
405                  */
406
407                 gp_get_3d_reference(p, rvec);
408                 zfac = ED_view3d_calc_zfac(p->ar->regiondata, rvec, NULL);
409
410                 if (ED_view3d_project_float_global(p->ar, rvec, mval_prj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
411                         sub_v2_v2v2(mval_f, mval_prj, mval);
412                         ED_view3d_win_to_delta(p->ar, mval_f, dvec, zfac);
413                         sub_v3_v3v3(out, rvec, dvec);
414                 }
415                 else {
416                         zero_v3(out);
417                 }
418         }
419 }
420
421 /* apply jitter to stroke */
422 static void gp_brush_jitter(
423         bGPdata *gpd, Brush *brush, tGPspoint *pt, const float mval[2],
424         const float pressure, float r_mval[2], RNG *rng)
425 {
426         float tmp_pressure = pressure;
427         if (brush->gpencil_settings->draw_jitter > 0.0f) {
428                 float curvef = curvemapping_evaluateF(brush->gpencil_settings->curve_jitter, 0, pressure);
429                 tmp_pressure = curvef * brush->gpencil_settings->draw_sensitivity;
430         }
431         const float exfactor = (brush->gpencil_settings->draw_jitter + 2.0f) * (brush->gpencil_settings->draw_jitter + 2.0f); /* exponential value */
432         const float fac = BLI_rng_get_float(rng) * exfactor * tmp_pressure;
433         /* Jitter is applied perpendicular to the mouse movement vector (2D space) */
434         float mvec[2], svec[2];
435         /* mouse movement in ints -> floats */
436         if (gpd->runtime.sbuffer_size > 1) {
437                 mvec[0] = (mval[0] - (pt - 1)->x);
438                 mvec[1] = (mval[1] - (pt - 1)->y);
439                 normalize_v2(mvec);
440         }
441         else {
442                 mvec[0] = 0.0f;
443                 mvec[1] = 0.0f;
444         }
445         /* rotate mvec by 90 degrees... */
446         svec[0] = -mvec[1];
447         svec[1] = mvec[0];
448         /* scale the displacement by the random, and apply */
449         if (BLI_rng_get_float(rng) > 0.5f) {
450                 mul_v2_fl(svec, -fac);
451         }
452         else {
453                 mul_v2_fl(svec, fac);
454         }
455
456         r_mval[0] = mval[0] + svec[0];
457         r_mval[1] = mval[1] + svec[1];
458
459 }
460
461 /* apply pressure change depending of the angle of the stroke to simulate a pen with shape */
462 static void gp_brush_angle(bGPdata *gpd, Brush *brush, tGPspoint *pt, const float mval[2])
463 {
464         float mvec[2];
465         float sen = brush->gpencil_settings->draw_angle_factor; /* sensitivity */;
466         float fac;
467         float mpressure;
468
469         float angle = brush->gpencil_settings->draw_angle; /* default angle of brush in radians */;
470         float v0[2] = { cos(angle), sin(angle) }; /* angle vector of the brush with full thickness */
471
472         /* Apply to first point (only if there are 2 points because before no data to do it ) */
473         if (gpd->runtime.sbuffer_size == 1) {
474                 mvec[0] = (mval[0] - (pt - 1)->x);
475                 mvec[1] = (mval[1] - (pt - 1)->y);
476                 normalize_v2(mvec);
477
478                 /* uses > 1.0f to get a smooth transition in first point */
479                 fac = 1.4f - fabs(dot_v2v2(v0, mvec)); /* 0.0 to 1.0 */
480                 (pt - 1)->pressure = (pt - 1)->pressure - (sen * fac);
481
482                 CLAMP((pt - 1)->pressure, GPENCIL_ALPHA_OPACITY_THRESH, 1.0f);
483         }
484
485         /* apply from second point */
486         if (gpd->runtime.sbuffer_size >= 1) {
487                 mvec[0] = (mval[0] - (pt - 1)->x);
488                 mvec[1] = (mval[1] - (pt - 1)->y);
489                 normalize_v2(mvec);
490
491                 fac = 1.0f - fabs(dot_v2v2(v0, mvec)); /* 0.0 to 1.0 */
492                 /* interpolate with previous point for smoother transitions */
493                 mpressure = interpf(pt->pressure - (sen * fac), (pt - 1)->pressure, 0.3f);
494                 pt->pressure = mpressure;
495
496                 CLAMP(pt->pressure, GPENCIL_ALPHA_OPACITY_THRESH, 1.0f);
497         }
498
499 }
500
501 /* Apply smooth to buffer while drawing
502  * to smooth point C, use 2 before (A, B) and current point (D):
503  *
504  *   A----B-----C------D
505  *
506  * \param p: Temp data
507  * \param inf: Influence factor
508  * \param idx: Index of the last point (need minimum 3 points in the array)
509  */
510 static void gp_smooth_buffer(tGPsdata *p, float inf, int idx)
511 {
512         bGPdata *gpd = p->gpd;
513         short num_points = gpd->runtime.sbuffer_size;
514
515         /* Do nothing if not enough points to smooth out */
516         if ((num_points < 3) || (idx < 3) || (inf == 0.0f)) {
517                 return;
518         }
519
520         tGPspoint *points = (tGPspoint *)gpd->runtime.sbuffer;
521         float steps = 4.0f;
522         if (idx < 4) {
523                 steps--;
524         }
525
526         tGPspoint *pta = idx >= 4 ? &points[idx - 4] : NULL;
527         tGPspoint *ptb = idx >= 3 ? &points[idx - 3] : NULL;
528         tGPspoint *ptc = idx >= 2 ? &points[idx - 2] : NULL;
529         tGPspoint *ptd = &points[idx - 1];
530
531         float sco[2] = { 0.0f };
532         float a[2], b[2], c[2], d[2];
533         const float average_fac = 1.0f / steps;
534
535         /* Compute smoothed coordinate by taking the ones nearby */
536         if (pta) {
537                 copy_v2_v2(a, &pta->x);
538                 madd_v2_v2fl(sco, a, average_fac);
539         }
540         if (ptb) {
541                 copy_v2_v2(b, &ptb->x);
542                 madd_v2_v2fl(sco, b, average_fac);
543         }
544         if (ptc) {
545                 copy_v2_v2(c, &ptc->x);
546                 madd_v2_v2fl(sco, c, average_fac);
547         }
548         if (ptd) {
549                 copy_v2_v2(d, &ptd->x);
550                 madd_v2_v2fl(sco, d, average_fac);
551         }
552
553         /* Based on influence factor, blend between original and optimal smoothed coordinate */
554         interp_v2_v2v2(c, c, sco, inf);
555         copy_v2_v2(&ptc->x, c);
556 }
557
558 /* add current stroke-point to buffer (returns whether point was successfully added) */
559 static short gp_stroke_addpoint(
560         tGPsdata *p, const float mval[2], float pressure, double curtime)
561 {
562         bGPdata *gpd = p->gpd;
563         Brush *brush = p->brush;
564         tGPspoint *pt;
565         ToolSettings *ts = p->scene->toolsettings;
566         Object *obact = (Object *)p->ownerPtr.data;
567         Depsgraph *depsgraph = p->depsgraph;
568         RegionView3D *rv3d = p->ar->regiondata;
569         View3D *v3d = p->sa->spacedata.first;
570         MaterialGPencilStyle *gp_style = p->material->gp_style;
571         const int def_nr = obact->actdef - 1;
572         const bool have_weight = (bool)BLI_findlink(&obact->defbase, def_nr);
573
574         /* check painting mode */
575         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
576                 /* straight lines only - i.e. only store start and end point in buffer */
577                 if (gpd->runtime.sbuffer_size == 0) {
578                         /* first point in buffer (start point) */
579                         pt = (tGPspoint *)(gpd->runtime.sbuffer);
580
581                         /* store settings */
582                         copy_v2_v2(&pt->x, mval);
583                         pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
584                         pt->strength = 1.0f;
585                         pt->time = (float)(curtime - p->inittime);
586
587                         /* increment buffer size */
588                         gpd->runtime.sbuffer_size++;
589                 }
590                 else {
591                         /* just reset the endpoint to the latest value
592                          * - assume that pointers for this are always valid...
593                          */
594                         pt = ((tGPspoint *)(gpd->runtime.sbuffer) + 1);
595
596                         /* store settings */
597                         copy_v2_v2(&pt->x, mval);
598                         pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
599                         pt->strength = 1.0f;
600                         pt->time = (float)(curtime - p->inittime);
601
602                         /* now the buffer has 2 points (and shouldn't be allowed to get any larger) */
603                         gpd->runtime.sbuffer_size = 2;
604                 }
605
606                 /* can keep carrying on this way :) */
607                 return GP_STROKEADD_NORMAL;
608         }
609         else if (p->paintmode == GP_PAINTMODE_DRAW) { /* normal drawing */
610                 /* check if still room in buffer */
611                 if (gpd->runtime.sbuffer_size >= GP_STROKE_BUFFER_MAX)
612                         return GP_STROKEADD_OVERFLOW;
613
614                 /* get pointer to destination point */
615                 pt = ((tGPspoint *)(gpd->runtime.sbuffer) + gpd->runtime.sbuffer_size);
616
617                 /* store settings */
618                 /* pressure */
619                 if (brush->gpencil_settings->flag & GP_BRUSH_USE_PRESSURE) {
620                         float curvef = curvemapping_evaluateF(brush->gpencil_settings->curve_sensitivity, 0, pressure);
621                         pt->pressure = curvef * brush->gpencil_settings->draw_sensitivity;
622                 }
623                 else {
624                         pt->pressure = 1.0f;
625                 }
626
627                 /* Apply jitter to position */
628                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
629                     (brush->gpencil_settings->draw_jitter > 0.0f))
630                 {
631                         float r_mval[2];
632                         const float jitpress = (brush->gpencil_settings->flag & GP_BRUSH_USE_JITTER_PRESSURE) ? pressure : 1.0f;
633                         gp_brush_jitter(gpd, brush, pt, mval, jitpress, r_mval, p->rng);
634                         copy_v2_v2(&pt->x, r_mval);
635                 }
636                 else {
637                         copy_v2_v2(&pt->x, mval);
638                 }
639                 /* apply randomness to pressure */
640                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
641                     (brush->gpencil_settings->draw_random_press > 0.0f))
642                 {
643                         float curvef = curvemapping_evaluateF(brush->gpencil_settings->curve_sensitivity, 0, pressure);
644                         float tmp_pressure = curvef * brush->gpencil_settings->draw_sensitivity;
645                         if (BLI_rng_get_float(p->rng) > 0.5f) {
646                                 pt->pressure -= tmp_pressure * brush->gpencil_settings->draw_random_press * BLI_rng_get_float(p->rng);
647                         }
648                         else {
649                                 pt->pressure += tmp_pressure * brush->gpencil_settings->draw_random_press * BLI_rng_get_float(p->rng);
650                         }
651                         CLAMP(pt->pressure, GPENCIL_STRENGTH_MIN, 1.0f);
652                 }
653
654                 /* apply randomness to uv texture rotation */
655                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) && (brush->gpencil_settings->uv_random > 0.0f)) {
656                         if (BLI_rng_get_float(p->rng) > 0.5f) {
657                                 pt->uv_rot = (BLI_rng_get_float(p->rng) * M_PI * -1) * brush->gpencil_settings->uv_random;
658                         }
659                         else {
660                                 pt->uv_rot = (BLI_rng_get_float(p->rng) * M_PI) * brush->gpencil_settings->uv_random;
661                         }
662                         CLAMP(pt->uv_rot, -M_PI_2, M_PI_2);
663                 }
664                 else {
665                         pt->uv_rot = 0.0f;
666                 }
667
668                 /* apply angle of stroke to brush size */
669                 if (brush->gpencil_settings->draw_angle_factor != 0.0f) {
670                         gp_brush_angle(gpd, brush, pt, mval);
671                 }
672
673                 /* color strength */
674                 if (brush->gpencil_settings->flag & GP_BRUSH_USE_STENGTH_PRESSURE) {
675                         float curvef = curvemapping_evaluateF(brush->gpencil_settings->curve_strength, 0, pressure);
676                         float tmp_pressure = curvef * brush->gpencil_settings->draw_sensitivity;
677
678                         pt->strength = tmp_pressure * brush->gpencil_settings->draw_strength;
679                 }
680                 else {
681                         pt->strength = brush->gpencil_settings->draw_strength;
682                 }
683                 CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
684
685                 /* apply randomness to color strength */
686                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
687                     (brush->gpencil_settings->draw_random_strength > 0.0f))
688                 {
689                         if (BLI_rng_get_float(p->rng) > 0.5f) {
690                                 pt->strength -= pt->strength * brush->gpencil_settings->draw_random_strength * BLI_rng_get_float(p->rng);
691                         }
692                         else {
693                                 pt->strength += pt->strength * brush->gpencil_settings->draw_random_strength * BLI_rng_get_float(p->rng);
694                         }
695                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
696                 }
697
698                 /* point time */
699                 pt->time = (float)(curtime - p->inittime);
700
701                 /* point uv (only 3d view) */
702                 if ((p->sa->spacetype == SPACE_VIEW3D) && (gpd->runtime.sbuffer_size > 1)) {
703                         float pixsize = gp_style->texture_pixsize / 1000000.0f;
704                         tGPspoint *ptb = (tGPspoint *)gpd->runtime.sbuffer + gpd->runtime.sbuffer_size - 2;
705                         bGPDspoint spt, spt2;
706
707                         /* get origin to reproject point */
708                         float origin[3];
709                         gp_get_3d_reference(p, origin);
710                         /* reproject current */
711                         ED_gpencil_tpoint_to_point(p->ar, origin, pt, &spt);
712                         ED_gp_project_point_to_plane(obact, rv3d, origin, p->lock_axis - 1, &spt);
713
714                         /* reproject previous */
715                         ED_gpencil_tpoint_to_point(p->ar, origin, ptb, &spt2);
716                         ED_gp_project_point_to_plane(obact, rv3d, origin, p->lock_axis - 1, &spt2);
717                         p->totpixlen += len_v3v3(&spt.x, &spt2.x) / pixsize;
718                         pt->uv_fac = p->totpixlen;
719                         if ((gp_style) && (gp_style->sima)) {
720                                 pt->uv_fac /= gp_style->sima->gen_x;
721                         }
722                 }
723                 else {
724                         p->totpixlen = 0.0f;
725                         pt->uv_fac = 0.0f;
726                 }
727
728                 /* increment counters */
729                 gpd->runtime.sbuffer_size++;
730
731                 /* smooth while drawing previous points with a reduction factor for previous */
732                 if (brush->gpencil_settings->active_smooth > 0.0f) {
733                         for (int s = 0; s < 3; s++) {
734                                 gp_smooth_buffer(p, brush->gpencil_settings->active_smooth * ((3.0f - s) / 3.0f), gpd->runtime.sbuffer_size - s);
735                         }
736                 }
737
738                 /* check if another operation can still occur */
739                 if (gpd->runtime.sbuffer_size == GP_STROKE_BUFFER_MAX)
740                         return GP_STROKEADD_FULL;
741                 else
742                         return GP_STROKEADD_NORMAL;
743         }
744         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
745
746                 /* enable special flag for drawing engine */
747                 gpd->flag |= GP_DATA_STROKE_POLYGON;
748
749                 bGPDlayer *gpl = BKE_gpencil_layer_getactive(gpd);
750                 /* get pointer to destination point */
751                 pt = (tGPspoint *)(gpd->runtime.sbuffer);
752
753                 /* store settings */
754                 copy_v2_v2(&pt->x, mval);
755                 pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
756                 pt->strength = 1.0f;
757                 pt->time = (float)(curtime - p->inittime);
758
759                 /* if there's stroke for this poly line session add (or replace last) point
760                  * to stroke. This allows to draw lines more interactively (see new segment
761                  * during mouse slide, e.g.)
762                  */
763                 if (gp_stroke_added_check(p)) {
764                         bGPDstroke *gps = p->gpf->strokes.last;
765                         bGPDspoint *pts;
766                         MDeformVert *dvert = NULL;
767
768                         /* first time point is adding to temporary buffer -- need to allocate new point in stroke */
769                         if (gpd->runtime.sbuffer_size == 0) {
770                                 gps->points = MEM_reallocN(gps->points, sizeof(bGPDspoint) * (gps->totpoints + 1));
771                                 if (gps->dvert != NULL) {
772                                         gps->dvert = MEM_reallocN(gps->dvert, sizeof(MDeformVert) * (gps->totpoints + 1));
773                                 }
774                                 gps->totpoints++;
775                         }
776
777                         pts = &gps->points[gps->totpoints - 1];
778                         if (gps->dvert != NULL) {
779                                 dvert = &gps->dvert[gps->totpoints - 1];
780                         }
781                         /* special case for poly lines: normally,
782                          * depth is needed only when creating new stroke from buffer,
783                          * but poly lines are converting to stroke instantly,
784                          * so initialize depth buffer before converting coordinates
785                          */
786                         if (gpencil_project_check(p)) {
787                                 view3d_region_operator_needs_opengl(p->win, p->ar);
788                                 ED_view3d_autodist_init(
789                                         p->depsgraph, p->ar, v3d, (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
790                         }
791
792                         /* convert screen-coordinates to appropriate coordinates (and store them) */
793                         gp_stroke_convertcoords(p, &pt->x, &pts->x, NULL);
794                         /* reproject to plane (only in 3d space) */
795                         gp_reproject_toplane(p, gps);
796                         /* if parented change position relative to parent object */
797                         gp_apply_parent_point(depsgraph, obact, gpd, gpl, pts);
798                         /* copy pressure and time */
799                         pts->pressure = pt->pressure;
800                         pts->strength = pt->strength;
801                         pts->time = pt->time;
802                         pts->uv_fac = pt->uv_fac;
803                         pts->uv_rot = pt->uv_rot;
804
805                         if ((ts->gpencil_flags & GP_TOOL_FLAG_CREATE_WEIGHTS) && (have_weight)) {
806                                 BKE_gpencil_dvert_ensure(gps);
807                                 MDeformWeight *dw = defvert_verify_index(dvert, def_nr);
808                                 if (dw) {
809                                         dw->weight = ts->vgroup_weight;
810                                 }
811                         }
812                         else {
813                                 if (dvert != NULL) {
814                                         dvert->totweight = 0;
815                                         dvert->dw = NULL;
816                                 }
817                         }
818
819                         /* force fill recalc */
820                         gps->flag |= GP_STROKE_RECALC_CACHES;
821                         /* drawing batch cache is dirty now */
822                         gp_update_cache(p->gpd);
823                 }
824
825                 /* increment counters */
826                 if (gpd->runtime.sbuffer_size == 0)
827                         gpd->runtime.sbuffer_size++;
828
829                 return GP_STROKEADD_NORMAL;
830         }
831
832         /* return invalid state for now... */
833         return GP_STROKEADD_INVALID;
834 }
835
836 /* make a new stroke from the buffer data */
837 static void gp_stroke_newfrombuffer(tGPsdata *p)
838 {
839         bGPdata *gpd = p->gpd;
840         bGPDlayer *gpl = p->gpl;
841         bGPDstroke *gps;
842         bGPDspoint *pt;
843         tGPspoint *ptc;
844         MDeformVert *dvert = NULL;
845         Brush *brush = p->brush;
846         ToolSettings *ts = p->scene->toolsettings;
847         Depsgraph *depsgraph = p->depsgraph;
848         Object *obact = (Object *)p->ownerPtr.data;
849         const int def_nr = obact->actdef - 1;
850         const bool have_weight = (bool)BLI_findlink(&obact->defbase, def_nr);
851
852         int i, totelem;
853         /* since strokes are so fine, when using their depth we need a margin otherwise they might get missed */
854         int depth_margin = (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 4 : 0;
855
856         /* get total number of points to allocate space for
857          * - drawing straight-lines only requires the endpoints
858          */
859         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT)
860                 totelem = (gpd->runtime.sbuffer_size >= 2) ? 2 : gpd->runtime.sbuffer_size;
861         else
862                 totelem = gpd->runtime.sbuffer_size;
863
864         /* exit with error if no valid points from this stroke */
865         if (totelem == 0) {
866                 if (G.debug & G_DEBUG)
867                         printf("Error: No valid points in stroke buffer to convert (tot=%d)\n", gpd->runtime.sbuffer_size);
868                 return;
869         }
870
871         /* special case for poly line -- for already added stroke during session
872          * coordinates are getting added to stroke immediately to allow more
873          * interactive behavior
874          */
875         if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
876                 /* be sure to hide any lazy cursor */
877                 ED_gpencil_toggle_brush_cursor(p->C, true, NULL);
878
879                 if (gp_stroke_added_check(p)) {
880                         return;
881                 }
882         }
883
884         /* allocate memory for a new stroke */
885         gps = MEM_callocN(sizeof(bGPDstroke), "gp_stroke");
886
887         /* copy appropriate settings for stroke */
888         gps->totpoints = totelem;
889         gps->thickness = brush->size;
890         gps->flag = gpd->runtime.sbuffer_sflag;
891         gps->inittime = p->inittime;
892
893         /* enable recalculation flag by default (only used if hq fill) */
894         gps->flag |= GP_STROKE_RECALC_CACHES;
895
896         /* allocate enough memory for a continuous array for storage points */
897         const int subdivide = brush->gpencil_settings->draw_subdivide;
898
899         gps->points = MEM_callocN(sizeof(bGPDspoint) * gps->totpoints, "gp_stroke_points");
900
901         /* initialize triangle memory to dummy data */
902         gps->triangles = MEM_callocN(sizeof(bGPDtriangle), "GP Stroke triangulation");
903         gps->flag |= GP_STROKE_RECALC_CACHES;
904         gps->tot_triangles = 0;
905         /* drawing batch cache is dirty now */
906         gp_update_cache(p->gpd);
907         /* set pointer to first non-initialized point */
908         pt = gps->points + (gps->totpoints - totelem);
909         if (gps->dvert != NULL) {
910                 dvert = gps->dvert + (gps->totpoints - totelem);
911         }
912
913         /* copy points from the buffer to the stroke */
914         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
915                 /* straight lines only -> only endpoints */
916                 {
917                         /* first point */
918                         ptc = gpd->runtime.sbuffer;
919
920                         /* convert screen-coordinates to appropriate coordinates (and store them) */
921                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
922                         /* copy pressure and time */
923                         pt->pressure = ptc->pressure;
924                         pt->strength = ptc->strength;
925                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
926                         pt->time = ptc->time;
927                         pt++;
928
929                         if ((ts->gpencil_flags & GP_TOOL_FLAG_CREATE_WEIGHTS) && (have_weight)) {
930                                 BKE_gpencil_dvert_ensure(gps);
931                                 MDeformWeight *dw = defvert_verify_index(dvert, def_nr);
932                                 if (dw) {
933                                         dw->weight = ts->vgroup_weight;
934                                 }
935                                 dvert++;
936                         }
937                         else {
938                                 if (dvert != NULL) {
939                                         dvert->totweight = 0;
940                                         dvert->dw = NULL;
941                                         dvert++;
942                                 }
943                         }
944                 }
945
946                 if (totelem == 2) {
947                         /* last point if applicable */
948                         ptc = ((tGPspoint *)gpd->runtime.sbuffer) + (gpd->runtime.sbuffer_size - 1);
949
950                         /* convert screen-coordinates to appropriate coordinates (and store them) */
951                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
952                         /* copy pressure and time */
953                         pt->pressure = ptc->pressure;
954                         pt->strength = ptc->strength;
955                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
956                         pt->time = ptc->time;
957
958                         if ((ts->gpencil_flags & GP_TOOL_FLAG_CREATE_WEIGHTS) && (have_weight)) {
959                                 BKE_gpencil_dvert_ensure(gps);
960                                 MDeformWeight *dw = defvert_verify_index(dvert, def_nr);
961                                 if (dw) {
962                                         dw->weight = ts->vgroup_weight;
963                                 }
964                         }
965                         else {
966                                 if (dvert != NULL) {
967                                         dvert->totweight = 0;
968                                         dvert->dw = NULL;
969                                 }
970                         }
971                 }
972
973                 /* reproject to plane (only in 3d space) */
974                 gp_reproject_toplane(p, gps);
975                 pt = gps->points;
976                 for (i = 0; i < gps->totpoints; i++, pt++) {
977                         /* if parented change position relative to parent object */
978                         gp_apply_parent_point(depsgraph, obact, gpd, gpl, pt);
979                 }
980         }
981         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
982                 /* first point */
983                 ptc = gpd->runtime.sbuffer;
984
985                 /* convert screen-coordinates to appropriate coordinates (and store them) */
986                 gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
987                 /* reproject to plane (only in 3d space) */
988                 gp_reproject_toplane(p, gps);
989                 /* if parented change position relative to parent object */
990                 gp_apply_parent_point(depsgraph, obact, gpd, gpl, pt);
991                 /* copy pressure and time */
992                 pt->pressure = ptc->pressure;
993                 pt->strength = ptc->strength;
994                 CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
995                 pt->time = ptc->time;
996
997                 if ((ts->gpencil_flags & GP_TOOL_FLAG_CREATE_WEIGHTS) && (have_weight)) {
998                         BKE_gpencil_dvert_ensure(gps);
999                         MDeformWeight *dw = defvert_verify_index(dvert, def_nr);
1000                         if (dw) {
1001                                 dw->weight = ts->vgroup_weight;
1002                         }
1003                 }
1004                 else {
1005                         if (dvert != NULL) {
1006                                 dvert->totweight = 0;
1007                                 dvert->dw = NULL;
1008                         }
1009                 }
1010
1011         }
1012         else {
1013                 float *depth_arr = NULL;
1014
1015                 /* get an array of depths, far depths are blended */
1016                 if (gpencil_project_check(p)) {
1017                         int mval_i[2], mval_prev[2] = { 0 };
1018                         int interp_depth = 0;
1019                         int found_depth = 0;
1020
1021                         depth_arr = MEM_mallocN(sizeof(float) * gpd->runtime.sbuffer_size, "depth_points");
1022
1023                         for (i = 0, ptc = gpd->runtime.sbuffer; i < gpd->runtime.sbuffer_size; i++, ptc++, pt++) {
1024
1025                                 round_v2i_v2fl(mval_i, &ptc->x);
1026
1027                                 if ((ED_view3d_autodist_depth(p->ar, mval_i, depth_margin, depth_arr + i) == 0) &&
1028                                     (i && (ED_view3d_autodist_depth_seg(p->ar, mval_i, mval_prev, depth_margin + 1, depth_arr + i) == 0)))
1029                                 {
1030                                         interp_depth = true;
1031                                 }
1032                                 else {
1033                                         found_depth = true;
1034                                 }
1035
1036                                 copy_v2_v2_int(mval_prev, mval_i);
1037                         }
1038
1039                         if (found_depth == false) {
1040                                 /* eeh... not much we can do.. :/, ignore depth in this case, use the 3D cursor */
1041                                 for (i = gpd->runtime.sbuffer_size - 1; i >= 0; i--)
1042                                         depth_arr[i] = 0.9999f;
1043                         }
1044                         else {
1045                                 if ((ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE_ENDPOINTS) ||
1046                                     (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE_FIRST))
1047                                 {
1048                                         int first_valid = 0;
1049                                         int last_valid = 0;
1050
1051                                         /* find first valid contact point */
1052                                         for (i = 0; i < gpd->runtime.sbuffer_size; i++) {
1053                                                 if (depth_arr[i] != FLT_MAX)
1054                                                         break;
1055                                         }
1056                                         first_valid = i;
1057
1058                                         /* find last valid contact point */
1059                                         if (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE_FIRST) {
1060                                                 last_valid = first_valid;
1061                                         }
1062                                         else {
1063                                                 for (i = gpd->runtime.sbuffer_size - 1; i >= 0; i--) {
1064                                                         if (depth_arr[i] != FLT_MAX)
1065                                                                 break;
1066                                                 }
1067                                                 last_valid = i;
1068                                         }
1069                                         /* invalidate any other point, to interpolate between
1070                                          * first and last contact in an imaginary line between them */
1071                                         for (i = 0; i < gpd->runtime.sbuffer_size; i++) {
1072                                                 if ((i != first_valid) && (i != last_valid)) {
1073                                                         depth_arr[i] = FLT_MAX;
1074                                                 }
1075                                         }
1076                                         interp_depth = true;
1077                                 }
1078
1079                                 if (interp_depth) {
1080                                         interp_sparse_array(depth_arr, gpd->runtime.sbuffer_size, FLT_MAX);
1081                                 }
1082                         }
1083                 }
1084
1085                 pt = gps->points;
1086                 dvert = gps->dvert;
1087
1088                 /* convert all points (normal behavior) */
1089                 for (i = 0, ptc = gpd->runtime.sbuffer; i < gpd->runtime.sbuffer_size && ptc; i++, ptc++, pt++) {
1090                         /* convert screen-coordinates to appropriate coordinates (and store them) */
1091                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, depth_arr ? depth_arr + i : NULL);
1092
1093                         /* copy pressure and time */
1094                         pt->pressure = ptc->pressure;
1095                         pt->strength = ptc->strength;
1096                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
1097                         pt->time = ptc->time;
1098                         pt->uv_fac = ptc->uv_fac;
1099                         pt->uv_rot = ptc->uv_rot;
1100
1101                         if (dvert != NULL) {
1102                                 dvert->totweight = 0;
1103                                 dvert->dw = NULL;
1104                                 dvert++;
1105                         }
1106                 }
1107
1108                 /* subdivide and smooth the stroke */
1109                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_SETTINGS) && (subdivide > 0)) {
1110                         gp_subdivide_stroke(gps, subdivide);
1111                 }
1112                 /* apply randomness to stroke */
1113                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
1114                     (brush->gpencil_settings->draw_random_sub > 0.0f))
1115                 {
1116                         gp_randomize_stroke(gps, brush, p->rng);
1117                 }
1118
1119                 /* smooth stroke after subdiv - only if there's something to do
1120                  * for each iteration, the factor is reduced to get a better smoothing without changing too much
1121                  * the original stroke
1122                  */
1123                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_SETTINGS) &&
1124                     (brush->gpencil_settings->draw_smoothfac > 0.0f))
1125                 {
1126                         float reduce = 0.0f;
1127                         for (int r = 0; r < brush->gpencil_settings->draw_smoothlvl; r++) {
1128                                 for (i = 0; i < gps->totpoints - 1; i++) {
1129                                         BKE_gpencil_smooth_stroke(gps, i, brush->gpencil_settings->draw_smoothfac - reduce);
1130                                         BKE_gpencil_smooth_stroke_strength(gps, i, brush->gpencil_settings->draw_smoothfac);
1131                                 }
1132                                 reduce += 0.25f;  // reduce the factor
1133                         }
1134                 }
1135                 /* smooth thickness */
1136                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_SETTINGS) &&
1137                     (brush->gpencil_settings->thick_smoothfac > 0.0f))
1138                 {
1139                         for (int r = 0; r < brush->gpencil_settings->thick_smoothlvl * 2; r++) {
1140                                 for (i = 0; i < gps->totpoints - 1; i++) {
1141                                         BKE_gpencil_smooth_stroke_thickness(gps, i, brush->gpencil_settings->thick_smoothfac);
1142                                 }
1143                         }
1144                 }
1145
1146                 /* reproject to plane (only in 3d space) */
1147                 gp_reproject_toplane(p, gps);
1148                 /* change position relative to parent object */
1149                 gp_apply_parent(depsgraph, obact, gpd, gpl, gps);
1150
1151                 if (depth_arr)
1152                         MEM_freeN(depth_arr);
1153         }
1154
1155         /* Save material index */
1156         gps->mat_nr = BKE_gpencil_get_material_index(p->ob, p->material) - 1;
1157
1158         /* calculate UVs along the stroke */
1159         ED_gpencil_calc_stroke_uv(obact, gps);
1160
1161         /* add stroke to frame, usually on tail of the listbase, but if on back is enabled the stroke is added on listbase head
1162          * because the drawing order is inverse and the head stroke is the first to draw. This is very useful for artist
1163          * when drawing the background
1164          */
1165         if ((ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) && (p->paintmode != GP_PAINTMODE_DRAW_POLY)) {
1166                 BLI_addhead(&p->gpf->strokes, gps);
1167         }
1168         else {
1169                 BLI_addtail(&p->gpf->strokes, gps);
1170         }
1171         /* add weights */
1172         if ((ts->gpencil_flags & GP_TOOL_FLAG_CREATE_WEIGHTS) && (have_weight)) {
1173                 BKE_gpencil_dvert_ensure(gps);
1174                 for (i = 0; i < gps->totpoints; i++) {
1175                         MDeformVert *ve = &gps->dvert[i];
1176                         MDeformWeight *dw = defvert_verify_index(ve, def_nr);
1177                         if (dw) {
1178                                 dw->weight = ts->vgroup_weight;
1179                         }
1180                 }
1181         }
1182
1183         gp_stroke_added_enable(p);
1184 }
1185
1186 /* --- 'Eraser' for 'Paint' Tool ------ */
1187
1188 /* which which point is infront (result should only be used for comparison) */
1189 static float view3d_point_depth(const RegionView3D *rv3d, const float co[3])
1190 {
1191         if (rv3d->is_persp) {
1192                 return ED_view3d_calc_zfac(rv3d, co, NULL);
1193         }
1194         else {
1195                 return -dot_v3v3(rv3d->viewinv[2], co);
1196         }
1197 }
1198
1199 /* only erase stroke points that are visible */
1200 static bool gp_stroke_eraser_is_occluded(tGPsdata *p, const bGPDspoint *pt, const int x, const int y)
1201 {
1202         Object *obact = (Object *)p->ownerPtr.data;
1203
1204         if ((p->sa->spacetype == SPACE_VIEW3D) &&
1205             (p->flags & GP_PAINTFLAG_V3D_ERASER_DEPTH))
1206         {
1207                 RegionView3D *rv3d = p->ar->regiondata;
1208                 bGPDlayer *gpl = p->gpl;
1209
1210                 const int mval_i[2] = {x, y};
1211                 float mval_3d[3];
1212                 float fpt[3];
1213
1214                 float diff_mat[4][4];
1215                 /* calculate difference matrix if parent object */
1216                 ED_gpencil_parent_location(p->depsgraph, obact, p->gpd, gpl, diff_mat);
1217
1218                 if (ED_view3d_autodist_simple(p->ar, mval_i, mval_3d, 0, NULL)) {
1219                         const float depth_mval = view3d_point_depth(rv3d, mval_3d);
1220
1221                         mul_v3_m4v3(fpt, diff_mat, &pt->x);
1222                         const float depth_pt = view3d_point_depth(rv3d, fpt);
1223
1224                         if (depth_pt > depth_mval) {
1225                                 return true;
1226                         }
1227                 }
1228         }
1229         return false;
1230 }
1231
1232 /* apply a falloff effect to brush strength, based on distance */
1233 static float gp_stroke_eraser_calc_influence(tGPsdata *p, const float mval[2], const int radius, const int co[2])
1234 {
1235         Brush *brush = p->brush;
1236         /* Linear Falloff... */
1237         int mval_i[2];
1238         round_v2i_v2fl(mval_i, mval);
1239         float distance = (float)len_v2v2_int(mval_i, co);
1240         float fac;
1241
1242         CLAMP(distance, 0.0f, (float)radius);
1243         fac = 1.0f - (distance / (float)radius);
1244
1245         /* apply strength factor */
1246         fac *= brush->gpencil_settings->draw_strength;
1247
1248         /* Control this further using pen pressure */
1249         if (brush->gpencil_settings->flag & GP_BRUSH_USE_PRESSURE) {
1250                 fac *= p->pressure;
1251         }
1252         /* Return influence factor computed here */
1253         return fac;
1254 }
1255
1256 /* helper to free a stroke */
1257 static void gp_free_stroke(bGPdata *gpd, bGPDframe *gpf, bGPDstroke *gps)
1258 {
1259         if (gps->points) {
1260                 MEM_freeN(gps->points);
1261         }
1262
1263         if (gps->dvert) {
1264                 BKE_gpencil_free_stroke_weights(gps);
1265                 MEM_freeN(gps->dvert);
1266         }
1267
1268         if (gps->triangles)
1269                 MEM_freeN(gps->triangles);
1270         BLI_freelinkN(&gpf->strokes, gps);
1271         gp_update_cache(gpd);
1272 }
1273
1274 /* analyze points to be removed when soft eraser is used
1275  * to avoid that segments gets the end points rounded. This
1276  * round cpas breaks the artistic effect.
1277  */
1278 static void gp_stroke_soft_refine(bGPDstroke *gps, const float cull_thresh)
1279 {
1280         bGPDspoint *pt = NULL;
1281         bGPDspoint *pt_before = NULL;
1282         bGPDspoint *pt_after = NULL;
1283         int i;
1284
1285         /* check if enough points*/
1286         if (gps->totpoints < 3) {
1287                 return;
1288         }
1289
1290         /* loop all points from second to last minus one
1291          * to untag any point that is not surrounded by tagged points
1292          */
1293         pt = gps->points;
1294         for (i = 1; i < gps->totpoints - 1; i++, pt++) {
1295                 if (pt->flag & GP_SPOINT_TAG) {
1296                         pt_before = &gps->points[i - 1];
1297                         pt_after = &gps->points[i + 1];
1298
1299                         /* if any of the side points are not tagged, mark to keep */
1300                         if (((pt_before->flag & GP_SPOINT_TAG) == 0) ||
1301                             ((pt_after->flag & GP_SPOINT_TAG) == 0))
1302                         {
1303                                 if (pt->pressure > cull_thresh) {
1304                                         pt->flag |= GP_SPOINT_TEMP_TAG;
1305                                 }
1306                         }
1307                         else {
1308                                 /* reduce opacity of extreme points */
1309                                 if ((pt_before->flag & GP_SPOINT_TAG) == 0) {
1310                                         pt_before->strength *= 0.5f;
1311                                 }
1312                                 if ((pt_after->flag & GP_SPOINT_TAG) == 0) {
1313                                         pt_after->strength *= 0.5f;
1314                                 }
1315                         }
1316                 }
1317         }
1318
1319         /* now untag temp tagged */
1320         pt = gps->points;
1321         for (i = 1; i < gps->totpoints - 1; i++, pt++) {
1322                 if (pt->flag & GP_SPOINT_TEMP_TAG) {
1323                         pt->flag &= ~GP_SPOINT_TAG;
1324                         pt->flag &= ~GP_SPOINT_TEMP_TAG;
1325                 }
1326         }
1327 }
1328
1329 /* eraser tool - evaluation per stroke */
1330 /* TODO: this could really do with some optimization (KD-Tree/BVH?) */
1331 static void gp_stroke_eraser_dostroke(tGPsdata *p,
1332         bGPDlayer *gpl, bGPDframe *gpf, bGPDstroke *gps,
1333         const float mval[2], const float mvalo[2],
1334         const int radius, const rcti *rect)
1335 {
1336         Depsgraph *depsgraph = p->depsgraph;
1337         Object *obact = (Object *)p->ownerPtr.data;
1338         Brush *eraser = p->eraser;
1339         bGPDspoint *pt0, *pt1, *pt2;
1340         int pc0[2] = {0};
1341         int pc1[2] = {0};
1342         int pc2[2] = {0};
1343         int i;
1344         float diff_mat[4][4];
1345         int mval_i[2];
1346         round_v2i_v2fl(mval_i, mval);
1347
1348         /* calculate difference matrix */
1349         ED_gpencil_parent_location(depsgraph, obact, p->gpd, gpl, diff_mat);
1350
1351         if (gps->totpoints == 0) {
1352                 /* just free stroke */
1353                 gp_free_stroke(p->gpd, gpf, gps);
1354         }
1355         else if (gps->totpoints == 1) {
1356                 /* only process if it hasn't been masked out... */
1357                 if (!(p->flags & GP_PAINTFLAG_SELECTMASK) || (gps->points->flag & GP_SPOINT_SELECT)) {
1358                         bGPDspoint pt_temp;
1359                         gp_point_to_parent_space(gps->points, diff_mat, &pt_temp);
1360                         gp_point_to_xy(&p->gsc, gps, &pt_temp, &pc1[0], &pc1[1]);
1361                         /* do boundbox check first */
1362                         if ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) {
1363                                 /* only check if point is inside */
1364                                 if (len_v2v2_int(mval_i, pc1) <= radius) {
1365                                         /* free stroke */
1366                                         gp_free_stroke(p->gpd, gpf, gps);
1367                                 }
1368                         }
1369                 }
1370         }
1371         else if ((p->flags & GP_PAINTFLAG_STROKE_ERASER) || (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_STROKE)) {
1372                 for (i = 0; (i + 1) < gps->totpoints; i++) {
1373
1374                         /* only process if it hasn't been masked out... */
1375                         if ((p->flags & GP_PAINTFLAG_SELECTMASK) && !(gps->points->flag & GP_SPOINT_SELECT))
1376                                 continue;
1377
1378                         /* get points to work with */
1379                         pt1 = gps->points + i;
1380                         bGPDspoint npt;
1381                         gp_point_to_parent_space(pt1, diff_mat, &npt);
1382                         gp_point_to_xy(&p->gsc, gps, &npt, &pc1[0], &pc1[1]);
1383
1384                         /* do boundbox check first */
1385                         if ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) {
1386                                 /* only check if point is inside */
1387                                 if (len_v2v2_int(mval_i, pc1) <= radius) {
1388                                         /* free stroke */
1389                                         gp_free_stroke(p->gpd, gpf, gps);
1390                                         return;
1391                                 }
1392                         }
1393                 }
1394         }
1395         else {
1396                 /* Pressure threshold at which stroke should be culled: Calculated as pressure value
1397                  * below which we would have invisible strokes
1398                  */
1399                 const float cull_thresh = (gps->thickness) ? 1.0f / ((float)gps->thickness) : 1.0f;
1400
1401                 /* Amount to decrease the pressure of each point with each stroke */
1402                 // TODO: Fetch from toolsettings, or compute based on thickness instead?
1403                 const float strength = 0.1f;
1404
1405                 /* Perform culling? */
1406                 bool do_cull = false;
1407
1408
1409                 /* Clear Tags
1410                  *
1411                  * Note: It's better this way, as we are sure that
1412                  * we don't miss anything, though things will be
1413                  * slightly slower as a result
1414                  */
1415                 for (i = 0; i < gps->totpoints; i++) {
1416                         bGPDspoint *pt = &gps->points[i];
1417                         pt->flag &= ~GP_SPOINT_TAG;
1418                 }
1419
1420                 /* First Pass: Loop over the points in the stroke
1421                  *   1) Thin out parts of the stroke under the brush
1422                  *   2) Tag "too thin" parts for removal (in second pass)
1423                  */
1424                 for (i = 0; (i + 1) < gps->totpoints; i++) {
1425                         /* get points to work with */
1426                         pt0 = i > 0 ? gps->points + i - 1 : NULL;
1427                         pt1 = gps->points + i;
1428                         pt2 = gps->points + i + 1;
1429
1430                         /* only process if it hasn't been masked out... */
1431                         if ((p->flags & GP_PAINTFLAG_SELECTMASK) && !(gps->points->flag & GP_SPOINT_SELECT))
1432                                 continue;
1433
1434                         bGPDspoint npt;
1435                         if (pt0) {
1436                                 gp_point_to_parent_space(pt0, diff_mat, &npt);
1437                                 gp_point_to_xy(&p->gsc, gps, &npt, &pc0[0], &pc0[1]);
1438                         }
1439                         else {
1440                                 /* avoid null values */
1441                                 copy_v2_v2_int(pc0, pc1);
1442                         }
1443
1444                         gp_point_to_parent_space(pt1, diff_mat, &npt);
1445                         gp_point_to_xy(&p->gsc, gps, &npt, &pc1[0], &pc1[1]);
1446
1447                         gp_point_to_parent_space(pt2, diff_mat, &npt);
1448                         gp_point_to_xy(&p->gsc, gps, &npt, &pc2[0], &pc2[1]);
1449
1450                         /* Check that point segment of the boundbox of the eraser stroke */
1451                         if (((!ELEM(V2D_IS_CLIPPED, pc0[0], pc0[1])) && BLI_rcti_isect_pt(rect, pc0[0], pc0[1])) ||
1452                             ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) ||
1453                             ((!ELEM(V2D_IS_CLIPPED, pc2[0], pc2[1])) && BLI_rcti_isect_pt(rect, pc2[0], pc2[1])))
1454                         {
1455                                 /* Check if point segment of stroke had anything to do with
1456                                  * eraser region  (either within stroke painted, or on its lines)
1457                                  * - this assumes that linewidth is irrelevant
1458                                  */
1459                                 if (gp_stroke_inside_circle(mval, mvalo, radius, pc0[0], pc0[1], pc2[0], pc2[1])) {
1460                                         if ((gp_stroke_eraser_is_occluded(p, pt0, pc0[0], pc0[1]) == false) ||
1461                                             (gp_stroke_eraser_is_occluded(p, pt1, pc1[0], pc1[1]) == false) ||
1462                                             (gp_stroke_eraser_is_occluded(p, pt2, pc2[0], pc2[1]) == false))
1463                                         {
1464                                                 /* Point is affected: */
1465                                                 /* Adjust thickness
1466                                                  *  - Influence of eraser falls off with distance from the middle of the eraser
1467                                                  *  - Second point gets less influence, as it might get hit again in the next segment
1468                                                  */
1469
1470                                                 /* Adjust strength if the eraser is soft */
1471                                                 if (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_SOFT) {
1472                                                         float f_strength = eraser->gpencil_settings->era_strength_f / 100.0f;
1473                                                         float f_thickness = eraser->gpencil_settings->era_thickness_f / 100.0f;
1474
1475                                                         if (pt0) {
1476                                                                 pt0->strength -= gp_stroke_eraser_calc_influence(p, mval, radius, pc0) * strength * f_strength * 0.5f;
1477                                                                 CLAMP_MIN(pt0->strength, 0.0f);
1478                                                                 pt0->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc0) * strength * f_thickness * 0.5f;
1479                                                         }
1480
1481                                                         pt1->strength -= gp_stroke_eraser_calc_influence(p, mval, radius, pc1) * strength * f_strength;
1482                                                         CLAMP_MIN(pt1->strength, 0.0f);
1483                                                         pt1->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc1) * strength * f_thickness;
1484
1485                                                         pt2->strength -= gp_stroke_eraser_calc_influence(p, mval, radius, pc2) * strength * f_strength * 0.5f;
1486                                                         CLAMP_MIN(pt2->strength, 0.0f);
1487                                                         pt2->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc2) * strength * f_thickness * 0.5f;
1488
1489                                                         /* if invisible, delete point */
1490                                                         if ((pt0) &&
1491                                                             ((pt0->strength <= GPENCIL_ALPHA_OPACITY_THRESH) ||
1492                                                              (pt0->pressure < cull_thresh)))
1493                                                         {
1494                                                                 pt0->flag |= GP_SPOINT_TAG;
1495                                                                 do_cull = true;
1496                                                         }
1497                                                         if ((pt1->strength <= GPENCIL_ALPHA_OPACITY_THRESH) || (pt1->pressure < cull_thresh)) {
1498                                                                 pt1->flag |= GP_SPOINT_TAG;
1499                                                                 do_cull = true;
1500                                                         }
1501                                                         if ((pt2->strength <= GPENCIL_ALPHA_OPACITY_THRESH) || (pt2->pressure < cull_thresh)) {
1502                                                                 pt2->flag |= GP_SPOINT_TAG;
1503                                                                 do_cull = true;
1504                                                         }
1505                                                 }
1506                                                 else {
1507                                                         pt1->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc1) * strength;
1508                                                         pt2->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc2) * strength * 0.5f;
1509                                                 }
1510
1511                                                 /* 2) Tag any point with overly low influence for removal in the next pass */
1512                                                 if ((pt1->pressure < cull_thresh) || (p->flags & GP_PAINTFLAG_HARD_ERASER) ||
1513                                                     (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_HARD))
1514                                                 {
1515                                                         pt1->flag |= GP_SPOINT_TAG;
1516                                                         do_cull = true;
1517                                                 }
1518                                                 if ((pt2->pressure < cull_thresh) || (p->flags & GP_PAINTFLAG_HARD_ERASER) ||
1519                                                     (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_HARD))
1520                                                 {
1521                                                         pt2->flag |= GP_SPOINT_TAG;
1522                                                         do_cull = true;
1523                                                 }
1524                                         }
1525                                 }
1526                         }
1527                 }
1528
1529                 /* Second Pass: Remove any points that are tagged */
1530                 if (do_cull) {
1531                         /* if soft eraser, must analyze points to be sure the stroke ends
1532                          * don't get rounded */
1533                         if (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_SOFT) {
1534                                 gp_stroke_soft_refine(gps, cull_thresh);
1535                         }
1536
1537                         gp_stroke_delete_tagged_points(gpf, gps, gps->next, GP_SPOINT_TAG, false);
1538                 }
1539                 gp_update_cache(p->gpd);
1540         }
1541 }
1542
1543 /* erase strokes which fall under the eraser strokes */
1544 static void gp_stroke_doeraser(tGPsdata *p)
1545 {
1546         bGPDlayer *gpl;
1547         bGPDstroke *gps, *gpn;
1548         rcti rect;
1549         Brush *brush = p->brush;
1550         Brush *eraser = p->eraser;
1551         bool use_pressure = false;
1552         float press = 1.0f;
1553
1554         /* detect if use pressure in eraser */
1555         if (brush->gpencil_tool == GPAINT_TOOL_ERASE) {
1556                 use_pressure = (bool)(brush->gpencil_settings->flag & GP_BRUSH_USE_PRESSURE);
1557         }
1558         else if ((eraser != NULL) & (eraser->gpencil_tool == GPAINT_TOOL_ERASE)) {
1559                 use_pressure = (bool)(eraser->gpencil_settings->flag & GP_BRUSH_USE_PRESSURE);
1560         }
1561         if (use_pressure) {
1562                 press = p->pressure;
1563                 CLAMP(press, 0.01f, 1.0f);
1564         }
1565         /* rect is rectangle of eraser */
1566         const int calc_radius = (int)p->radius * press;
1567         rect.xmin = p->mval[0] - calc_radius;
1568         rect.ymin = p->mval[1] - calc_radius;
1569         rect.xmax = p->mval[0] + calc_radius;
1570         rect.ymax = p->mval[1] + calc_radius;
1571
1572         if (p->sa->spacetype == SPACE_VIEW3D) {
1573                 if (p->flags & GP_PAINTFLAG_V3D_ERASER_DEPTH) {
1574                         View3D *v3d = p->sa->spacedata.first;
1575                         view3d_region_operator_needs_opengl(p->win, p->ar);
1576                         ED_view3d_autodist_init(p->depsgraph, p->ar, v3d, 0);
1577                 }
1578         }
1579
1580         /* loop over all layers too, since while it's easy to restrict editing to
1581          * only a subset of layers, it is harder to perform the same erase operation
1582          * on multiple layers...
1583          */
1584         for (gpl = p->gpd->layers.first; gpl; gpl = gpl->next) {
1585                 bGPDframe *gpf = gpl->actframe;
1586
1587                 /* only affect layer if it's editable (and visible) */
1588                 if (gpencil_layer_is_editable(gpl) == false) {
1589                         continue;
1590                 }
1591                 else if (gpf == NULL) {
1592                         continue;
1593                 }
1594
1595                 /* loop over strokes, checking segments for intersections */
1596                 for (gps = gpf->strokes.first; gps; gps = gpn) {
1597                         gpn = gps->next;
1598                         /* check if the color is editable */
1599                         if (ED_gpencil_stroke_color_use(p->ob, gpl, gps) == false) {
1600                                 continue;
1601                         }
1602                         /* Not all strokes in the datablock may be valid in the current editor/context
1603                          * (e.g. 2D space strokes in the 3D view, if the same datablock is shared)
1604                          */
1605                         if (ED_gpencil_stroke_can_use_direct(p->sa, gps)) {
1606                                 gp_stroke_eraser_dostroke(p, gpl, gpf, gps, p->mval, p->mvalo, calc_radius, &rect);
1607                         }
1608                 }
1609         }
1610 }
1611
1612 /* ******************************************* */
1613 /* Sketching Operator */
1614
1615 /* clear the session buffers (call this before AND after a paint operation) */
1616 static void gp_session_validatebuffer(tGPsdata *p)
1617 {
1618         bGPdata *gpd = p->gpd;
1619         Brush *brush = p->brush;
1620
1621         /* clear memory of buffer (or allocate it if starting a new session) */
1622         if (gpd->runtime.sbuffer) {
1623                 /* printf("\t\tGP - reset sbuffer\n"); */
1624                 memset(gpd->runtime.sbuffer, 0, sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX);
1625         }
1626         else {
1627                 /* printf("\t\tGP - allocate sbuffer\n"); */
1628                 gpd->runtime.sbuffer = MEM_callocN(sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX, "gp_session_strokebuffer");
1629         }
1630
1631         /* reset indices */
1632         gpd->runtime.sbuffer_size = 0;
1633
1634         /* reset flags */
1635         gpd->runtime.sbuffer_sflag = 0;
1636
1637         /* reset inittime */
1638         p->inittime = 0.0;
1639
1640         /* reset lazy */
1641         if (brush) {
1642                 brush->gpencil_settings->flag &= ~GP_BRUSH_STABILIZE_MOUSE_TEMP;
1643         }
1644 }
1645
1646 /* helper to get default eraser and create one if no eraser brush */
1647 static Brush *gp_get_default_eraser(Main *bmain, ToolSettings *ts)
1648 {
1649         Brush *brush_dft = NULL;
1650         Paint *paint = &ts->gp_paint->paint;
1651         Brush *brush_old = paint->brush;
1652         for (Brush *brush = bmain->brush.first; brush; brush = brush->id.next) {
1653                 if ((brush->ob_mode == OB_MODE_PAINT_GPENCIL) &&
1654                     (brush->gpencil_tool == GPAINT_TOOL_ERASE))
1655                 {
1656                         /* save first eraser to use later if no default */
1657                         if (brush_dft == NULL) {
1658                                 brush_dft = brush;
1659                         }
1660                         /* found default */
1661                         if (brush->gpencil_settings->flag & GP_BRUSH_DEFAULT_ERASER) {
1662                                 return brush;
1663                         }
1664                 }
1665         }
1666         /* if no default, but exist eraser brush, return this and set as default */
1667         if (brush_dft) {
1668                 brush_dft->gpencil_settings->flag |= GP_BRUSH_DEFAULT_ERASER;
1669                 return brush_dft;
1670         }
1671         /* create a new soft eraser brush */
1672         else {
1673                 brush_dft = BKE_brush_add_gpencil(bmain, ts, "Soft Eraser");
1674                 brush_dft->size = 30.0f;
1675                 brush_dft->gpencil_settings->flag |= (GP_BRUSH_ENABLE_CURSOR | GP_BRUSH_DEFAULT_ERASER);
1676                 brush_dft->gpencil_settings->icon_id = GP_BRUSH_ICON_ERASE_SOFT;
1677                 brush_dft->gpencil_tool = GPAINT_TOOL_ERASE;
1678                 brush_dft->gpencil_settings->eraser_mode = GP_BRUSH_ERASER_SOFT;
1679
1680                 /* reset current brush */
1681                 BKE_paint_brush_set(paint, brush_old);
1682
1683                 return brush_dft;
1684         }
1685 }
1686
1687 /* initialize a drawing brush */
1688 static void gp_init_drawing_brush(bContext *C, tGPsdata *p)
1689 {
1690         Scene *scene = CTX_data_scene(C);
1691         ToolSettings *ts = CTX_data_tool_settings(C);
1692
1693         Paint *paint = &ts->gp_paint->paint;
1694
1695         /* if not exist, create a new one */
1696         if (paint->brush == NULL) {
1697                 /* create new brushes */
1698                 BKE_brush_gpencil_presets(C);
1699         }
1700         /* be sure curves are initializated */
1701         curvemapping_initialize(paint->brush->gpencil_settings->curve_sensitivity);
1702         curvemapping_initialize(paint->brush->gpencil_settings->curve_strength);
1703         curvemapping_initialize(paint->brush->gpencil_settings->curve_jitter);
1704
1705         /* assign to temp tGPsdata */
1706         p->brush = paint->brush;
1707         if (paint->brush->gpencil_tool != GPAINT_TOOL_ERASE) {
1708                 p->eraser = gp_get_default_eraser(p->bmain, ts);
1709         }
1710         else {
1711                 p->eraser = paint->brush;
1712         }
1713         /* use radius of eraser */
1714         p->radius = (short)p->eraser->size;
1715
1716         /* GPXX: Need this update to synchronize brush with draw manager.
1717          * Maybe this update can be removed when the new tool system
1718          * will be in place, but while, we need this to keep drawing working.
1719          */
1720         DEG_id_tag_update(&scene->id, ID_RECALC_COPY_ON_WRITE);
1721 }
1722
1723
1724 /* initialize a paint brush and a default color if not exist */
1725 static void gp_init_colors(tGPsdata *p)
1726 {
1727         bGPdata *gpd = p->gpd;
1728         Brush *brush = p->brush;
1729
1730         Material *ma = NULL;
1731         MaterialGPencilStyle *gp_style = NULL;
1732
1733         /* use brush material */
1734         ma = BKE_gpencil_get_material_from_brush(brush);
1735
1736         /* if no brush defaults, get material and color info
1737          * NOTE: Ensures that everything we need will exist...
1738          */
1739         if ((ma == NULL) || (ma->gp_style == NULL)) {
1740                 BKE_gpencil_material_ensure(p->bmain, p->ob);
1741
1742                 /* assign always the first material to the brush */
1743                 p->material = give_current_material(p->ob, 1);
1744                 brush->gpencil_settings->material = p->material;
1745         }
1746         else {
1747                 p->material = ma;
1748         }
1749
1750         /* check if the material is already on object material slots and add it if missing */
1751         if (BKE_gpencil_get_material_index(p->ob, p->material) == 0) {
1752                 BKE_object_material_slot_add(p->bmain, p->ob);
1753                 assign_material(p->bmain, p->ob, ma, p->ob->totcol, BKE_MAT_ASSIGN_USERPREF);
1754         }
1755
1756         /* assign color information to temp tGPsdata */
1757         gp_style = p->material->gp_style;
1758         if (gp_style) {
1759
1760                 /* set colors */
1761                 copy_v4_v4(gpd->runtime.scolor, gp_style->stroke_rgba);
1762                 copy_v4_v4(gpd->runtime.sfill, gp_style->fill_rgba);
1763                 /* add some alpha to make easy the filling without hide strokes */
1764                 if (gpd->runtime.sfill[3] > 0.8f) {
1765                         gpd->runtime.sfill[3] = 0.8f;
1766                 }
1767
1768                 gpd->runtime.mode = (short)gp_style->mode;
1769                 gpd->runtime.bstroke_style = gp_style->stroke_style;
1770                 gpd->runtime.bfill_style = gp_style->fill_style;
1771         }
1772 }
1773
1774 /* (re)init new painting data */
1775 static bool gp_session_initdata(bContext *C, wmOperator *op, tGPsdata *p)
1776 {
1777         Main *bmain = CTX_data_main(C);
1778         bGPdata **gpd_ptr = NULL;
1779         ScrArea *curarea = CTX_wm_area(C);
1780         ARegion *ar = CTX_wm_region(C);
1781         ToolSettings *ts = CTX_data_tool_settings(C);
1782         Object *obact = CTX_data_active_object(C);
1783
1784         /* make sure the active view (at the starting time) is a 3d-view */
1785         if (curarea == NULL) {
1786                 p->status = GP_STATUS_ERROR;
1787                 if (G.debug & G_DEBUG)
1788                         printf("Error: No active view for painting\n");
1789                 return 0;
1790         }
1791
1792         /* pass on current scene and window */
1793         p->C = C;
1794         p->bmain = CTX_data_main(C);
1795         p->scene = CTX_data_scene(C);
1796         p->depsgraph = CTX_data_depsgraph(C);
1797         p->win = CTX_wm_window(C);
1798         p->disable_fill = RNA_boolean_get(op->ptr, "disable_fill");
1799
1800         unit_m4(p->imat);
1801         unit_m4(p->mat);
1802
1803         switch (curarea->spacetype) {
1804                 /* supported views first */
1805                 case SPACE_VIEW3D:
1806                 {
1807                         /* View3D *v3d = curarea->spacedata.first; */
1808                         /* RegionView3D *rv3d = ar->regiondata; */
1809
1810                         /* set current area
1811                          * - must verify that region data is 3D-view (and not something else)
1812                          */
1813                          /* CAUTION: If this is the "toolbar", then this will change on the first stroke */
1814                         p->sa = curarea;
1815                         p->ar = ar;
1816                         p->align_flag = &ts->gpencil_v3d_align;
1817
1818                         if (ar->regiondata == NULL) {
1819                                 p->status = GP_STATUS_ERROR;
1820                                 if (G.debug & G_DEBUG)
1821                                         printf("Error: 3D-View active region doesn't have any region data, so cannot be drawable\n");
1822                                 return 0;
1823                         }
1824
1825                         if ((!obact) || (obact->type != OB_GPENCIL)) {
1826                                 View3D *v3d = p->sa->spacedata.first;
1827                                 /* if active object doesn't exist or isn't a GP Object, create one */
1828                                 const float *cur = p->scene->cursor.location;
1829
1830                                 ushort local_view_bits = 0;
1831                                 if (v3d->localvd) {
1832                                         local_view_bits = v3d->local_view_uuid;
1833                                 }
1834                                 /* create new default object */
1835                                 obact = ED_gpencil_add_object(C, p->scene, cur, local_view_bits);
1836                         }
1837                         /* assign object after all checks to be sure we have one active */
1838                         p->ob = obact;
1839
1840                         break;
1841                 }
1842
1843                 /* unsupported views */
1844                 default:
1845                 {
1846                         p->status = GP_STATUS_ERROR;
1847                         if (G.debug & G_DEBUG)
1848                                 printf("Error: Active view not appropriate for Grease Pencil drawing\n");
1849                         return 0;
1850                 }
1851         }
1852
1853         /* get gp-data */
1854         gpd_ptr = ED_gpencil_data_get_pointers(C, &p->ownerPtr);
1855         if ((gpd_ptr == NULL) || ED_gpencil_data_owner_is_annotation(&p->ownerPtr)) {
1856                 p->status = GP_STATUS_ERROR;
1857                 if (G.debug & G_DEBUG)
1858                         printf("Error: Current context doesn't allow for any Grease Pencil data\n");
1859                 return 0;
1860         }
1861         else {
1862                 /* if no existing GPencil block exists, add one */
1863                 if (*gpd_ptr == NULL)
1864                         *gpd_ptr = BKE_gpencil_data_addnew(bmain, "GPencil");
1865                 p->gpd = *gpd_ptr;
1866         }
1867
1868         if (ED_gpencil_session_active() == 0) {
1869                 /* initialize undo stack,
1870                  * also, existing undo stack would make buffer drawn
1871                  */
1872                 gpencil_undo_init(p->gpd);
1873         }
1874
1875         /* clear out buffer (stored in gp-data), in case something contaminated it */
1876         gp_session_validatebuffer(p);
1877
1878         /* set brush and create a new one if null */
1879         gp_init_drawing_brush(C, p);
1880
1881         /* setup active color */
1882         if (curarea->spacetype == SPACE_VIEW3D) {
1883                 /* NOTE: This is only done for 3D view, as Materials aren't used for
1884                  *       annotations in 2D editors
1885                  */
1886                 gp_init_colors(p);
1887         }
1888
1889         /* lock axis (in some modes, disable) */
1890         if (((*p->align_flag & GP_PROJECT_DEPTH_VIEW) == 0) &&
1891             ((*p->align_flag & GP_PROJECT_DEPTH_STROKE) == 0))
1892         {
1893                 p->lock_axis = ts->gp_sculpt.lock_axis;
1894         }
1895         else {
1896                 p->lock_axis = 0;
1897         }
1898
1899         /* region where paint was originated */
1900         p->gpd->runtime.ar = CTX_wm_region(C);
1901
1902         return 1;
1903 }
1904
1905 /* init new painting session */
1906 static tGPsdata *gp_session_initpaint(bContext *C, wmOperator *op)
1907 {
1908         tGPsdata *p = NULL;
1909
1910         /* Create new context data */
1911         p = MEM_callocN(sizeof(tGPsdata), "GPencil Drawing Data");
1912
1913         /* Try to initialise context data
1914          * WARNING: This may not always succeed (e.g. using GP in an annotation-only context)
1915          */
1916         if (gp_session_initdata(C, op, p) == 0) {
1917                 /* Invalid state - Exit
1918                  * NOTE: It should be safe to just free the data, since failing context checks should
1919                  * only happen when no data has been allocated.
1920                  */
1921                 MEM_freeN(p);
1922                 return NULL;
1923         }
1924
1925         /* Random generator, only init once. */
1926         uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX);
1927         rng_seed ^= POINTER_AS_UINT(p);
1928         p->rng = BLI_rng_new(rng_seed);
1929
1930         /* return context data for running paint operator */
1931         return p;
1932 }
1933
1934 /* cleanup after a painting session */
1935 static void gp_session_cleanup(tGPsdata *p)
1936 {
1937         bGPdata *gpd = (p) ? p->gpd : NULL;
1938
1939         /* error checking */
1940         if (gpd == NULL)
1941                 return;
1942
1943         /* free stroke buffer */
1944         if (gpd->runtime.sbuffer) {
1945                 /* printf("\t\tGP - free sbuffer\n"); */
1946                 MEM_freeN(gpd->runtime.sbuffer);
1947                 gpd->runtime.sbuffer = NULL;
1948         }
1949
1950         /* clear flags */
1951         gpd->runtime.sbuffer_size = 0;
1952         gpd->runtime.sbuffer_sflag = 0;
1953         p->inittime = 0.0;
1954 }
1955
1956 static void gp_session_free(tGPsdata *p)
1957 {
1958         if (p->rng != NULL) {
1959                 BLI_rng_free(p->rng);
1960         }
1961         MEM_freeN(p);
1962 }
1963
1964
1965 /* init new stroke */
1966 static void gp_paint_initstroke(tGPsdata *p, eGPencil_PaintModes paintmode, Depsgraph *depsgraph)
1967 {
1968         Scene *scene = p->scene;
1969         ToolSettings *ts = scene->toolsettings;
1970         int cfra_eval = (int)DEG_get_ctime(p->depsgraph);
1971
1972         /* get active layer (or add a new one if non-existent) */
1973         p->gpl = BKE_gpencil_layer_getactive(p->gpd);
1974         if (p->gpl == NULL) {
1975                 p->gpl = BKE_gpencil_layer_addnew(p->gpd, DATA_("GP_Layer"), true);
1976
1977                 if (p->custom_color[3])
1978                         copy_v3_v3(p->gpl->color, p->custom_color);
1979         }
1980         if (p->gpl->flag & GP_LAYER_LOCKED) {
1981                 p->status = GP_STATUS_ERROR;
1982                 if (G.debug & G_DEBUG)
1983                         printf("Error: Cannot paint on locked layer\n");
1984                 return;
1985         }
1986
1987         /* get active frame (add a new one if not matching frame) */
1988         if (paintmode == GP_PAINTMODE_ERASER) {
1989                 /* Eraser mode:
1990                  * 1) Add new frames to all frames that we might touch,
1991                  * 2) Ensure that p->gpf refers to the frame used for the active layer
1992                  *    (to avoid problems with other tools which expect it to exist)
1993                  */
1994                 bool has_layer_to_erase = false;
1995
1996                 for (bGPDlayer *gpl = p->gpd->layers.first; gpl; gpl = gpl->next) {
1997                         /* Skip if layer not editable */
1998                         if (gpencil_layer_is_editable(gpl) == false)
1999                                 continue;
2000
2001                         /* Add a new frame if needed (and based off the active frame,
2002                          * as we need some existing strokes to erase)
2003                          *
2004                          * Note: We don't add a new frame if there's nothing there now, so
2005                          *       -> If there are no frames at all, don't add one
2006                          *       -> If there are no strokes in that frame, don't add a new empty frame
2007                          */
2008                         if (gpl->actframe && gpl->actframe->strokes.first) {
2009                                 gpl->actframe = BKE_gpencil_layer_getframe(gpl, cfra_eval, GP_GETFRAME_ADD_COPY);
2010                                 has_layer_to_erase = true;
2011                         }
2012
2013                         /* XXX: we omit GP_FRAME_PAINT here for now,
2014                          * as it is only really useful for doing
2015                          * paintbuffer drawing
2016                          */
2017                 }
2018
2019                 /* Ensure this gets set... */
2020                 p->gpf = p->gpl->actframe;
2021
2022                 /* Restrict eraser to only affecting selected strokes, if the "selection mask" is on
2023                  * (though this is only available in editmode)
2024                  */
2025                 if (p->gpd->flag & GP_DATA_STROKE_EDITMODE) {
2026                         if (ts->gp_sculpt.flag & GP_SCULPT_SETT_FLAG_SELECT_MASK) {
2027                                 p->flags |= GP_PAINTFLAG_SELECTMASK;
2028                         }
2029                 }
2030
2031                 if (has_layer_to_erase == false) {
2032                         p->status = GP_STATUS_ERROR;
2033                         //if (G.debug & G_DEBUG)
2034                         printf("Error: Eraser will not be affecting anything (gpencil_paint_init)\n");
2035                         return;
2036                 }
2037         }
2038         else {
2039                 /* Drawing Modes - Add a new frame if needed on the active layer */
2040                 short add_frame_mode;
2041
2042                 if (ts->gpencil_flags & GP_TOOL_FLAG_RETAIN_LAST)
2043                         add_frame_mode = GP_GETFRAME_ADD_COPY;
2044                 else
2045                         add_frame_mode = GP_GETFRAME_ADD_NEW;
2046
2047                 p->gpf = BKE_gpencil_layer_getframe(p->gpl, cfra_eval, add_frame_mode);
2048                 /* set as dirty draw manager cache */
2049                 gp_update_cache(p->gpd);
2050
2051                 if (p->gpf == NULL) {
2052                         p->status = GP_STATUS_ERROR;
2053                         if (G.debug & G_DEBUG)
2054                                 printf("Error: No frame created (gpencil_paint_init)\n");
2055                         return;
2056                 }
2057                 else {
2058                         p->gpf->flag |= GP_FRAME_PAINT;
2059                 }
2060         }
2061
2062         /* set 'eraser' for this stroke if using eraser */
2063         p->paintmode = paintmode;
2064         if (p->paintmode == GP_PAINTMODE_ERASER) {
2065                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_ERASER;
2066
2067                 /* check if we should respect depth while erasing */
2068                 if (p->sa->spacetype == SPACE_VIEW3D) {
2069                         if (p->gpl->flag & GP_LAYER_NO_XRAY) {
2070                                 p->flags |= GP_PAINTFLAG_V3D_ERASER_DEPTH;
2071                         }
2072                 }
2073         }
2074         else {
2075                 /* disable eraser flags - so that we can switch modes during a session */
2076                 p->gpd->runtime.sbuffer_sflag &= ~GP_STROKE_ERASER;
2077
2078                 if (p->sa->spacetype == SPACE_VIEW3D) {
2079                         if (p->gpl->flag & GP_LAYER_NO_XRAY) {
2080                                 p->flags &= ~GP_PAINTFLAG_V3D_ERASER_DEPTH;
2081                         }
2082                 }
2083         }
2084
2085         /* set special fill stroke mode */
2086         if (p->disable_fill == true) {
2087                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_NOFILL;
2088                 /* replace stroke color with fill color */
2089                 copy_v4_v4(p->gpd->runtime.scolor, p->gpd->runtime.sfill);
2090         }
2091
2092         /* set 'initial run' flag, which is only used to denote when a new stroke is starting */
2093         p->flags |= GP_PAINTFLAG_FIRSTRUN;
2094
2095         /* when drawing in the camera view, in 2D space, set the subrect */
2096         p->subrect = NULL;
2097         if ((*p->align_flag & GP_PROJECT_VIEWSPACE) == 0) {
2098                 if (p->sa->spacetype == SPACE_VIEW3D) {
2099                         View3D *v3d = p->sa->spacedata.first;
2100                         RegionView3D *rv3d = p->ar->regiondata;
2101
2102                         /* for camera view set the subrect */
2103                         if (rv3d->persp == RV3D_CAMOB) {
2104                                 ED_view3d_calc_camera_border(p->scene, depsgraph, p->ar, v3d, rv3d, &p->subrect_data, true); /* no shift */
2105                                 p->subrect = &p->subrect_data;
2106                         }
2107                 }
2108         }
2109
2110         /* init stroke point space-conversion settings... */
2111         p->gsc.gpd = p->gpd;
2112         p->gsc.gpl = p->gpl;
2113
2114         p->gsc.sa = p->sa;
2115         p->gsc.ar = p->ar;
2116         p->gsc.v2d = p->v2d;
2117
2118         p->gsc.subrect_data = p->subrect_data;
2119         p->gsc.subrect = p->subrect;
2120
2121         copy_m4_m4(p->gsc.mat, p->mat);
2122
2123
2124         /* check if points will need to be made in view-aligned space */
2125         if (*p->align_flag & GP_PROJECT_VIEWSPACE) {
2126                 switch (p->sa->spacetype) {
2127                         case SPACE_VIEW3D:
2128                         {
2129                                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_3DSPACE;
2130                                 break;
2131                         }
2132                 }
2133         }
2134 }
2135
2136 /* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
2137 static void gp_paint_strokeend(tGPsdata *p)
2138 {
2139         ToolSettings *ts = p->scene->toolsettings;
2140         /* for surface sketching, need to set the right OpenGL context stuff so that
2141          * the conversions will project the values correctly...
2142          */
2143         if (gpencil_project_check(p)) {
2144                 View3D *v3d = p->sa->spacedata.first;
2145
2146                 /* need to restore the original projection settings before packing up */
2147                 view3d_region_operator_needs_opengl(p->win, p->ar);
2148                 ED_view3d_autodist_init(p->depsgraph, p->ar, v3d, (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
2149         }
2150
2151         /* check if doing eraser or not */
2152         if ((p->gpd->runtime.sbuffer_sflag & GP_STROKE_ERASER) == 0) {
2153                 /* transfer stroke to frame */
2154                 gp_stroke_newfrombuffer(p);
2155         }
2156
2157         /* clean up buffer now */
2158         gp_session_validatebuffer(p);
2159 }
2160
2161 /* finish off stroke painting operation */
2162 static void gp_paint_cleanup(tGPsdata *p)
2163 {
2164         /* p->gpd==NULL happens when stroke failed to initialize,
2165          * for example when GP is hidden in current space (sergey)
2166          */
2167         if (p->gpd) {
2168                 /* finish off a stroke */
2169                 gp_paint_strokeend(p);
2170         }
2171
2172         /* "unlock" frame */
2173         if (p->gpf)
2174                 p->gpf->flag &= ~GP_FRAME_PAINT;
2175 }
2176
2177 /* ------------------------------- */
2178
2179 /* Helper callback for drawing the cursor itself */
2180 static void gpencil_draw_eraser(bContext *UNUSED(C), int x, int y, void *p_ptr)
2181 {
2182         tGPsdata *p = (tGPsdata *)p_ptr;
2183
2184         if (p->paintmode == GP_PAINTMODE_ERASER) {
2185                 GPUVertFormat *format = immVertexFormat();
2186                 const uint shdr_pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2187                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2188
2189                 GPU_line_smooth(true);
2190                 GPU_blend(true);
2191                 GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
2192
2193                 immUniformColor4ub(255, 100, 100, 20);
2194                 imm_draw_circle_fill_2d(shdr_pos, x, y, p->radius, 40);
2195
2196                 immUnbindProgram();
2197
2198                 immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
2199
2200                 float viewport_size[4];
2201                 GPU_viewport_size_get_f(viewport_size);
2202                 immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
2203
2204                 immUniformColor4f(1.0f, 0.39f, 0.39f, 0.78f);
2205                 immUniform1i("colors_len", 0);  /* "simple" mode */
2206                 immUniform1f("dash_width", 12.0f);
2207                 immUniform1f("dash_factor", 0.5f);
2208
2209                 imm_draw_circle_wire_2d(shdr_pos, x, y, p->radius,
2210                         /* XXX Dashed shader gives bad results with sets of small segments currently,
2211                          *     temp hack around the issue. :( */
2212                         max_ii(8, p->radius / 2));  /* was fixed 40 */
2213
2214                 immUnbindProgram();
2215
2216                 GPU_blend(false);
2217                 GPU_line_smooth(false);
2218         }
2219 }
2220
2221 /* Turn brush cursor in 3D view on/off */
2222 static void gpencil_draw_toggle_eraser_cursor(bContext *C, tGPsdata *p, short enable)
2223 {
2224         if (p->erasercursor && !enable) {
2225                 /* clear cursor */
2226                 WM_paint_cursor_end(CTX_wm_manager(C), p->erasercursor);
2227                 p->erasercursor = NULL;
2228         }
2229         else if (enable && !p->erasercursor) {
2230                 ED_gpencil_toggle_brush_cursor(p->C, false, NULL);
2231                 /* enable cursor */
2232                 p->erasercursor = WM_paint_cursor_activate(
2233                         CTX_wm_manager(C),
2234                         SPACE_TYPE_ANY, RGN_TYPE_ANY,
2235                         NULL, /* XXX */
2236                         gpencil_draw_eraser, p);
2237         }
2238 }
2239
2240 /* Check if tablet eraser is being used (when processing events) */
2241 static bool gpencil_is_tablet_eraser_active(const wmEvent *event)
2242 {
2243         if (event->tablet_data) {
2244                 const wmTabletData *wmtab = event->tablet_data;
2245                 return (wmtab->Active == EVT_TABLET_ERASER);
2246         }
2247
2248         return false;
2249 }
2250
2251 /* ------------------------------- */
2252
2253 static void gpencil_draw_exit(bContext *C, wmOperator *op)
2254 {
2255         tGPsdata *p = op->customdata;
2256
2257         /* don't assume that operator data exists at all */
2258         if (p) {
2259                 /* check size of buffer before cleanup, to determine if anything happened here */
2260                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2261                         /* turn off radial brush cursor */
2262                         gpencil_draw_toggle_eraser_cursor(C, p, false);
2263                 }
2264
2265                 /* always store the new eraser size to be used again next time
2266                  * NOTE: Do this even when not in eraser mode, as eraser may
2267                  *       have been toggled at some point.
2268                  */
2269                 if (p->eraser) {
2270                         p->eraser->size = p->radius;
2271                 }
2272
2273                 /* restore cursor to indicate end of drawing */
2274                 if (p->sa->spacetype != SPACE_VIEW3D) {
2275                         WM_cursor_modal_restore(CTX_wm_window(C));
2276                 }
2277                 else {
2278                         /* or restore paint if 3D view */
2279                         if ((p) && (p->paintmode == GP_PAINTMODE_ERASER)) {
2280                                 WM_cursor_modal_set(p->win, CURSOR_STD);
2281                         }
2282
2283                         /* drawing batch cache is dirty now */
2284                         bGPdata *gpd = CTX_data_gpencil_data(C);
2285                         if (gpd) {
2286                                 gpd->flag &= ~GP_DATA_STROKE_POLYGON;
2287                                 gp_update_cache(gpd);
2288                         }
2289                 }
2290
2291                 /* clear undo stack */
2292                 gpencil_undo_finish();
2293
2294                 /* cleanup */
2295                 gp_paint_cleanup(p);
2296                 gp_session_cleanup(p);
2297                 ED_gpencil_toggle_brush_cursor(C, true, NULL);
2298
2299                 /* finally, free the temp data */
2300                 gp_session_free(p);
2301                 p = NULL;
2302         }
2303
2304         op->customdata = NULL;
2305 }
2306
2307 static void gpencil_draw_cancel(bContext *C, wmOperator *op)
2308 {
2309         /* this is just a wrapper around exit() */
2310         gpencil_draw_exit(C, op);
2311 }
2312
2313 /* ------------------------------- */
2314
2315
2316 static int gpencil_draw_init(bContext *C, wmOperator *op, const wmEvent *event)
2317 {
2318         tGPsdata *p;
2319         eGPencil_PaintModes paintmode = RNA_enum_get(op->ptr, "mode");
2320         ToolSettings *ts = CTX_data_tool_settings(C);
2321         Brush *brush = BKE_paint_brush(&ts->gp_paint->paint);
2322
2323         /* if mode is draw and the brush is eraser, cancel */
2324         if (paintmode != GP_PAINTMODE_ERASER) {
2325                 if ((brush) && (brush->gpencil_tool == GPAINT_TOOL_ERASE)) {
2326                         return 0;
2327                 }
2328         }
2329
2330         /* check context */
2331         p = op->customdata = gp_session_initpaint(C, op);
2332         if ((p == NULL) || (p->status == GP_STATUS_ERROR)) {
2333                 /* something wasn't set correctly in context */
2334                 gpencil_draw_exit(C, op);
2335                 return 0;
2336         }
2337
2338         /* init painting data */
2339         gp_paint_initstroke(p, paintmode, CTX_data_depsgraph(C));
2340         if (p->status == GP_STATUS_ERROR) {
2341                 gpencil_draw_exit(C, op);
2342                 return 0;
2343         }
2344
2345         if (event != NULL) {
2346                 p->keymodifier = event->keymodifier;
2347         }
2348         else {
2349                 p->keymodifier = -1;
2350         }
2351
2352         p->reports = op->reports;
2353
2354         /* everything is now setup ok */
2355         return 1;
2356 }
2357
2358
2359 /* ------------------------------- */
2360
2361 /* ensure that the correct cursor icon is set */
2362 static void gpencil_draw_cursor_set(tGPsdata *p)
2363 {
2364         Brush *brush = p->brush;
2365         if ((p->paintmode == GP_PAINTMODE_ERASER) ||
2366             (brush->gpencil_tool == GPAINT_TOOL_ERASE))
2367         {
2368                 WM_cursor_modal_set(p->win, BC_CROSSCURSOR);  /* XXX need a better cursor */
2369         }
2370         else {
2371                 WM_cursor_modal_set(p->win,     CURSOR_NONE);
2372
2373         }
2374 }
2375
2376 /* update UI indicators of status, including cursor and header prints */
2377 static void gpencil_draw_status_indicators(bContext *C, tGPsdata *p)
2378 {
2379         /* header prints */
2380         switch (p->status) {
2381
2382 #if 0 /* FIXME, this never runs! */
2383                 switch (p->paintmode) {
2384                         case GP_PAINTMODE_DRAW_POLY:
2385                                 /* Provide usage tips, since this is modal, and unintuitive without hints */
2386                                 ED_workspace_status_text(
2387                                         C, IFACE_(
2388                                                 "Annotation Create Poly: LMB click to place next stroke vertex | "
2389                                                 "ESC/Enter to end  (or click outside this area)"
2390                                         ));
2391                                 break;
2392                         default:
2393                                 /* Do nothing - the others are self explanatory, exit quickly once the mouse is released
2394                                  * Showing any text would just be annoying as it would flicker.
2395                                  */
2396                                 break;
2397                 }
2398 #endif
2399
2400                 case GP_STATUS_IDLING:
2401                         /* print status info */
2402                         switch (p->paintmode) {
2403                                 case GP_PAINTMODE_ERASER:
2404                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Erase Session: Hold and drag LMB or RMB to erase | "
2405                                                 "ESC/Enter to end  (or click outside this area)"));
2406                                         break;
2407                                 case GP_PAINTMODE_DRAW_STRAIGHT:
2408                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Line Session: Hold and drag LMB to draw | "
2409                                                 "ESC/Enter to end  (or click outside this area)"));
2410                                         break;
2411                                 case GP_PAINTMODE_DRAW:
2412                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Freehand Session: Hold and drag LMB to draw"));
2413                                         break;
2414                                 case GP_PAINTMODE_DRAW_POLY:
2415                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Poly Session: LMB click to place next stroke vertex | "
2416                                                 "Release Shift/ESC/Enter to end  (or click outside this area)"));
2417                                         break;
2418
2419                                 default: /* unhandled future cases */
2420                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Session: ESC/Enter to end   (or click outside this area)"));
2421                                         break;
2422                         }
2423                         break;
2424
2425                 case GP_STATUS_ERROR:
2426                 case GP_STATUS_DONE:
2427                         /* clear status string */
2428                         ED_workspace_status_text(C, NULL);
2429                         break;
2430                 case GP_STATUS_PAINTING:
2431                         break;
2432         }
2433 }
2434
2435 /* ------------------------------- */
2436
2437 /* create a new stroke point at the point indicated by the painting context */
2438 static void gpencil_draw_apply(bContext *C, wmOperator *op, tGPsdata *p, Depsgraph *depsgraph)
2439 {
2440         bGPdata *gpd = p->gpd;
2441         tGPspoint *pt = NULL;
2442
2443         /* handle drawing/erasing -> test for erasing first */
2444         if (p->paintmode == GP_PAINTMODE_ERASER) {
2445                 /* do 'live' erasing now */
2446                 gp_stroke_doeraser(p);
2447
2448                 /* store used values */
2449                 p->mvalo[0] = p->mval[0];
2450                 p->mvalo[1] = p->mval[1];
2451                 p->opressure = p->pressure;
2452         }
2453         /* only add current point to buffer if mouse moved (even though we got an event, it might be just noise) */
2454         else if (gp_stroke_filtermval(p, p->mval, p->mvalo)) {
2455
2456                 /* if lazy mouse, interpolate the last and current mouse positions */
2457                 if (GPENCIL_LAZY_MODE(p->brush, p->shift)) {
2458                         float now_mouse[2];
2459                         float last_mouse[2];
2460                         copy_v2_v2(now_mouse, p->mval);
2461                         copy_v2_v2(last_mouse, p->mvalo);
2462                         interp_v2_v2v2(now_mouse, now_mouse, last_mouse, p->brush->smooth_stroke_factor);
2463                         copy_v2_v2(p->mval, now_mouse);
2464                 }
2465
2466                 /* try to add point */
2467                 short ok = gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
2468
2469                 /* handle errors while adding point */
2470                 if ((ok == GP_STROKEADD_FULL) || (ok == GP_STROKEADD_OVERFLOW)) {
2471                         /* finish off old stroke */
2472                         gp_paint_strokeend(p);
2473                         /* And start a new one!!! Else, projection errors! */
2474                         gp_paint_initstroke(p, p->paintmode, depsgraph);
2475
2476                         /* start a new stroke, starting from previous point */
2477                         /* XXX Must manually reset inittime... */
2478                         /* XXX We only need to reuse previous point if overflow! */
2479                         if (ok == GP_STROKEADD_OVERFLOW) {
2480                                 p->inittime = p->ocurtime;
2481                                 gp_stroke_addpoint(p, p->mvalo, p->opressure, p->ocurtime);
2482                         }
2483                         else {
2484                                 p->inittime = p->curtime;
2485                         }
2486                         gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
2487                 }
2488                 else if (ok == GP_STROKEADD_INVALID) {
2489                         /* the painting operation cannot continue... */
2490                         BKE_report(op->reports, RPT_ERROR, "Cannot paint stroke");
2491                         p->status = GP_STATUS_ERROR;
2492
2493                         if (G.debug & G_DEBUG)
2494                                 printf("Error: Grease-Pencil Paint - Add Point Invalid\n");
2495                         return;
2496                 }
2497
2498                 /* store used values */
2499                 p->mvalo[0] = p->mval[0];
2500                 p->mvalo[1] = p->mval[1];
2501                 p->opressure = p->pressure;
2502                 p->ocurtime = p->curtime;
2503
2504                 pt = (tGPspoint *)gpd->runtime.sbuffer + gpd->runtime.sbuffer_size - 1;
2505                 if (p->paintmode != GP_PAINTMODE_ERASER) {
2506                         ED_gpencil_toggle_brush_cursor(C, true, &pt->x);
2507                 }
2508         }
2509         else if ((p->brush->gpencil_settings->flag & GP_BRUSH_STABILIZE_MOUSE_TEMP) &&
2510                  (gpd->runtime.sbuffer_size > 0))
2511         {
2512                 pt = (tGPspoint *)gpd->runtime.sbuffer + gpd->runtime.sbuffer_size - 1;
2513                 if (p->paintmode != GP_PAINTMODE_ERASER) {
2514                         ED_gpencil_toggle_brush_cursor(C, true, &pt->x);
2515                 }
2516         }
2517 }
2518
2519 /* handle draw event */
2520 static void gpencil_draw_apply_event(bContext *C, wmOperator *op, const wmEvent *event, Depsgraph *depsgraph, float x, float y)
2521 {
2522         tGPsdata *p = op->customdata;
2523         PointerRNA itemptr;
2524         float mousef[2];
2525         int tablet = 0;
2526
2527         /* convert from window-space to area-space mouse coordinates
2528          * add any x,y override position for fake events
2529          * NOTE: float to ints conversions, +1 factor is probably used to ensure a bit more accurate rounding...
2530          */
2531         p->mval[0] = event->mval[0] + 1.0f - x;
2532         p->mval[1] = event->mval[1] + 1.0f - y;
2533         p->shift = event->shift;
2534
2535         /* verify key status for straight lines */
2536         if ((event->alt > 0) && (RNA_boolean_get(op->ptr, "disable_straight") == false)) {
2537                 if (p->straight[0] == 0) {
2538                         int dx = (int)fabsf(p->mval[0] - p->mvalo[0]);
2539                         int dy = (int)fabsf(p->mval[1] - p->mvalo[1]);
2540                         if ((dx > 0) || (dy > 0)) {
2541                                 /* check mouse direction to replace the other coordinate with previous values */
2542                                 if (dx >= dy) {
2543                                         /* horizontal */
2544                                         p->straight[0] = 1;
2545                                         p->straight[1] = (short)p->mval[1]; /* save y */
2546                                 }
2547                                 else {
2548                                         /* vertical */
2549                                         p->straight[0] = 2;
2550                                         p->straight[1] = (short)p->mval[0]; /* save x */
2551                                 }
2552                         }
2553                 }
2554         }
2555         else {
2556                 p->straight[0] = 0;
2557         }
2558
2559         p->curtime = PIL_check_seconds_timer();
2560
2561         /* handle pressure sensitivity (which is supplied by tablets) */
2562         if (event->tablet_data) {
2563                 const wmTabletData *wmtab = event->tablet_data;
2564
2565                 tablet = (wmtab->Active != EVT_TABLET_NONE);
2566                 p->pressure = wmtab->Pressure;
2567
2568                 /* Hack for pressure sensitive eraser on D+RMB when using a tablet:
2569                  * The pen has to float over the tablet surface, resulting in
2570                  * zero pressure (T47101). Ignore pressure values if floating
2571                  * (i.e. "effectively zero" pressure), and only when the "active"
2572                  * end is the stylus (i.e. the default when not eraser)
2573                  */
2574                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2575                         if ((wmtab->Active != EVT_TABLET_ERASER) && (p->pressure < 0.001f)) {
2576                                 p->pressure = 1.0f;
2577                         }
2578                 }
2579         }
2580         else {
2581                 /* No tablet data -> No pressure info is available */
2582                 p->pressure = 1.0f;
2583         }
2584
2585         /* special eraser modes */
2586         if (p->paintmode == GP_PAINTMODE_ERASER) {
2587                 if (event->shift > 0) {
2588                         p->flags |= GP_PAINTFLAG_HARD_ERASER;
2589                 }
2590                 else {
2591                         p->flags &= ~GP_PAINTFLAG_HARD_ERASER;
2592                 }
2593                 if (event->alt > 0) {
2594                         p->flags |= GP_PAINTFLAG_STROKE_ERASER;
2595                 }
2596                 else {
2597                         p->flags &= ~GP_PAINTFLAG_STROKE_ERASER;
2598                 }
2599         }
2600
2601         /* special exception for start of strokes (i.e. maybe for just a dot) */
2602         if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
2603                 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
2604
2605                 p->mvalo[0] = p->mval[0];
2606                 p->mvalo[1] = p->mval[1];
2607                 p->opressure = p->pressure;
2608                 p->inittime = p->ocurtime = p->curtime;
2609                 p->straight[0] = 0;
2610                 p->straight[1] = 0;
2611
2612                 /* special exception here for too high pressure values on first touch in
2613                  * windows for some tablets, then we just skip first touch...
2614                  */
2615                 if (tablet && (p->pressure >= 0.99f))
2616                         return;
2617         }
2618
2619         /* check if alt key is pressed and limit to straight lines */
2620         if ((p->paintmode != GP_PAINTMODE_ERASER) && (p->straight[0] != 0)) {
2621                 if (p->straight[0] == 1) {
2622                         /* horizontal */
2623                         p->mval[1] = p->straight[1]; /* replace y */
2624                 }
2625                 else {
2626                         /* vertical */
2627                         p->mval[0] = p->straight[1]; /* replace x */
2628                 }
2629         }
2630
2631         /* fill in stroke data (not actually used directly by gpencil_draw_apply) */
2632         RNA_collection_add(op->ptr, "stroke", &itemptr);
2633
2634         mousef[0] = p->mval[0];
2635         mousef[1] = p->mval[1];
2636         RNA_float_set_array(&itemptr, "mouse", mousef);
2637         RNA_float_set(&itemptr, "pressure", p->pressure);
2638         RNA_boolean_set(&itemptr, "is_start", (p->flags & GP_PAINTFLAG_FIRSTRUN) != 0);
2639
2640         RNA_float_set(&itemptr, "time", p->curtime - p->inittime);
2641
2642         /* apply the current latest drawing point */
2643         gpencil_draw_apply(C, op, p, depsgraph);
2644
2645         /* force refresh */
2646         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
2647 }
2648
2649 /* ------------------------------- */
2650
2651 /* operator 'redo' (i.e. after changing some properties, but also for repeat last) */
2652 static int gpencil_draw_exec(bContext *C, wmOperator *op)
2653 {
2654         tGPsdata *p = NULL;
2655         Depsgraph *depsgraph = CTX_data_depsgraph(C);
2656
2657         /* printf("GPencil - Starting Re-Drawing\n"); */
2658
2659         /* try to initialize context data needed while drawing */
2660         if (!gpencil_draw_init(C, op, NULL)) {
2661                 MEM_SAFE_FREE(op->customdata);
2662                 /* printf("\tGP - no valid data\n"); */
2663                 return OPERATOR_CANCELLED;
2664         }
2665         else
2666                 p = op->customdata;
2667
2668         /* printf("\tGP - Start redrawing stroke\n"); */
2669
2670         /* loop over the stroke RNA elements recorded (i.e. progress of mouse movement),
2671          * setting the relevant values in context at each step, then applying
2672          */
2673         RNA_BEGIN(op->ptr, itemptr, "stroke")
2674         {
2675                 float mousef[2];
2676
2677                 /* printf("\t\tGP - stroke elem\n"); */
2678
2679                 /* get relevant data for this point from stroke */
2680                 RNA_float_get_array(&itemptr, "mouse", mousef);
2681                 p->mval[0] = (int)mousef[0];
2682                 p->mval[1] = (int)mousef[1];
2683                 p->pressure = RNA_float_get(&itemptr, "pressure");
2684                 p->curtime = (double)RNA_float_get(&itemptr, "time") + p->inittime;
2685
2686                 if (RNA_boolean_get(&itemptr, "is_start")) {
2687                         /* if first-run flag isn't set already (i.e. not true first stroke),
2688                          * then we must terminate the previous one first before continuing
2689                          */
2690                         if ((p->flags & GP_PAINTFLAG_FIRSTRUN) == 0) {
2691                                 /* TODO: both of these ops can set error-status, but we probably don't need to worry */
2692                                 gp_paint_strokeend(p);
2693                                 gp_paint_initstroke(p, p->paintmode, depsgraph);
2694                         }
2695                 }
2696
2697                 /* if first run, set previous data too */
2698                 if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
2699                         p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
2700
2701                         p->mvalo[0] = p->mval[0];
2702                         p->mvalo[1] = p->mval[1];
2703                         p->opressure = p->pressure;
2704                         p->ocurtime = p->curtime;
2705                 }
2706
2707                 /* apply this data as necessary now (as per usual) */
2708                 gpencil_draw_apply(C, op, p, depsgraph);
2709         }
2710         RNA_END;
2711
2712         /* printf("\tGP - done\n"); */
2713
2714         /* cleanup */
2715         gpencil_draw_exit(C, op);
2716
2717         /* refreshes */
2718         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2719
2720         /* done */
2721         return OPERATOR_FINISHED;
2722 }
2723
2724 /* ------------------------------- */
2725
2726 /* start of interactive drawing part of operator */
2727 static int gpencil_draw_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2728 {
2729         tGPsdata *p = NULL;
2730
2731         if (G.debug & G_DEBUG)
2732                 printf("GPencil - Starting Drawing\n");
2733
2734         /* support for tablets eraser pen */
2735         if (gpencil_is_tablet_eraser_active(event)) {
2736                 RNA_enum_set(op->ptr, "mode", GP_PAINTMODE_ERASER);
2737         }
2738
2739         /* try to initialize context data needed while drawing */
2740         if (!gpencil_draw_init(C, op, event)) {
2741                 if (op->customdata)
2742                         MEM_freeN(op->customdata);
2743                 if (G.debug & G_DEBUG)
2744                         printf("\tGP - no valid data\n");
2745                 return OPERATOR_CANCELLED;
2746         }
2747         else
2748                 p = op->customdata;
2749
2750         /* TODO: set any additional settings that we can take from the events?
2751          * TODO? if tablet is erasing, force eraser to be on? */
2752
2753          /* TODO: move cursor setting stuff to stroke-start so that paintmode can be changed midway... */
2754
2755          /* if eraser is on, draw radial aid */
2756         if (p->paintmode == GP_PAINTMODE_ERASER) {
2757                 gpencil_draw_toggle_eraser_cursor(C, p, true);
2758         }
2759         else {
2760                 ED_gpencil_toggle_brush_cursor(C, true, NULL);
2761         }
2762         /* set cursor
2763          * NOTE: This may change later (i.e. intentionally via brush toggle,
2764          *       or unintentionally if the user scrolls outside the area)...
2765          */
2766         gpencil_draw_cursor_set(p);
2767
2768         /* only start drawing immediately if we're allowed to do so... */
2769         if (RNA_boolean_get(op->ptr, "wait_for_input") == false) {
2770                 /* hotkey invoked - start drawing */
2771                 /* printf("\tGP - set first spot\n"); */
2772                 p->status = GP_STATUS_PAINTING;
2773
2774                 /* handle the initial drawing - i.e. for just doing a simple dot */
2775                 gpencil_draw_apply_event(C, op, event, CTX_data_depsgraph(C), 0, 0);
2776                 op->flag |= OP_IS_MODAL_CURSOR_REGION;
2777         }
2778         else {
2779                 /* toolbar invoked - don't start drawing yet... */
2780                 /* printf("\tGP - hotkey invoked... waiting for click-drag\n"); */
2781                 op->flag |= OP_IS_MODAL_CURSOR_REGION;
2782         }
2783
2784         /* enable paint mode */
2785         if (p->sa->spacetype == SPACE_VIEW3D) {
2786                 Object *ob = CTX_data_active_object(C);
2787                 if (ob && (ob->type == OB_GPENCIL) && ((p->gpd->flag & GP_DATA_STROKE_PAINTMODE) == 0)) {
2788                         /* FIXME: use the mode switching operator, this misses notifiers, messages. */
2789                         /* Just set paintmode flag... */
2790                         p->gpd->flag |= GP_DATA_STROKE_PAINTMODE;
2791                         /* disable other GP modes */
2792                         p->gpd->flag &= ~GP_DATA_STROKE_EDITMODE;
2793                         p->gpd->flag &= ~GP_DATA_STROKE_SCULPTMODE;
2794                         p->gpd->flag &= ~GP_DATA_STROKE_WEIGHTMODE;
2795                         /* set workspace mode */
2796                         ob->restore_mode = ob->mode;
2797                         ob->mode = OB_MODE_PAINT_GPENCIL;
2798                         /* redraw mode on screen */
2799                         WM_event_add_notifier(C, NC_SCENE | ND_MODE, NULL);
2800                 }
2801         }
2802
2803         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2804
2805         /* add a modal handler for this operator, so that we can then draw continuous strokes */
2806         WM_event_add_modal_handler(C, op);
2807
2808         return OPERATOR_RUNNING_MODAL;
2809 }
2810
2811 /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
2812 static bool gpencil_area_exists(bContext *C, ScrArea *sa_test)
2813 {
2814         bScreen *sc = CTX_wm_screen(C);
2815         return (BLI_findindex(&sc->areabase, sa_test) != -1);
2816 }
2817
2818 static tGPsdata *gpencil_stroke_begin(bContext *C, wmOperator *op)
2819 {
2820         tGPsdata *p = op->customdata;
2821
2822         /* we must check that we're still within the area that we're set up to work from
2823          * otherwise we could crash (see bug #20586)
2824          */
2825         if (CTX_wm_area(C) != p->sa) {
2826                 printf("\t\t\tGP - wrong area execution abort!\n");
2827                 p->status = GP_STATUS_ERROR;
2828         }
2829
2830         /* printf("\t\tGP - start stroke\n"); */
2831
2832         /* we may need to set up paint env again if we're resuming */
2833         /* XXX: watch it with the paintmode! in future,
2834          *      it'd be nice to allow changing paint-mode when in sketching-sessions */
2835
2836         if (gp_session_initdata(C, op, p))
2837                 gp_paint_initstroke(p, p->paintmode, CTX_data_depsgraph(C));
2838
2839         if (p->status != GP_STATUS_ERROR) {
2840                 p->status = GP_STATUS_PAINTING;
2841                 op->flag &= ~OP_IS_MODAL_CURSOR_REGION;
2842         }
2843
2844         return op->customdata;
2845 }
2846
2847 static void gpencil_stroke_end(wmOperator *op)
2848 {
2849         tGPsdata *p = op->customdata;
2850
2851         gp_paint_cleanup(p);
2852
2853         gpencil_undo_push(p->gpd);
2854
2855         gp_session_cleanup(p);
2856
2857         p->status = GP_STATUS_IDLING;
2858         op->flag |= OP_IS_MODAL_CURSOR_REGION;
2859
2860         p->gpd = NULL;
2861         p->gpl = NULL;
2862         p->gpf = NULL;
2863 }
2864
2865 /* Move last stroke in the listbase to the head to be drawn below all previous strokes in the layer */
2866 static void gpencil_move_last_stroke_to_back(bContext *C)
2867 {
2868         /* move last stroke (the polygon) to head of the listbase stroke to draw on back of all previous strokes */
2869         bGPdata *gpd = ED_gpencil_data_get_active(C);
2870         bGPDlayer *gpl = BKE_gpencil_layer_getactive(gpd);
2871
2872         /* sanity checks */
2873         if (ELEM(NULL, gpd, gpl, gpl->actframe)) {
2874                 return;
2875         }
2876
2877         bGPDframe *gpf = gpl->actframe;
2878         bGPDstroke *gps = gpf->strokes.last;
2879         if (ELEM(NULL, gps)) {
2880                 return;
2881         }
2882
2883         BLI_remlink(&gpf->strokes, gps);
2884         BLI_insertlinkbefore(&gpf->strokes, gpf->strokes.first, gps);
2885 }
2886
2887 /* add events for missing mouse movements when the artist draw very fast */
2888 static void gpencil_add_missing_events(bContext *C, wmOperator *op, const wmEvent *event, tGPsdata *p)
2889 {
2890         Brush *brush = p->brush;
2891         if (brush->gpencil_settings->input_samples == 0) {
2892                 return;
2893         }
2894         RegionView3D *rv3d = p->ar->regiondata;
2895         float defaultpixsize = rv3d->pixsize * 1000.0f;
2896         int samples = (GP_MAX_INPUT_SAMPLES - brush->gpencil_settings->input_samples + 1);
2897         float thickness = (float)brush->size;
2898
2899         float pt[2], a[2], b[2];
2900         float vec[3];
2901         float scale = 1.0f;
2902
2903         /* get pixel scale */
2904         gp_get_3d_reference(p, vec);
2905         mul_m4_v3(rv3d->persmat, vec);
2906         if (rv3d->is_persp) {
2907                 scale = vec[2] * defaultpixsize;
2908         }
2909         else {
2910                 scale = defaultpixsize;
2911         }
2912
2913         /* The thickness of the brush is reduced of thickness to get overlap dots */
2914         float dot_factor = 0.50f;
2915         if (samples < 2) {
2916                 dot_factor = 0.05f;
2917         }
2918         else if (samples < 4) {
2919                 dot_factor = 0.10f;
2920         }
2921         else if (samples < 7) {
2922                 dot_factor = 0.3f;
2923         }
2924         else if (samples < 10) {
2925                 dot_factor = 0.4f;
2926         }
2927         float factor = ((thickness * dot_factor) / scale) * samples;
2928
2929         copy_v2_v2(a, p->mvalo);
2930         b[0] = event->mval[0] + 1;
2931         b[1] = event->mval[1] + 1;
2932
2933         /* get distance in pixels */
2934         float dist = len_v2v2(a, b);
2935
2936         /* for very small distances, add a half way point */
2937         if (dist <= 2.0f) {
2938                 interp_v2_v2v2(pt, a, b, 0.5f);
2939                 sub_v2_v2v2(pt, b, pt);
2940                 /* create fake event */
2941                 gpencil_draw_apply_event(C, op, event, CTX_data_depsgraph(C),
2942                         (int)pt[0], (int)pt[1]);
2943         }
2944         else if (dist >= factor) {
2945                 int slices = 2 + (int)((dist - 1.0) / factor);
2946                 float n = 1.0f / slices;
2947                 for (int i = 1; i < slices; i++) {
2948                         interp_v2_v2v2(pt, a, b, n * i);
2949                         sub_v2_v2v2(pt, b, pt);
2950                         /* create fake event */
2951                         gpencil_draw_apply_event(C, op, event, CTX_data_depsgraph(C),
2952                                 (int)pt[0], (int)pt[1]);
2953                 }
2954         }
2955 }
2956
2957 /* events handling during interactive drawing part of operator */
2958 static int gpencil_draw_modal(bContext *C, wmOperator *op, const wmEvent *event)
2959 {
2960         tGPsdata *p = op->customdata;
2961         ToolSettings *ts = CTX_data_tool_settings(C);
2962         int estate = OPERATOR_PASS_THROUGH; /* default exit state - pass through to support MMB view nav, etc. */
2963
2964         /* if (event->type == NDOF_MOTION)
2965          *    return OPERATOR_PASS_THROUGH;
2966          * -------------------------------
2967          * [mce] Not quite what I was looking
2968          * for, but a good start! GP continues to
2969          * draw on the screen while the 3D mouse
2970          * moves the viewpoint. Problem is that
2971          * the stroke is converted to 3D only after
2972          * it is finished. This approach should work
2973          * better in tools that immediately apply
2974          * in 3D space.
2975          */
2976
2977         if (p->status == GP_STATUS_IDLING) {
2978                 ARegion *ar = CTX_wm_region(C);
2979                 p->ar = ar;
2980         }
2981
2982         /* we don't pass on key events, GP is used with key-modifiers - prevents Dkey to insert drivers */
2983         if (ISKEYBOARD(event->type)) {
2984                 if (ELEM(event->type, LEFTARROWKEY, DOWNARROWKEY, RIGHTARROWKEY, UPARROWKEY, ZKEY)) {
2985                         /* allow some keys:
2986                          *   - for frame changing [#33412]
2987                          *   - for undo (during sketching sessions)
2988                          */
2989                 }
2990                 else if (ELEM(event->type, PAD0, PAD1, PAD2, PAD3, PAD4, PAD5, PAD6, PAD7, PAD8, PAD9)) {
2991                         /* allow numpad keys so that camera/view manipulations can still take place
2992                          * - PAD0 in particular is really important for Grease Pencil drawing,
2993                          *   as animators may be working "to camera", so having this working
2994                          *   is essential for ensuring that they can quickly return to that view
2995                          */
2996                 }
2997                 else if ((event->type == BKEY) && (event->val == KM_RELEASE)) {
2998                         /* Add Blank Frame
2999                          * - Since this operator is non-modal, we can just&nbs