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