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