GP: Use Fill color when drawing strokes for no stroke materials
[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 > 0)) {
759                         float pixsize = gp_style->texture_pixsize / 1000000.0f;
760                         tGPspoint *ptb = (tGPspoint *)gpd->runtime.sbuffer + gpd->runtime.sbuffer_size - 1;
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                 if (gp_style->flag & GP_STYLE_STROKE_SHOW) {
1850                         copy_v4_v4(gpd->runtime.scolor, gp_style->stroke_rgba);
1851                 }
1852                 else {
1853                         /* if no stroke, use fill */
1854                         copy_v4_v4(gpd->runtime.scolor, gp_style->fill_rgba);
1855                 }
1856                 copy_v4_v4(gpd->runtime.sfill, gp_style->fill_rgba);
1857                 /* add some alpha to make easy the filling without hide strokes */
1858                 if (gpd->runtime.sfill[3] > 0.8f) {
1859                         gpd->runtime.sfill[3] = 0.8f;
1860                 }
1861
1862                 gpd->runtime.mode = (short)gp_style->mode;
1863                 gpd->runtime.bstroke_style = gp_style->stroke_style;
1864                 gpd->runtime.bfill_style = gp_style->fill_style;
1865         }
1866 }
1867
1868 /* (re)init new painting data */
1869 static bool gp_session_initdata(bContext *C, wmOperator *op, tGPsdata *p)
1870 {
1871         Main *bmain = CTX_data_main(C);
1872         bGPdata **gpd_ptr = NULL;
1873         ScrArea *curarea = CTX_wm_area(C);
1874         ARegion *ar = CTX_wm_region(C);
1875         ToolSettings *ts = CTX_data_tool_settings(C);
1876         Object *obact = CTX_data_active_object(C);
1877
1878         /* make sure the active view (at the starting time) is a 3d-view */
1879         if (curarea == NULL) {
1880                 p->status = GP_STATUS_ERROR;
1881                 if (G.debug & G_DEBUG)
1882                         printf("Error: No active view for painting\n");
1883                 return 0;
1884         }
1885
1886         /* pass on current scene and window */
1887         p->C = C;
1888         p->bmain = CTX_data_main(C);
1889         p->scene = CTX_data_scene(C);
1890         p->depsgraph = CTX_data_depsgraph(C);
1891         p->win = CTX_wm_window(C);
1892         p->disable_fill = RNA_boolean_get(op->ptr, "disable_fill");
1893
1894         unit_m4(p->imat);
1895         unit_m4(p->mat);
1896
1897         switch (curarea->spacetype) {
1898                 /* supported views first */
1899                 case SPACE_VIEW3D:
1900                 {
1901                         /* View3D *v3d = curarea->spacedata.first; */
1902                         /* RegionView3D *rv3d = ar->regiondata; */
1903
1904                         /* set current area
1905                          * - must verify that region data is 3D-view (and not something else)
1906                          */
1907                          /* CAUTION: If this is the "toolbar", then this will change on the first stroke */
1908                         p->sa = curarea;
1909                         p->ar = ar;
1910                         p->align_flag = &ts->gpencil_v3d_align;
1911
1912                         if (ar->regiondata == NULL) {
1913                                 p->status = GP_STATUS_ERROR;
1914                                 if (G.debug & G_DEBUG)
1915                                         printf("Error: 3D-View active region doesn't have any region data, so cannot be drawable\n");
1916                                 return 0;
1917                         }
1918
1919                         if ((!obact) || (obact->type != OB_GPENCIL)) {
1920                                 View3D *v3d = p->sa->spacedata.first;
1921                                 /* if active object doesn't exist or isn't a GP Object, create one */
1922                                 const float *cur = p->scene->cursor.location;
1923
1924                                 ushort local_view_bits = 0;
1925                                 if (v3d->localvd) {
1926                                         local_view_bits = v3d->local_view_uuid;
1927                                 }
1928                                 /* create new default object */
1929                                 obact = ED_gpencil_add_object(C, p->scene, cur, local_view_bits);
1930                         }
1931                         /* assign object after all checks to be sure we have one active */
1932                         p->ob = obact;
1933
1934                         break;
1935                 }
1936
1937                 /* unsupported views */
1938                 default:
1939                 {
1940                         p->status = GP_STATUS_ERROR;
1941                         if (G.debug & G_DEBUG)
1942                                 printf("Error: Active view not appropriate for Grease Pencil drawing\n");
1943                         return 0;
1944                 }
1945         }
1946
1947         /* get gp-data */
1948         gpd_ptr = ED_gpencil_data_get_pointers(C, &p->ownerPtr);
1949         if ((gpd_ptr == NULL) || ED_gpencil_data_owner_is_annotation(&p->ownerPtr)) {
1950                 p->status = GP_STATUS_ERROR;
1951                 if (G.debug & G_DEBUG)
1952                         printf("Error: Current context doesn't allow for any Grease Pencil data\n");
1953                 return 0;
1954         }
1955         else {
1956                 /* if no existing GPencil block exists, add one */
1957                 if (*gpd_ptr == NULL)
1958                         *gpd_ptr = BKE_gpencil_data_addnew(bmain, "GPencil");
1959                 p->gpd = *gpd_ptr;
1960         }
1961
1962         if (ED_gpencil_session_active() == 0) {
1963                 /* initialize undo stack,
1964                  * also, existing undo stack would make buffer drawn
1965                  */
1966                 gpencil_undo_init(p->gpd);
1967         }
1968
1969         /* clear out buffer (stored in gp-data), in case something contaminated it */
1970         gp_session_validatebuffer(p);
1971
1972         /* set brush and create a new one if null */
1973         gp_init_drawing_brush(C, p);
1974
1975         /* setup active color */
1976         if (curarea->spacetype == SPACE_VIEW3D) {
1977                 /* NOTE: This is only done for 3D view, as Materials aren't used for
1978                  *       annotations in 2D editors
1979                  */
1980                 gp_init_colors(p);
1981         }
1982
1983         /* lock axis (in some modes, disable) */
1984         if (((*p->align_flag & GP_PROJECT_DEPTH_VIEW) == 0) &&
1985             ((*p->align_flag & GP_PROJECT_DEPTH_STROKE) == 0))
1986         {
1987                 p->lock_axis = ts->gp_sculpt.lock_axis;
1988         }
1989         else {
1990                 p->lock_axis = 0;
1991         }
1992
1993         /* region where paint was originated */
1994         p->gpd->runtime.ar = CTX_wm_region(C);
1995
1996         return 1;
1997 }
1998
1999 /* init new painting session */
2000 static tGPsdata *gp_session_initpaint(bContext *C, wmOperator *op)
2001 {
2002         tGPsdata *p = NULL;
2003
2004         /* Create new context data */
2005         p = MEM_callocN(sizeof(tGPsdata), "GPencil Drawing Data");
2006
2007         /* Try to initialise context data
2008          * WARNING: This may not always succeed (e.g. using GP in an annotation-only context)
2009          */
2010         if (gp_session_initdata(C, op, p) == 0) {
2011                 /* Invalid state - Exit
2012                  * NOTE: It should be safe to just free the data, since failing context checks should
2013                  * only happen when no data has been allocated.
2014                  */
2015                 MEM_freeN(p);
2016                 return NULL;
2017         }
2018
2019         /* Random generator, only init once. */
2020         uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX);
2021         rng_seed ^= POINTER_AS_UINT(p);
2022         p->rng = BLI_rng_new(rng_seed);
2023
2024         /* return context data for running paint operator */
2025         return p;
2026 }
2027
2028 /* cleanup after a painting session */
2029 static void gp_session_cleanup(tGPsdata *p)
2030 {
2031         bGPdata *gpd = (p) ? p->gpd : NULL;
2032
2033         /* error checking */
2034         if (gpd == NULL)
2035                 return;
2036
2037         /* free stroke buffer */
2038         if (gpd->runtime.sbuffer) {
2039                 /* printf("\t\tGP - free sbuffer\n"); */
2040                 MEM_SAFE_FREE(gpd->runtime.sbuffer);
2041                 gpd->runtime.sbuffer = NULL;
2042         }
2043
2044         /* clear flags */
2045         gpd->runtime.sbuffer_size = 0;
2046         gpd->runtime.sbuffer_sflag = 0;
2047         p->inittime = 0.0;
2048 }
2049
2050 static void gp_session_free(tGPsdata *p)
2051 {
2052         if (p->rng != NULL) {
2053                 BLI_rng_free(p->rng);
2054         }
2055
2056         MEM_freeN(p);
2057 }
2058
2059 /* init new stroke */
2060 static void gp_paint_initstroke(tGPsdata *p, eGPencil_PaintModes paintmode, Depsgraph *depsgraph)
2061 {
2062         Scene *scene = p->scene;
2063         ToolSettings *ts = scene->toolsettings;
2064         int cfra_eval = (int)DEG_get_ctime(p->depsgraph);
2065
2066         /* get active layer (or add a new one if non-existent) */
2067         p->gpl = BKE_gpencil_layer_getactive(p->gpd);
2068         if (p->gpl == NULL) {
2069                 p->gpl = BKE_gpencil_layer_addnew(p->gpd, DATA_("GP_Layer"), true);
2070
2071                 if (p->custom_color[3])
2072                         copy_v3_v3(p->gpl->color, p->custom_color);
2073         }
2074         if (p->gpl->flag & GP_LAYER_LOCKED) {
2075                 p->status = GP_STATUS_ERROR;
2076                 if (G.debug & G_DEBUG)
2077                         printf("Error: Cannot paint on locked layer\n");
2078                 return;
2079         }
2080
2081         /* get active frame (add a new one if not matching frame) */
2082         if (paintmode == GP_PAINTMODE_ERASER) {
2083                 /* Eraser mode:
2084                  * 1) Add new frames to all frames that we might touch,
2085                  * 2) Ensure that p->gpf refers to the frame used for the active layer
2086                  *    (to avoid problems with other tools which expect it to exist)
2087                  */
2088                 bool has_layer_to_erase = false;
2089
2090                 for (bGPDlayer *gpl = p->gpd->layers.first; gpl; gpl = gpl->next) {
2091                         /* Skip if layer not editable */
2092                         if (gpencil_layer_is_editable(gpl) == false)
2093                                 continue;
2094
2095                         /* Add a new frame if needed (and based off the active frame,
2096                          * as we need some existing strokes to erase)
2097                          *
2098                          * Note: We don't add a new frame if there's nothing there now, so
2099                          *       -> If there are no frames at all, don't add one
2100                          *       -> If there are no strokes in that frame, don't add a new empty frame
2101                          */
2102                         if (gpl->actframe && gpl->actframe->strokes.first) {
2103                                 gpl->actframe = BKE_gpencil_layer_getframe(gpl, cfra_eval, GP_GETFRAME_ADD_COPY);
2104                                 has_layer_to_erase = true;
2105                         }
2106
2107                         /* XXX: we omit GP_FRAME_PAINT here for now,
2108                          * as it is only really useful for doing
2109                          * paintbuffer drawing
2110                          */
2111                 }
2112
2113                 /* Ensure this gets set... */
2114                 p->gpf = p->gpl->actframe;
2115
2116                 /* Restrict eraser to only affecting selected strokes, if the "selection mask" is on
2117                  * (though this is only available in editmode)
2118                  */
2119                 if (p->gpd->flag & GP_DATA_STROKE_EDITMODE) {
2120                         if (ts->gp_sculpt.flag & GP_SCULPT_SETT_FLAG_SELECT_MASK) {
2121                                 p->flags |= GP_PAINTFLAG_SELECTMASK;
2122                         }
2123                 }
2124
2125                 if (has_layer_to_erase == false) {
2126                         p->status = GP_STATUS_ERROR;
2127                         //if (G.debug & G_DEBUG)
2128                         printf("Error: Eraser will not be affecting anything (gpencil_paint_init)\n");
2129                         return;
2130                 }
2131         }
2132         else {
2133                 /* Drawing Modes - Add a new frame if needed on the active layer */
2134                 short add_frame_mode;
2135
2136                 if (ts->gpencil_flags & GP_TOOL_FLAG_RETAIN_LAST)
2137                         add_frame_mode = GP_GETFRAME_ADD_COPY;
2138                 else
2139                         add_frame_mode = GP_GETFRAME_ADD_NEW;
2140
2141                 p->gpf = BKE_gpencil_layer_getframe(p->gpl, cfra_eval, add_frame_mode);
2142                 /* set as dirty draw manager cache */
2143                 gp_update_cache(p->gpd);
2144
2145                 if (p->gpf == NULL) {
2146                         p->status = GP_STATUS_ERROR;
2147                         if (G.debug & G_DEBUG)
2148                                 printf("Error: No frame created (gpencil_paint_init)\n");
2149                         return;
2150                 }
2151                 else {
2152                         p->gpf->flag |= GP_FRAME_PAINT;
2153                 }
2154         }
2155
2156         /* set 'eraser' for this stroke if using eraser */
2157         p->paintmode = paintmode;
2158         if (p->paintmode == GP_PAINTMODE_ERASER) {
2159                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_ERASER;
2160         }
2161         else {
2162                 /* disable eraser flags - so that we can switch modes during a session */
2163                 p->gpd->runtime.sbuffer_sflag &= ~GP_STROKE_ERASER;
2164         }
2165
2166         /* set special fill stroke mode */
2167         if (p->disable_fill == true) {
2168                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_NOFILL;
2169                 /* replace stroke color with fill color */
2170                 copy_v4_v4(p->gpd->runtime.scolor, p->gpd->runtime.sfill);
2171         }
2172
2173         /* set 'initial run' flag, which is only used to denote when a new stroke is starting */
2174         p->flags |= GP_PAINTFLAG_FIRSTRUN;
2175
2176         /* when drawing in the camera view, in 2D space, set the subrect */
2177         p->subrect = NULL;
2178         if ((*p->align_flag & GP_PROJECT_VIEWSPACE) == 0) {
2179                 if (p->sa->spacetype == SPACE_VIEW3D) {
2180                         View3D *v3d = p->sa->spacedata.first;
2181                         RegionView3D *rv3d = p->ar->regiondata;
2182
2183                         /* for camera view set the subrect */
2184                         if (rv3d->persp == RV3D_CAMOB) {
2185                                 /* no shift */
2186                                 ED_view3d_calc_camera_border(p->scene, depsgraph, p->ar, v3d, rv3d, &p->subrect_data, true);
2187                                 p->subrect = &p->subrect_data;
2188                         }
2189                 }
2190         }
2191
2192         /* init stroke point space-conversion settings... */
2193         p->gsc.gpd = p->gpd;
2194         p->gsc.gpl = p->gpl;
2195
2196         p->gsc.sa = p->sa;
2197         p->gsc.ar = p->ar;
2198         p->gsc.v2d = p->v2d;
2199
2200         p->gsc.subrect_data = p->subrect_data;
2201         p->gsc.subrect = p->subrect;
2202
2203         copy_m4_m4(p->gsc.mat, p->mat);
2204
2205
2206         /* check if points will need to be made in view-aligned space */
2207         if (*p->align_flag & GP_PROJECT_VIEWSPACE) {
2208                 switch (p->sa->spacetype) {
2209                         case SPACE_VIEW3D:
2210                         {
2211                                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_3DSPACE;
2212                                 break;
2213                         }
2214                 }
2215         }
2216 }
2217
2218 /* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
2219 static void gp_paint_strokeend(tGPsdata *p)
2220 {
2221         ToolSettings *ts = p->scene->toolsettings;
2222         /* for surface sketching, need to set the right OpenGL context stuff so that
2223          * the conversions will project the values correctly...
2224          */
2225         if (gpencil_project_check(p)) {
2226                 View3D *v3d = p->sa->spacedata.first;
2227
2228                 /* need to restore the original projection settings before packing up */
2229                 view3d_region_operator_needs_opengl(p->win, p->ar);
2230                 ED_view3d_autodist_init(p->depsgraph, p->ar, v3d, (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
2231         }
2232
2233         /* check if doing eraser or not */
2234         if ((p->gpd->runtime.sbuffer_sflag & GP_STROKE_ERASER) == 0) {
2235                 /* transfer stroke to frame */
2236                 gp_stroke_newfrombuffer(p);
2237         }
2238
2239         /* clean up buffer now */
2240         gp_session_validatebuffer(p);
2241 }
2242
2243 /* finish off stroke painting operation */
2244 static void gp_paint_cleanup(tGPsdata *p)
2245 {
2246         /* p->gpd==NULL happens when stroke failed to initialize,
2247          * for example when GP is hidden in current space (sergey)
2248          */
2249         if (p->gpd) {
2250                 /* finish off a stroke */
2251                 gp_paint_strokeend(p);
2252         }
2253
2254         /* "unlock" frame */
2255         if (p->gpf)
2256                 p->gpf->flag &= ~GP_FRAME_PAINT;
2257 }
2258
2259 /* ------------------------------- */
2260
2261 /* Helper callback for drawing the cursor itself */
2262 static void gpencil_draw_eraser(bContext *UNUSED(C), int x, int y, void *p_ptr)
2263 {
2264         tGPsdata *p = (tGPsdata *)p_ptr;
2265
2266         if (p->paintmode == GP_PAINTMODE_ERASER) {
2267                 GPUVertFormat *format = immVertexFormat();
2268                 const uint shdr_pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2269                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2270
2271                 GPU_line_smooth(true);
2272                 GPU_blend(true);
2273                 GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
2274
2275                 immUniformColor4ub(255, 100, 100, 20);
2276                 imm_draw_circle_fill_2d(shdr_pos, x, y, p->radius, 40);
2277
2278                 immUnbindProgram();
2279
2280                 immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
2281
2282                 float viewport_size[4];
2283                 GPU_viewport_size_get_f(viewport_size);
2284                 immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
2285
2286                 immUniformColor4f(1.0f, 0.39f, 0.39f, 0.78f);
2287                 immUniform1i("colors_len", 0);  /* "simple" mode */
2288                 immUniform1f("dash_width", 12.0f);
2289                 immUniform1f("dash_factor", 0.5f);
2290
2291                 imm_draw_circle_wire_2d(shdr_pos, x, y, p->radius,
2292                         /* XXX Dashed shader gives bad results with sets of small segments currently,
2293                          *     temp hack around the issue. :( */
2294                         max_ii(8, p->radius / 2));  /* was fixed 40 */
2295
2296                 immUnbindProgram();
2297
2298                 GPU_blend(false);
2299                 GPU_line_smooth(false);
2300         }
2301 }
2302
2303 /* Turn brush cursor in 3D view on/off */
2304 static void gpencil_draw_toggle_eraser_cursor(bContext *C, tGPsdata *p, short enable)
2305 {
2306         if (p->erasercursor && !enable) {
2307                 /* clear cursor */
2308                 WM_paint_cursor_end(CTX_wm_manager(C), p->erasercursor);
2309                 p->erasercursor = NULL;
2310         }
2311         else if (enable && !p->erasercursor) {
2312                 ED_gpencil_toggle_brush_cursor(p->C, false, NULL);
2313                 /* enable cursor */
2314                 p->erasercursor = WM_paint_cursor_activate(
2315                         CTX_wm_manager(C),
2316                         SPACE_TYPE_ANY, RGN_TYPE_ANY,
2317                         NULL, /* XXX */
2318                         gpencil_draw_eraser, p);
2319         }
2320 }
2321
2322 /* Check if tablet eraser is being used (when processing events) */
2323 static bool gpencil_is_tablet_eraser_active(const wmEvent *event)
2324 {
2325         if (event->tablet_data) {
2326                 const wmTabletData *wmtab = event->tablet_data;
2327                 return (wmtab->Active == EVT_TABLET_ERASER);
2328         }
2329
2330         return false;
2331 }
2332
2333 /* ------------------------------- */
2334
2335 static void gpencil_draw_exit(bContext *C, wmOperator *op)
2336 {
2337         tGPsdata *p = op->customdata;
2338
2339         /* don't assume that operator data exists at all */
2340         if (p) {
2341                 /* check size of buffer before cleanup, to determine if anything happened here */
2342                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2343                         /* turn off radial brush cursor */
2344                         gpencil_draw_toggle_eraser_cursor(C, p, false);
2345                 }
2346
2347                 /* always store the new eraser size to be used again next time
2348                  * NOTE: Do this even when not in eraser mode, as eraser may
2349                  *       have been toggled at some point.
2350                  */
2351                 if (p->eraser) {
2352                         p->eraser->size = p->radius;
2353                 }
2354
2355                 /* restore cursor to indicate end of drawing */
2356                 if (p->sa->spacetype != SPACE_VIEW3D) {
2357                         WM_cursor_modal_restore(CTX_wm_window(C));
2358                 }
2359                 else {
2360                         /* or restore paint if 3D view */
2361                         if ((p) && (p->paintmode == GP_PAINTMODE_ERASER)) {
2362                                 WM_cursor_modal_set(p->win, CURSOR_STD);
2363                         }
2364
2365                         /* drawing batch cache is dirty now */
2366                         bGPdata *gpd = CTX_data_gpencil_data(C);
2367                         if (gpd) {
2368                                 gpd->flag &= ~GP_DATA_STROKE_POLYGON;
2369                                 gp_update_cache(gpd);
2370                         }
2371                 }
2372
2373                 /* clear undo stack */
2374                 gpencil_undo_finish();
2375
2376                 /* cleanup */
2377                 gp_paint_cleanup(p);
2378                 gp_session_cleanup(p);
2379                 ED_gpencil_toggle_brush_cursor(C, true, NULL);
2380
2381                 /* finally, free the temp data */
2382                 gp_session_free(p);
2383                 p = NULL;
2384         }
2385
2386         op->customdata = NULL;
2387 }
2388
2389 static void gpencil_draw_cancel(bContext *C, wmOperator *op)
2390 {
2391         /* this is just a wrapper around exit() */
2392         gpencil_draw_exit(C, op);
2393 }
2394
2395 /* ------------------------------- */
2396
2397
2398 static int gpencil_draw_init(bContext *C, wmOperator *op, const wmEvent *event)
2399 {
2400         tGPsdata *p;
2401         eGPencil_PaintModes paintmode = RNA_enum_get(op->ptr, "mode");
2402         ToolSettings *ts = CTX_data_tool_settings(C);
2403         Brush *brush = BKE_paint_brush(&ts->gp_paint->paint);
2404
2405         /* if mode is draw and the brush is eraser, cancel */
2406         if (paintmode != GP_PAINTMODE_ERASER) {
2407                 if ((brush) && (brush->gpencil_tool == GPAINT_TOOL_ERASE)) {
2408                         return 0;
2409                 }
2410         }
2411
2412         /* check context */
2413         p = op->customdata = gp_session_initpaint(C, op);
2414         if ((p == NULL) || (p->status == GP_STATUS_ERROR)) {
2415                 /* something wasn't set correctly in context */
2416                 gpencil_draw_exit(C, op);
2417                 return 0;
2418         }
2419
2420         /* init painting data */
2421         gp_paint_initstroke(p, paintmode, CTX_data_depsgraph(C));
2422         if (p->status == GP_STATUS_ERROR) {
2423                 gpencil_draw_exit(C, op);
2424                 return 0;
2425         }
2426
2427         if (event != NULL) {
2428                 p->keymodifier = event->keymodifier;
2429         }
2430         else {
2431                 p->keymodifier = -1;
2432         }
2433
2434         p->reports = op->reports;
2435
2436         /* everything is now setup ok */
2437         return 1;
2438 }
2439
2440
2441 /* ------------------------------- */
2442
2443 /* ensure that the correct cursor icon is set */
2444 static void gpencil_draw_cursor_set(tGPsdata *p)
2445 {
2446         Brush *brush = p->brush;
2447         if ((p->paintmode == GP_PAINTMODE_ERASER) ||
2448             (brush->gpencil_tool == GPAINT_TOOL_ERASE))
2449         {
2450                 WM_cursor_modal_set(p->win, BC_CROSSCURSOR);  /* XXX need a better cursor */
2451         }
2452         else {
2453                 WM_cursor_modal_set(p->win,     CURSOR_NONE);
2454
2455         }
2456 }
2457
2458 /* update UI indicators of status, including cursor and header prints */
2459 static void gpencil_draw_status_indicators(bContext *C, tGPsdata *p)
2460 {
2461         /* header prints */
2462         switch (p->status) {
2463
2464 #if 0 /* FIXME, this never runs! */
2465                 switch (p->paintmode) {
2466                         case GP_PAINTMODE_DRAW_POLY:
2467                                 /* Provide usage tips, since this is modal, and unintuitive without hints */
2468                                 ED_workspace_status_text(
2469                                         C, IFACE_(
2470                                                 "Annotation Create Poly: LMB click to place next stroke vertex | "
2471                                                 "ESC/Enter to end  (or click outside this area)"
2472                                         ));
2473                                 break;
2474                         default:
2475                                 /* Do nothing - the others are self explanatory, exit quickly once the mouse is released
2476                                  * Showing any text would just be annoying as it would flicker.
2477                                  */
2478                                 break;
2479                 }
2480 #endif
2481
2482                 case GP_STATUS_IDLING:
2483                 {
2484                         /* print status info */
2485                         switch (p->paintmode) {
2486                                 case GP_PAINTMODE_ERASER:
2487                                 {
2488                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Erase Session: Hold and drag LMB or RMB to erase | "
2489                                                 "ESC/Enter to end  (or click outside this area)"));
2490                                         break;
2491                                 }
2492                                 case GP_PAINTMODE_DRAW_STRAIGHT:
2493                                 {
2494                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Line Session: Hold and drag LMB to draw | "
2495                                                 "ESC/Enter to end  (or click outside this area)"));
2496                                         break;
2497                                 }
2498                                 case GP_PAINTMODE_SET_CP:
2499                                 {
2500                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Guides: LMB click and release to place reference point | "
2501                                                 "Esc/RMB to cancel"));
2502                                         break;
2503                                 }
2504                                 case GP_PAINTMODE_DRAW:
2505                                 {
2506                                         GP_Sculpt_Guide *guide = &p->scene->toolsettings->gp_sculpt.guide;
2507                                         if (guide->use_guide) {
2508                                                 ED_workspace_status_text(C, IFACE_("Grease Pencil Freehand Session: Hold and drag LMB to draw | "
2509                                                         "M key to flip guide | O key to move reference point"));
2510                                         }
2511                                         else {
2512                                                 ED_workspace_status_text(C, IFACE_("Grease Pencil Freehand Session: Hold and drag LMB to draw"));
2513                                         }
2514                                         break;
2515                                 }
2516                                 case GP_PAINTMODE_DRAW_POLY:
2517                                 {
2518                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Poly Session: LMB click to place next stroke vertex | "
2519                                                 "Release Shift/ESC/Enter to end  (or click outside this area)"));
2520                                         break;
2521                                 }
2522                                 default: /* unhandled future cases */
2523                                 {
2524                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Session: ESC/Enter to end   (or click outside this area)"));
2525                                         break;
2526                                 }
2527                         }
2528                         break;
2529                 }
2530                 case GP_STATUS_ERROR:
2531                 case GP_STATUS_DONE:
2532                 {
2533                         /* clear status string */
2534                         ED_workspace_status_text(C, NULL);
2535                         break;
2536                 }
2537                 case GP_STATUS_PAINTING:
2538                         break;
2539         }
2540 }
2541
2542 /* ------------------------------- */
2543
2544 /* create a new stroke point at the point indicated by the painting context */
2545 static void gpencil_draw_apply(bContext *C, wmOperator *op, tGPsdata *p, Depsgraph *depsgraph)
2546 {
2547         bGPdata *gpd = p->gpd;
2548         tGPspoint *pt = NULL;
2549
2550         /* handle drawing/erasing -> test for erasing first */
2551         if (p->paintmode == GP_PAINTMODE_ERASER) {
2552                 /* do 'live' erasing now */
2553                 gp_stroke_doeraser(p);
2554
2555                 /* store used values */
2556                 copy_v2_v2(p->mvalo, p->mval);
2557                 p->opressure = p->pressure;
2558         }
2559         /* only add current point to buffer if mouse moved (even though we got an event, it might be just noise) */
2560         else if (gp_stroke_filtermval(p, p->mval, p->mvalo)) {
2561
2562                 /* if lazy mouse, interpolate the last and current mouse positions */
2563                 if (GPENCIL_LAZY_MODE(p->brush, p->shift)) {
2564                         float now_mouse[2];
2565                         float last_mouse[2];
2566                         copy_v2_v2(now_mouse, p->mval);
2567                         copy_v2_v2(last_mouse, p->mvalo);
2568                         interp_v2_v2v2(now_mouse, now_mouse, last_mouse, p->brush->smooth_stroke_factor);
2569                         copy_v2_v2(p->mval, now_mouse);
2570                 }
2571
2572                 /* try to add point */
2573                 short ok = gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
2574
2575                 /* handle errors while adding point */
2576                 if ((ok == GP_STROKEADD_FULL) || (ok == GP_STROKEADD_OVERFLOW)) {
2577                         /* finish off old stroke */
2578                         gp_paint_strokeend(p);
2579                         /* And start a new one!!! Else, projection errors! */
2580                         gp_paint_initstroke(p, p->paintmode, depsgraph);
2581
2582                         /* start a new stroke, starting from previous point */
2583                         /* XXX Must manually reset inittime... */
2584                         /* XXX We only need to reuse previous point if overflow! */
2585                         if (ok == GP_STROKEADD_OVERFLOW) {
2586                                 p->inittime = p->ocurtime;
2587                                 gp_stroke_addpoint(p, p->mvalo, p->opressure, p->ocurtime);
2588                         }
2589                         else {
2590                                 p->inittime = p->curtime;
2591                         }
2592                         gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
2593                 }
2594                 else if (ok == GP_STROKEADD_INVALID) {
2595                         /* the painting operation cannot continue... */
2596                         BKE_report(op->reports, RPT_ERROR, "Cannot paint stroke");
2597                         p->status = GP_STATUS_ERROR;
2598
2599                         if (G.debug & G_DEBUG)
2600                                 printf("Error: Grease-Pencil Paint - Add Point Invalid\n");
2601                         return;
2602                 }
2603
2604                 /* store used values */
2605                 copy_v2_v2(p->mvalo, p->mval);
2606                 p->opressure = p->pressure;
2607                 p->ocurtime = p->curtime;
2608
2609                 pt = (tGPspoint *)gpd->runtime.sbuffer + gpd->runtime.sbuffer_size - 1;
2610                 if (p->paintmode != GP_PAINTMODE_ERASER) {
2611                         ED_gpencil_toggle_brush_cursor(C, true, &pt->x);
2612                 }
2613         }
2614         else if ((p->brush->gpencil_settings->flag & GP_BRUSH_STABILIZE_MOUSE_TEMP) &&
2615                  (gpd->runtime.sbuffer_size > 0))
2616         {
2617                 pt = (tGPspoint *)gpd->runtime.sbuffer + gpd->runtime.sbuffer_size - 1;
2618                 if (p->paintmode != GP_PAINTMODE_ERASER) {
2619                         ED_gpencil_toggle_brush_cursor(C, true, &pt->x);
2620                 }
2621         }
2622 }
2623
2624 /* Helper to rotate point around origin */
2625 static void gp_rotate_v2_v2v2fl(float v[2], const float p[2], const float origin[2], const float angle)
2626 {
2627         float pt[2];
2628         float r[2];
2629         sub_v2_v2v2(pt, p, origin);
2630         rotate_v2_v2fl(r, pt, angle);
2631         add_v2_v2v2(v, r, origin);
2632 }
2633
2634 /* Helper to snap value to grid */
2635 static float gp_snap_to_grid_fl(float v, const float offset, const float spacing)
2636 {
2637         if (spacing > 0.0f) {
2638                 return roundf(v / spacing) * spacing + fmodf(offset, spacing);
2639         }
2640         else {
2641                 return v;
2642         }
2643 }
2644
2645 static void UNUSED_FUNCTION(gp_snap_to_grid_v2)(float v[2], const float offset[2], const float spacing)
2646 {
2647         v[0] = gp_snap_to_grid_fl(v[0], offset[0], spacing);
2648         v[1] = gp_snap_to_grid_fl(v[1], offset[1], spacing);
2649 }
2650
2651 /* get reference point - screen coords to buffer coords */
2652 static void gp_origin_set(wmOperator *op, const int mval[2])
2653 {
2654         tGPsdata *p = op->customdata;
2655         GP_Sculpt_Guide *guide = &p->scene->toolsettings->gp_sculpt.guide;
2656         float origin[2];
2657         float point[3];
2658         copy_v2fl_v2i(origin, mval);
2659         gp_stroke_convertcoords(p, origin, point, NULL);
2660         if (guide->reference_point == GP_GUIDE_REF_CUSTOM) {
2661                 copy_v3_v3(guide->location, point);
2662         }
2663         else if (guide->reference_point == GP_GUIDE_REF_CURSOR) {
2664                 copy_v3_v3(p->scene->cursor.location, point);
2665         }
2666 }
2667
2668 /* get reference point - buffer coords to screen coords */
2669 static void gp_origin_get(tGPsdata *p, float origin[2])
2670 {
2671         GP_Sculpt_Guide *guide = &p->scene->toolsettings->gp_sculpt.guide;
2672         float location[3];
2673         if (guide->reference_point == GP_GUIDE_REF_CUSTOM) {
2674                 copy_v3_v3(location, guide->location);
2675         }
2676         else if (guide->reference_point == GP_GUIDE_REF_OBJECT &&
2677                  guide->reference_object != NULL)
2678         {
2679                 copy_v3_v3(location, guide->reference_object->loc);
2680         }
2681         else {
2682                 copy_v3_v3(location, p->scene->cursor.location);
2683         }
2684         GP_SpaceConversion *gsc = &p->gsc;
2685         gp_point_3d_to_xy(gsc, p->gpd->runtime.sbuffer_sflag, location, origin);
2686 }
2687
2688 /* handle draw event */
2689 static void gpencil_draw_apply_event(bContext *C, wmOperator *op, const wmEvent *event, Depsgraph *depsgraph, float x, float y)
2690 {
2691         tGPsdata *p = op->customdata;
2692         GP_Sculpt_Guide *guide = &p->scene->toolsettings->gp_sculpt.guide;
2693         PointerRNA itemptr;
2694         float mousef[2];
2695         int tablet = 0;
2696
2697         /* convert from window-space to area-space mouse coordinates
2698          * add any x,y override position for fake events
2699          */
2700         p->mval[0] = (float)event->mval[0] - x;
2701         p->mval[1] = (float)event->mval[1] - y;
2702         p->shift = event->shift;
2703
2704         /* verify direction for straight lines */
2705         if ((guide->use_guide) || ((event->alt > 0) && (RNA_boolean_get(op->ptr, "disable_straight") == false))) {
2706                 if (p->straight == 0) {
2707                         int dx = (int)fabsf(p->mval[0] - p->mvali[0]);
2708                         int dy = (int)fabsf(p->mval[1] - p->mvali[1]);
2709                         if ((dx > 0) || (dy > 0)) {
2710                                 /* store mouse direction */
2711                                 if (dx > dy) {
2712                                         p->straight = STROKE_HORIZONTAL;
2713                                 }
2714                                 else if (dx < dy) {
2715                                         p->straight = STROKE_VERTICAL;
2716                                 }
2717                         }
2718                 }
2719         }
2720
2721         p->curtime = PIL_check_seconds_timer();
2722
2723         /* handle pressure sensitivity (which is supplied by tablets) */
2724         if (event->tablet_data) {
2725                 const wmTabletData *wmtab = event->tablet_data;
2726
2727                 tablet = (wmtab->Active != EVT_TABLET_NONE);
2728                 p->pressure = wmtab->Pressure;
2729
2730                 /* Hack for pressure sensitive eraser on D+RMB when using a tablet:
2731                  * The pen has to float over the tablet surface, resulting in
2732                  * zero pressure (T47101). Ignore pressure values if floating
2733                  * (i.e. "effectively zero" pressure), and only when the "active"
2734                  * end is the stylus (i.e. the default when not eraser)
2735                  */
2736                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2737                         if ((wmtab->Active != EVT_TABLET_ERASER) && (p->pressure < 0.001f)) {
2738                                 p->pressure = 1.0f;
2739                         }
2740                 }
2741         }
2742         else {
2743                 /* No tablet data -> No pressure info is available */
2744                 p->pressure = 1.0f;
2745         }
2746
2747         /* special eraser modes */
2748         if (p->paintmode == GP_PAINTMODE_ERASER) {
2749                 if (event->shift > 0) {
2750                         p->flags |= GP_PAINTFLAG_HARD_ERASER;
2751                 }
2752                 else {
2753                         p->flags &= ~GP_PAINTFLAG_HARD_ERASER;
2754                 }
2755                 if (event->alt > 0) {
2756                         p->flags |= GP_PAINTFLAG_STROKE_ERASER;
2757                 }
2758                 else {
2759                         p->flags &= ~GP_PAINTFLAG_STROKE_ERASER;
2760                 }
2761         }
2762
2763         /* special exception for start of strokes (i.e. maybe for just a dot) */
2764         if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
2765                 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
2766
2767                 /* set values */
2768                 copy_v2_v2(p->mvalo, p->mval);
2769                 p->opressure = p->pressure;
2770                 p->inittime = p->ocurtime = p->curtime;
2771                 p->straight = 0;
2772
2773                 /* save initial mouse */
2774                 copy_v2_v2(p->mvali, p->mval);
2775
2776                 /* calculate once and store snapping distance and origin */
2777                 RegionView3D * rv3d = p->ar->regiondata;
2778                 float scale = 1.0f;
2779                 if (rv3d->is_persp) {
2780                         float vec[3];
2781                         gp_get_3d_reference(p, vec);
2782                         mul_m4_v3(rv3d->persmat, vec);
2783                         scale = vec[2] * rv3d->pixsize;
2784                 }
2785                 else {
2786                         scale = rv3d->pixsize;
2787                 }
2788                 p->guide_spacing = guide->spacing / scale;
2789                 p->half_spacing = p->guide_spacing * 0.5f;
2790                 gp_origin_get(p, p->origin);
2791
2792                 /* special exception here for too high pressure values on first touch in
2793                  * windows for some tablets, then we just skip first touch...
2794                  */
2795                 if (tablet && (p->pressure >= 0.99f)) {
2796                         return;
2797                 }
2798
2799                 /* special exception for grid snapping
2800                  * it requires direction which needs at least two points
2801                  */
2802                 if (!ELEM(p->paintmode, GP_PAINTMODE_ERASER, GP_PAINTMODE_SET_CP) &&
2803                     guide->use_guide &&
2804                     guide->use_snapping &&
2805                     (guide->type == GP_GUIDE_GRID))
2806                 {
2807                         p->flags |= GP_PAINTFLAG_REQ_VECTOR;
2808                 }
2809         }
2810
2811         /* wait for vector then add initial point */
2812         if (p->flags & GP_PAINTFLAG_REQ_VECTOR) {
2813                 if (p->straight == 0) {
2814                         return;
2815                 }
2816
2817                 p->flags &= ~GP_PAINTFLAG_REQ_VECTOR;
2818
2819                 /* create fake events */
2820                 float tmp[2];
2821                 float pt[2];
2822                 copy_v2_v2(tmp, p->mval);
2823                 sub_v2_v2v2(pt, p->mval, p->mvali);
2824                 gpencil_draw_apply_event(C, op, event, CTX_data_depsgraph(C), pt[0], pt[1]);
2825                 if (len_v2v2(p->mval, p->mvalo)) {
2826                         sub_v2_v2v2(pt, p->mval, p->mvalo);
2827                         gpencil_draw_apply_event(C, op, event, CTX_data_depsgraph(C), pt[0], pt[1]);
2828                 }
2829                 copy_v2_v2(p->mval, tmp);
2830         }
2831
2832         /* check if stroke is straight or guided */
2833         if ((p->paintmode != GP_PAINTMODE_ERASER) &&
2834             ((p->straight) || (guide->use_guide)))
2835         {
2836                 /* guided stroke */
2837                 if (guide->use_guide) {
2838                         switch (guide->type) {
2839                                 default:
2840                                 case GP_GUIDE_CIRCULAR:
2841                                 {
2842                                         float distance;
2843                                         distance = len_v2v2(p->mvali, p->origin);
2844
2845                                         if (guide->use_snapping && (guide->spacing > 0.0f)) {
2846                                                 distance = gp_snap_to_grid_fl(distance, 0.0f, p->guide_spacing);
2847                                         }
2848
2849                                         dist_ensure_v2_v2fl(p->mval, p->origin, distance);
2850                                         break;
2851                                 }
2852                                 case GP_GUIDE_RADIAL:
2853                                 {
2854                                         if (guide->use_snapping && (guide->angle_snap > 0.0f)) {
2855                                                 float point[2];
2856                                                 float xy[2];
2857                                                 float angle;
2858                                                 float half_angle = guide->angle_snap * 0.5f;
2859                                                 sub_v2_v2v2(xy, p->mvali, p->origin);
2860                                                 angle = atan2f(xy[1], xy[0]);
2861                                                 angle += (M_PI * 2.0f);
2862                                                 angle = fmodf(angle + half_angle, guide->angle_snap);
2863                                                 angle -= half_angle;
2864                                                 gp_rotate_v2_v2v2fl(point, p->mvali, p->origin, -angle);
2865                                                 closest_to_line_v2(p->mval, p->mval, point, p->origin);
2866                                         }
2867                                         else {
2868                                                 closest_to_line_v2(p->mval, p->mval, p->mvali, p->origin);
2869                                         }
2870                                         break;
2871                                 }
2872                                 case GP_GUIDE_PARALLEL:
2873                                 {
2874                                         float point[2];
2875                                         float unit[2];
2876                                         copy_v2_v2(unit, p->mvali);
2877                                         unit[0] += 1.0f; /* start from horizontal */
2878                                         gp_rotate_v2_v2v2fl(point, unit, p->mvali, guide->angle);
2879                                         closest_to_line_v2(p->mval, p->mval, p->mvali, point);
2880
2881                                         if (guide->use_snapping && (guide->spacing > 0.0f)) {
2882                                                 gp_rotate_v2_v2v2fl(p->mval, p->mval, p->origin, -guide->angle);
2883                                                 p->mval[1] = gp_snap_to_grid_fl(p->mval[1] - p->half_spacing, p->origin[1], p->guide_spacing);
2884                                                 gp_rotate_v2_v2v2fl(p->mval, p->mval, p->origin, guide->angle);
2885                                         }
2886                                         break;
2887                                 }
2888                                 case GP_GUIDE_GRID:
2889                                 {
2890                                         if (guide->use_snapping && (guide->spacing > 0.0f)) {
2891                                                 float point[2];
2892                                                 float unit[2];
2893                                                 float angle;
2894                                                 copy_v2_v2(unit, p->mvali);
2895                                                 unit[0] += 1.0f; /* start from horizontal */
2896                                                 angle = (p->straight == STROKE_VERTICAL) ? M_PI_2 : 0.0f;
2897                                                 gp_rotate_v2_v2v2fl(point, unit, p->mvali, angle);
2898                                                 closest_to_line_v2(p->mval, p->mval, p->mvali, point);
2899
2900                                                 if (p->straight == STROKE_HORIZONTAL) {
2901                                                         p->mval[1] = gp_snap_to_grid_fl(p->mval[1] - p->half_spacing, p->origin[1], p->guide_spacing);
2902                                                 }
2903                                                 else {
2904                                                         p->mval[0] = gp_snap_to_grid_fl(p->mval[0] - p->half_spacing, p->origin[0], p->guide_spacing);
2905                                                 }
2906                                         }
2907                                         else if (p->straight == STROKE_HORIZONTAL) {
2908                                                 p->mval[1] = p->mvali[1]; /* replace y */
2909                                         }
2910                                         else {
2911                                                 p->mval[0] = p->mvali[0]; /* replace x */
2912                                         }
2913                                         break;
2914                                 }
2915                         }
2916                 }
2917                 else if (p->straight == STROKE_HORIZONTAL) {
2918                         p->mval[1] = p->mvali[1]; /* replace y */
2919                 }
2920                 else {
2921                         p->mval[0] = p->mvali[0]; /* replace x */
2922                 }
2923         }
2924
2925         /* fill in stroke data (not actually used directly by gpencil_draw_apply) */
2926         RNA_collection_add(op->ptr, "stroke", &itemptr);
2927
2928         mousef[0] = p->mval[0];
2929         mousef[1] = p->mval[1];
2930         RNA_float_set_array(&itemptr, "mouse", mousef);
2931         RNA_float_set(&itemptr, "pressure", p->pressure);
2932         RNA_boolean_set(&itemptr, "is_start", (p->flags & GP_PAINTFLAG_FIRSTRUN) != 0);
2933
2934         RNA_float_set(&itemptr, "time", p->curtime - p->inittime);
2935
2936         /* apply the current latest drawing point */
2937         gpencil_draw_apply(C, op, p, depsgraph);
2938
2939         /* force refresh */
2940         /* just active area for now, since doing whole screen is too slow */
2941         ED_region_tag_redraw(p->ar);
2942 }
2943
2944 /* ------------------------------- */
2945
2946 /* operator 'redo' (i.e. after changing some properties, but also for repeat last) */
2947 static int gpencil_draw_exec(bContext *C, wmOperator *op)
2948 {
2949         tGPsdata *p = NULL;
2950         Depsgraph *depsgraph = CTX_data_depsgraph(C);
2951
2952         /* printf("GPencil - Starting Re-Drawing\n"); */
2953
2954         /* try to initialize context data needed while drawing */
2955         if (!gpencil_draw_init(C, op, NULL)) {
2956                 MEM_SAFE_FREE(op->customdata);
2957                 /* printf("\tGP - no valid data\n"); */
2958                 return OPERATOR_CANCELLED;
2959         }
2960         else
2961                 p = op->customdata;
2962