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