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