Merge branch 'blender2.7'
[blender.git] / source / blender / editors / gpencil / gpencil_paint.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2008, Blender Foundation
17  * This is a new part of Blender
18  */
19
20 /** \file
21  * \ingroup edgpencil
22  */
23
24 #include <stdio.h>
25 #include <stddef.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <math.h>
29
30 #include "MEM_guardedalloc.h"
31
32 #include "BLI_blenlib.h"
33 #include "BLI_math.h"
34 #include "BLI_utildefines.h"
35 #include "BLI_rand.h"
36 #include "BLI_math_geom.h"
37
38 #include "BLT_translation.h"
39
40 #include "PIL_time.h"
41
42 #include "DNA_meshdata_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_scene_types.h"
45 #include "DNA_gpencil_types.h"
46 #include "DNA_material_types.h"
47 #include "DNA_brush_types.h"
48 #include "DNA_windowmanager_types.h"
49
50 #include "BKE_colortools.h"
51 #include "BKE_main.h"
52 #include "BKE_brush.h"
53 #include "BKE_paint.h"
54 #include "BKE_context.h"
55 #include "BKE_deform.h"
56 #include "BKE_global.h"
57 #include "BKE_gpencil.h"
58 #include "BKE_report.h"
59 #include "BKE_layer.h"
60 #include "BKE_material.h"
61 #include "BKE_screen.h"
62 #include "BKE_tracking.h"
63
64 #include "UI_view2d.h"
65
66 #include "ED_gpencil.h"
67 #include "ED_screen.h"
68 #include "ED_object.h"
69 #include "ED_view3d.h"
70 #include "ED_clip.h"
71
72
73 #include "GPU_immediate.h"
74 #include "GPU_immediate_util.h"
75 #include "GPU_state.h"
76
77 #include "RNA_access.h"
78 #include "RNA_define.h"
79
80 #include "WM_api.h"
81 #include "WM_types.h"
82
83 #include "DEG_depsgraph.h"
84 #include "DEG_depsgraph_query.h"
85
86 #include "gpencil_intern.h"
87
88   /* ******************************************* */
89   /* 'Globals' and Defines */
90
91   /* values for tGPsdata->status */
92 typedef enum eGPencil_PaintStatus {
93         GP_STATUS_IDLING = 0,   /* stroke isn't in progress yet */
94         GP_STATUS_PAINTING,     /* a stroke is in progress */
95         GP_STATUS_ERROR,        /* something wasn't correctly set up */
96         GP_STATUS_DONE          /* painting done */
97 } eGPencil_PaintStatus;
98
99 /* Return flags for adding points to stroke buffer */
100 typedef enum eGP_StrokeAdd_Result {
101         GP_STROKEADD_INVALID    = -2,       /* error occurred - insufficient info to do so */
102         GP_STROKEADD_OVERFLOW   = -1,       /* error occurred - cannot fit any more points */
103         GP_STROKEADD_NORMAL,                /* point was successfully added */
104         GP_STROKEADD_FULL                   /* cannot add any more points to buffer */
105 } eGP_StrokeAdd_Result;
106
107 /* Runtime flags */
108 typedef enum eGPencil_PaintFlags {
109         GP_PAINTFLAG_FIRSTRUN       = (1 << 0),    /* operator just started */
110         GP_PAINTFLAG_STROKEADDED    = (1 << 1),
111         GP_PAINTFLAG_SELECTMASK     = (1 << 3),
112         GP_PAINTFLAG_HARD_ERASER    = (1 << 4),
113         GP_PAINTFLAG_STROKE_ERASER  = (1 << 5),
114         GP_PAINTFLAG_REQ_VECTOR     = (1 << 6),
115 } eGPencil_PaintFlags;
116
117 /* Temporary 'Stroke' Operation data
118  *   "p" = op->customdata
119  */
120 typedef struct tGPsdata {
121         bContext *C;
122
123         /** main database pointer. */
124         Main *bmain;
125         /** current scene from context. */
126         Scene *scene;
127         struct Depsgraph *depsgraph;
128
129         /** current object. */
130         Object *ob;
131         /** window where painting originated. */
132         wmWindow *win;
133         /** area where painting originated. */
134         ScrArea *sa;
135         /** region where painting originated. */
136         ARegion *ar;
137         /** needed for GP_STROKE_2DSPACE. */
138         View2D *v2d;
139         /** for using the camera rect within the 3d view. */
140         rctf *subrect;
141         rctf subrect_data;
142
143         /** settings to pass to gp_points_to_xy(). */
144         GP_SpaceConversion gsc;
145
146         /** pointer to owner of gp-datablock. */
147         PointerRNA ownerPtr;
148         /** gp-datablock layer comes from. */
149         bGPdata *gpd;
150         /** layer we're working on. */
151         bGPDlayer *gpl;
152         /** frame we're working on. */
153         bGPDframe *gpf;
154
155         /** projection-mode flags (toolsettings - eGPencil_Placement_Flags) */
156         char *align_flag;
157
158         /** current status of painting. */
159         eGPencil_PaintStatus status;
160         /** mode for painting. */
161         eGPencil_PaintModes  paintmode;
162         /** flags that can get set during runtime (eGPencil_PaintFlags) */
163         eGPencil_PaintFlags  flags;
164
165         /** radius of influence for eraser. */
166         short radius;
167
168         /** current mouse-position. */
169         float mval[2];
170         /** previous recorded mouse-position. */
171         float mvalo[2];
172         /** initial recorded mouse-position */
173         float mvali[2];
174
175         /** current stylus pressure. */
176         float pressure;
177         /** previous stylus pressure. */
178         float opressure;
179
180         /* These need to be doubles, as (at least under unix) they are in seconds since epoch,
181          * float (and its 7 digits precision) is definitively not enough here!
182          * double, with its 15 digits precision, ensures us millisecond precision for a few centuries at least.
183          */
184         /** Used when converting to path. */
185         double inittime;
186         /** Used when converting to path. */
187         double curtime;
188         /** Used when converting to path. */
189         double ocurtime;
190
191         /** Inverted transformation matrix applying when converting coords from screen-space
192          * to region space. */
193         float imat[4][4];
194         float mat[4][4];
195
196         /** custom color - hack for enforcing a particular color for track/mask editing. */
197         float custom_color[4];
198
199         /** radial cursor data for drawing eraser. */
200         void *erasercursor;
201
202         /* mat settings are only used for 3D view */
203         /** current material */
204         Material *material;
205         /** current drawing brush */
206         Brush *brush;
207         /** default eraser brush */
208         Brush *eraser;
209
210         /** 1: line horizontal, 2: line vertical, other: not defined */
211         short straight;
212         /** lock drawing to one axis */
213         int lock_axis;
214         /** the stroke is no fill mode */
215         bool disable_fill;
216
217         RNG *rng;
218
219         /** key used for invoking the operator */
220         short keymodifier;
221         /** shift modifier flag */
222         short shift;
223         /** size in pixels for uv calculation */
224         float totpixlen;
225
226         /* guide */
227         /** guide spacing */
228         float guide_spacing;
229         /** half guide spacing */
230         float half_spacing;
231         /** origin */
232         float origin[2];
233
234         ReportList *reports;
235 } tGPsdata;
236
237 /* ------ */
238
239 #define STROKE_HORIZONTAL 1
240 #define STROKE_VERTICAL 2
241
242 /* Macros for accessing sensitivity thresholds... */
243 /* minimum number of pixels mouse should move before new point created */
244 #define MIN_MANHATTEN_PX    (U.gp_manhattendist)
245 /* minimum length of new segment before new point can be added */
246 #define MIN_EUCLIDEAN_PX    (U.gp_euclideandist)
247
248 static void gp_update_cache(bGPdata *gpd)
249 {
250         if (gpd) {
251                 DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
252                 gpd->flag |= GP_DATA_CACHE_IS_DIRTY;
253         }
254 }
255
256 static bool gp_stroke_added_check(tGPsdata *p)
257 {
258         return (p->gpf && p->gpf->strokes.last && p->flags & GP_PAINTFLAG_STROKEADDED);
259 }
260
261 static void gp_stroke_added_enable(tGPsdata *p)
262 {
263         BLI_assert(p->gpf->strokes.last != NULL);
264         p->flags |= GP_PAINTFLAG_STROKEADDED;
265
266         /* drawing batch cache is dirty now */
267         gp_update_cache(p->gpd);
268 }
269
270 /* ------ */
271 /* Forward defines for some functions... */
272
273 static void gp_session_validatebuffer(tGPsdata *p);
274
275 /* ******************************************* */
276 /* Context Wrangling... */
277
278 /* check if context is suitable for drawing */
279 static bool gpencil_draw_poll(bContext *C)
280 {
281         if (ED_operator_regionactive(C)) {
282                 ScrArea *sa = CTX_wm_area(C);
283                 /* 3D Viewport */
284                 if (sa->spacetype != SPACE_VIEW3D) {
285                         return false;
286                 }
287
288                 /* check if Grease Pencil isn't already running */
289                 if (ED_gpencil_session_active() != 0) {
290                         CTX_wm_operator_poll_msg_set(C, "Grease Pencil operator is already active");
291                         return false;
292                 }
293
294                 /* only grease pencil object type */
295                 Object *ob = CTX_data_active_object(C);
296                 if ((ob == NULL) || (ob->type != OB_GPENCIL)) {
297                         return false;
298                 }
299
300                 bGPdata *gpd = (bGPdata *)ob->data;
301                 if (!GPENCIL_PAINT_MODE(gpd)) {
302                         return false;
303                 }
304
305                 return true;
306         }
307         else {
308                 CTX_wm_operator_poll_msg_set(C, "Active region not set");
309                 return false;
310         }
311 }
312
313 /* check if projecting strokes into 3d-geometry in the 3D-View */
314 static bool gpencil_project_check(tGPsdata *p)
315 {
316         bGPdata *gpd = p->gpd;
317         return ((gpd->runtime.sbuffer_sflag & GP_STROKE_3DSPACE) && (*p->align_flag & (GP_PROJECT_DEPTH_VIEW | GP_PROJECT_DEPTH_STROKE)));
318 }
319
320 /* ******************************************* */
321 /* Calculations/Conversions */
322
323 /* Utilities --------------------------------- */
324
325 /* get the reference point for stroke-point conversions */
326 static void gp_get_3d_reference(tGPsdata *p, float vec[3])
327 {
328         Object *ob = NULL;
329         if (p->ownerPtr.type == &RNA_Object) {
330                 ob = (Object *)p->ownerPtr.data;
331         }
332         ED_gp_get_drawing_reference(p->scene, ob, p->gpl, *p->align_flag, vec);
333 }
334
335 /* Stroke Editing ---------------------------- */
336 /* check if the current mouse position is suitable for adding a new point */
337 static bool gp_stroke_filtermval(tGPsdata *p, const float mval[2], float mvalo[2])
338 {
339         Brush *brush = p->brush;
340         int dx = (int)fabsf(mval[0] - mvalo[0]);
341         int dy = (int)fabsf(mval[1] - mvalo[1]);
342         brush->gpencil_settings->flag &= ~GP_BRUSH_STABILIZE_MOUSE_TEMP;
343
344         /* if buffer is empty, just let this go through (i.e. so that dots will work) */
345         if (p->gpd->runtime.sbuffer_size == 0) {
346                 return true;
347         }
348         /* if lazy mouse, check minimum distance */
349         else if (GPENCIL_LAZY_MODE(brush, p->shift)) {
350                 brush->gpencil_settings->flag |= GP_BRUSH_STABILIZE_MOUSE_TEMP;
351                 if ((dx * dx + dy * dy) > (brush->smooth_stroke_radius * brush->smooth_stroke_radius)) {
352                         return true;
353                 }
354                 else {
355                         /* If the mouse is moving within the radius of the last move,
356                          * don't update the mouse position. This allows sharp turns. */
357                         copy_v2_v2(p->mval, p->mvalo);
358                         return false;
359                 }
360         }
361         /* check if mouse moved at least certain distance on both axes (best case)
362          * - aims to eliminate some jitter-noise from input when trying to draw straight lines freehand
363          */
364         else if ((dx > MIN_MANHATTEN_PX) && (dy > MIN_MANHATTEN_PX))
365                 return true;
366
367         /* check if the distance since the last point is significant enough
368          * - prevents points being added too densely
369          * - distance here doesn't use sqrt to prevent slowness... we should still be safe from overflows though
370          */
371         else if ((dx * dx + dy * dy) > MIN_EUCLIDEAN_PX * MIN_EUCLIDEAN_PX)
372                 return true;
373
374         /* mouse 'didn't move' */
375         else
376                 return false;
377 }
378
379 /* reproject stroke to plane locked to axis in 3d cursor location */
380 static void gp_reproject_toplane(tGPsdata *p, bGPDstroke *gps)
381 {
382         bGPdata *gpd = p->gpd;
383         Object *obact = (Object *)p->ownerPtr.data;
384
385         float origin[3];
386         RegionView3D *rv3d = p->ar->regiondata;
387
388         /* verify the stroke mode is CURSOR 3d space mode */
389         if ((gpd->runtime.sbuffer_sflag & GP_STROKE_3DSPACE) == 0) {
390                 return;
391         }
392         if ((*p->align_flag & GP_PROJECT_VIEWSPACE) == 0) {
393                 return;
394         }
395         if ((*p->align_flag & GP_PROJECT_DEPTH_VIEW) || (*p->align_flag & GP_PROJECT_DEPTH_STROKE)) {
396                 return;
397         }
398
399         /* get drawing origin */
400         gp_get_3d_reference(p, origin);
401         ED_gp_project_stroke_to_plane(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         gp_stroke_added_enable(p);
1246 }
1247
1248 /* --- 'Eraser' for 'Paint' Tool ------ */
1249
1250 /* which which point is infront (result should only be used for comparison) */
1251 static float view3d_point_depth(const RegionView3D *rv3d, const float co[3])
1252 {
1253         if (rv3d->is_persp) {
1254                 return ED_view3d_calc_zfac(rv3d, co, NULL);
1255         }
1256         else {
1257                 return -dot_v3v3(rv3d->viewinv[2], co);
1258         }
1259 }
1260
1261 /* only erase stroke points that are visible */
1262 static bool gp_stroke_eraser_is_occluded(tGPsdata *p, const bGPDspoint *pt, const int x, const int y)
1263 {
1264         Object *obact = (Object *)p->ownerPtr.data;
1265         Brush *brush = p->brush;
1266         Brush *eraser = p->eraser;
1267         BrushGpencilSettings *gp_settings = NULL;
1268
1269         if (brush->gpencil_tool == GPAINT_TOOL_ERASE) {
1270                 gp_settings = brush->gpencil_settings;
1271         }
1272         else if ((eraser != NULL) & (eraser->gpencil_tool == GPAINT_TOOL_ERASE)) {
1273                 gp_settings = eraser->gpencil_settings;
1274         }
1275
1276         if ((gp_settings != NULL) && (p->sa->spacetype == SPACE_VIEW3D) &&
1277             (gp_settings->flag & GP_BRUSH_OCCLUDE_ERASER))
1278         {
1279                 RegionView3D *rv3d = p->ar->regiondata;
1280                 bGPDlayer *gpl = p->gpl;
1281
1282                 const int mval_i[2] = {x, y};
1283                 float mval_3d[3];
1284                 float fpt[3];
1285
1286                 float diff_mat[4][4];
1287                 /* calculate difference matrix if parent object */
1288                 ED_gpencil_parent_location(p->depsgraph, obact, p->gpd, gpl, diff_mat);
1289
1290                 if (ED_view3d_autodist_simple(p->ar, mval_i, mval_3d, 0, NULL)) {
1291                         const float depth_mval = view3d_point_depth(rv3d, mval_3d);
1292
1293                         mul_v3_m4v3(fpt, diff_mat, &pt->x);
1294                         const float depth_pt = view3d_point_depth(rv3d, fpt);
1295
1296                         if (depth_pt > depth_mval) {
1297                                 return true;
1298                         }
1299                 }
1300         }
1301         return false;
1302 }
1303
1304 /* apply a falloff effect to brush strength, based on distance */
1305 static float gp_stroke_eraser_calc_influence(tGPsdata *p, const float mval[2], const int radius, const int co[2])
1306 {
1307         Brush *brush = p->brush;
1308         /* Linear Falloff... */
1309         int mval_i[2];
1310         round_v2i_v2fl(mval_i, mval);
1311         float distance = (float)len_v2v2_int(mval_i, co);
1312         float fac;
1313
1314         CLAMP(distance, 0.0f, (float)radius);
1315         fac = 1.0f - (distance / (float)radius);
1316
1317         /* apply strength factor */
1318         fac *= brush->gpencil_settings->draw_strength;
1319
1320         /* Control this further using pen pressure */
1321         if (brush->gpencil_settings->flag & GP_BRUSH_USE_PRESSURE) {
1322                 fac *= p->pressure;
1323         }
1324         /* Return influence factor computed here */
1325         return fac;
1326 }
1327
1328 /* helper to free a stroke */
1329 static void gp_free_stroke(bGPdata *gpd, bGPDframe *gpf, bGPDstroke *gps)
1330 {
1331         if (gps->points) {
1332                 MEM_freeN(gps->points);
1333         }
1334
1335         if (gps->dvert) {
1336                 BKE_gpencil_free_stroke_weights(gps);
1337                 MEM_freeN(gps->dvert);
1338         }
1339
1340         if (gps->triangles)
1341                 MEM_freeN(gps->triangles);
1342         BLI_freelinkN(&gpf->strokes, gps);
1343         gp_update_cache(gpd);
1344 }
1345
1346 /* analyze points to be removed when soft eraser is used
1347  * to avoid that segments gets the end points rounded. This
1348  * round cpas breaks the artistic effect.
1349  */
1350 static void gp_stroke_soft_refine(bGPDstroke *gps, const float cull_thresh)
1351 {
1352         bGPDspoint *pt = NULL;
1353         bGPDspoint *pt_before = NULL;
1354         bGPDspoint *pt_after = NULL;
1355         int i;
1356
1357         /* check if enough points*/
1358         if (gps->totpoints < 3) {
1359                 return;
1360         }
1361
1362         /* loop all points from second to last minus one
1363          * to untag any point that is not surrounded by tagged points
1364          */
1365         pt = gps->points;
1366         for (i = 1; i < gps->totpoints - 1; i++, pt++) {
1367                 if (pt->flag & GP_SPOINT_TAG) {
1368                         pt_before = &gps->points[i - 1];
1369                         pt_after = &gps->points[i + 1];
1370
1371                         /* if any of the side points are not tagged, mark to keep */
1372                         if (((pt_before->flag & GP_SPOINT_TAG) == 0) ||
1373                             ((pt_after->flag & GP_SPOINT_TAG) == 0))
1374                         {
1375                                 if (pt->pressure > cull_thresh) {
1376                                         pt->flag |= GP_SPOINT_TEMP_TAG;
1377                                 }
1378                         }
1379                         else {
1380                                 /* reduce opacity of extreme points */
1381                                 if ((pt_before->flag & GP_SPOINT_TAG) == 0) {
1382                                         pt_before->strength *= 0.5f;
1383                                 }
1384                                 if ((pt_after->flag & GP_SPOINT_TAG) == 0) {
1385                                         pt_after->strength *= 0.5f;
1386                                 }
1387                         }
1388                 }
1389         }
1390
1391         /* now untag temp tagged */
1392         pt = gps->points;
1393         for (i = 1; i < gps->totpoints - 1; i++, pt++) {
1394                 if (pt->flag & GP_SPOINT_TEMP_TAG) {
1395                         pt->flag &= ~GP_SPOINT_TAG;
1396                         pt->flag &= ~GP_SPOINT_TEMP_TAG;
1397                 }
1398         }
1399 }
1400
1401 /* eraser tool - evaluation per stroke */
1402 /* TODO: this could really do with some optimization (KD-Tree/BVH?) */
1403 static void gp_stroke_eraser_dostroke(tGPsdata *p,
1404         bGPDlayer *gpl, bGPDframe *gpf, bGPDstroke *gps,
1405         const float mval[2], const float mvalo[2],
1406         const int radius, const rcti *rect)
1407 {
1408         Depsgraph *depsgraph = p->depsgraph;
1409         Object *obact = (Object *)p->ownerPtr.data;
1410         Brush *eraser = p->eraser;
1411         bGPDspoint *pt0, *pt1, *pt2;
1412         int pc0[2] = {0};
1413         int pc1[2] = {0};
1414         int pc2[2] = {0};
1415         int i;
1416         float diff_mat[4][4];
1417         int mval_i[2];
1418         round_v2i_v2fl(mval_i, mval);
1419
1420         /* calculate difference matrix */
1421         ED_gpencil_parent_location(depsgraph, obact, p->gpd, gpl, diff_mat);
1422
1423         if (gps->totpoints == 0) {
1424                 /* just free stroke */
1425                 gp_free_stroke(p->gpd, gpf, gps);
1426         }
1427         else if (gps->totpoints == 1) {
1428                 /* only process if it hasn't been masked out... */
1429                 if (!(p->flags & GP_PAINTFLAG_SELECTMASK) || (gps->points->flag & GP_SPOINT_SELECT)) {
1430                         bGPDspoint pt_temp;
1431                         gp_point_to_parent_space(gps->points, diff_mat, &pt_temp);
1432                         gp_point_to_xy(&p->gsc, gps, &pt_temp, &pc1[0], &pc1[1]);
1433                         /* do boundbox check first */
1434                         if ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) {
1435                                 /* only check if point is inside */
1436                                 if (len_v2v2_int(mval_i, pc1) <= radius) {
1437                                         /* free stroke */
1438                                         gp_free_stroke(p->gpd, gpf, gps);
1439                                 }
1440                         }
1441                 }
1442         }
1443         else if ((p->flags & GP_PAINTFLAG_STROKE_ERASER) || (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_STROKE)) {
1444                 for (i = 0; (i + 1) < gps->totpoints; i++) {
1445
1446                         /* only process if it hasn't been masked out... */
1447                         if ((p->flags & GP_PAINTFLAG_SELECTMASK) && !(gps->points->flag & GP_SPOINT_SELECT))
1448                                 continue;
1449
1450                         /* get points to work with */
1451                         pt1 = gps->points + i;
1452                         bGPDspoint npt;
1453                         gp_point_to_parent_space(pt1, diff_mat, &npt);
1454                         gp_point_to_xy(&p->gsc, gps, &npt, &pc1[0], &pc1[1]);
1455
1456                         /* do boundbox check first */
1457                         if ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) {
1458                                 /* only check if point is inside */
1459                                 if (len_v2v2_int(mval_i, pc1) <= radius) {
1460                                         /* free stroke */
1461                                         gp_free_stroke(p->gpd, gpf, gps);
1462                                         return;
1463                                 }
1464                         }
1465                 }
1466         }
1467         else {
1468                 /* Pressure threshold at which stroke should be culled: Calculated as pressure value
1469                  * below which we would have invisible strokes
1470                  */
1471                 const float cull_thresh = (gps->thickness) ? 1.0f / ((float)gps->thickness) : 1.0f;
1472
1473                 /* Amount to decrease the pressure of each point with each stroke */
1474                 // TODO: Fetch from toolsettings, or compute based on thickness instead?
1475                 const float strength = 0.1f;
1476
1477                 /* Perform culling? */
1478                 bool do_cull = false;
1479
1480
1481                 /* Clear Tags
1482                  *
1483                  * Note: It's better this way, as we are sure that
1484                  * we don't miss anything, though things will be
1485                  * slightly slower as a result
1486                  */
1487                 for (i = 0; i < gps->totpoints; i++) {
1488                         bGPDspoint *pt = &gps->points[i];
1489                         pt->flag &= ~GP_SPOINT_TAG;
1490                 }
1491
1492                 /* First Pass: Loop over the points in the stroke
1493                  *   1) Thin out parts of the stroke under the brush
1494                  *   2) Tag "too thin" parts for removal (in second pass)
1495                  */
1496                 for (i = 0; (i + 1) < gps->totpoints; i++) {
1497                         /* get points to work with */
1498                         pt0 = i > 0 ? gps->points + i - 1 : NULL;
1499                         pt1 = gps->points + i;
1500                         pt2 = gps->points + i + 1;
1501
1502                         /* only process if it hasn't been masked out... */
1503                         if ((p->flags & GP_PAINTFLAG_SELECTMASK) && !(gps->points->flag & GP_SPOINT_SELECT))
1504                                 continue;
1505
1506                         bGPDspoint npt;
1507                         if (pt0) {
1508                                 gp_point_to_parent_space(pt0, diff_mat, &npt);
1509                                 gp_point_to_xy(&p->gsc, gps, &npt, &pc0[0], &pc0[1]);
1510                         }
1511                         else {
1512                                 /* avoid null values */
1513                                 copy_v2_v2_int(pc0, pc1);
1514                         }
1515
1516                         gp_point_to_parent_space(pt1, diff_mat, &npt);
1517                         gp_point_to_xy(&p->gsc, gps, &npt, &pc1[0], &pc1[1]);
1518
1519                         gp_point_to_parent_space(pt2, diff_mat, &npt);
1520                         gp_point_to_xy(&p->gsc, gps, &npt, &pc2[0], &pc2[1]);
1521
1522                         /* Check that point segment of the boundbox of the eraser stroke */
1523                         if (((!ELEM(V2D_IS_CLIPPED, pc0[0], pc0[1])) && BLI_rcti_isect_pt(rect, pc0[0], pc0[1])) ||
1524                             ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) ||
1525                             ((!ELEM(V2D_IS_CLIPPED, pc2[0], pc2[1])) && BLI_rcti_isect_pt(rect, pc2[0], pc2[1])))
1526                         {
1527                                 /* Check if point segment of stroke had anything to do with
1528                                  * eraser region  (either within stroke painted, or on its lines)
1529                                  * - this assumes that linewidth is irrelevant
1530                                  */
1531                                 if (gp_stroke_inside_circle(mval, mvalo, radius, pc0[0], pc0[1], pc2[0], pc2[1])) {
1532                                         if ((gp_stroke_eraser_is_occluded(p, pt0, pc0[0], pc0[1]) == false) ||
1533                                             (gp_stroke_eraser_is_occluded(p, pt1, pc1[0], pc1[1]) == false) ||
1534                                             (gp_stroke_eraser_is_occluded(p, pt2, pc2[0], pc2[1]) == false))
1535                                         {
1536                                                 /* Point is affected: */
1537                                                 /* Adjust thickness
1538                                                  *  - Influence of eraser falls off with distance from the middle of the eraser
1539                                                  *  - Second point gets less influence, as it might get hit again in the next segment
1540                                                  */
1541
1542                                                 /* Adjust strength if the eraser is soft */
1543                                                 if (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_SOFT) {
1544                                                         float f_strength = eraser->gpencil_settings->era_strength_f / 100.0f;
1545                                                         float f_thickness = eraser->gpencil_settings->era_thickness_f / 100.0f;
1546
1547                                                         if (pt0) {
1548                                                                 pt0->strength -= gp_stroke_eraser_calc_influence(p, mval, radius, pc0) * strength * f_strength * 0.5f;
1549                                                                 CLAMP_MIN(pt0->strength, 0.0f);
1550                                                                 pt0->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc0) * strength * f_thickness * 0.5f;
1551                                                         }
1552
1553                                                         pt1->strength -= gp_stroke_eraser_calc_influence(p, mval, radius, pc1) * strength * f_strength;
1554                                                         CLAMP_MIN(pt1->strength, 0.0f);
1555                                                         pt1->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc1) * strength * f_thickness;
1556
1557                                                         pt2->strength -= gp_stroke_eraser_calc_influence(p, mval, radius, pc2) * strength * f_strength * 0.5f;
1558                                                         CLAMP_MIN(pt2->strength, 0.0f);
1559                                                         pt2->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc2) * strength * f_thickness * 0.5f;
1560
1561                                                         /* if invisible, delete point */
1562                                                         if ((pt0) &&
1563                                                             ((pt0->strength <= GPENCIL_ALPHA_OPACITY_THRESH) ||
1564                                                              (pt0->pressure < cull_thresh)))
1565                                                         {
1566                                                                 pt0->flag |= GP_SPOINT_TAG;
1567                                                                 do_cull = true;
1568                                                         }
1569                                                         if ((pt1->strength <= GPENCIL_ALPHA_OPACITY_THRESH) || (pt1->pressure < cull_thresh)) {
1570                                                                 pt1->flag |= GP_SPOINT_TAG;
1571                                                                 do_cull = true;
1572                                                         }
1573                                                         if ((pt2->strength <= GPENCIL_ALPHA_OPACITY_THRESH) || (pt2->pressure < cull_thresh)) {
1574                                                                 pt2->flag |= GP_SPOINT_TAG;
1575                                                                 do_cull = true;
1576                                                         }
1577                                                 }
1578                                                 else {
1579                                                         pt1->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc1) * strength;
1580                                                         pt2->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc2) * strength * 0.5f;
1581                                                 }
1582
1583                                                 /* 2) Tag any point with overly low influence for removal in the next pass */
1584                                                 if ((pt1->pressure < cull_thresh) || (p->flags & GP_PAINTFLAG_HARD_ERASER) ||
1585                                                     (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_HARD))
1586                                                 {
1587                                                         pt1->flag |= GP_SPOINT_TAG;
1588                                                         do_cull = true;
1589                                                 }
1590                                                 if ((pt2->pressure < cull_thresh) || (p->flags & GP_PAINTFLAG_HARD_ERASER) ||
1591                                                     (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_HARD))
1592                                                 {
1593                                                         pt2->flag |= GP_SPOINT_TAG;
1594                                                         do_cull = true;
1595                                                 }
1596                                         }
1597                                 }
1598                         }
1599                 }
1600
1601                 /* Second Pass: Remove any points that are tagged */
1602                 if (do_cull) {
1603                         /* if soft eraser, must analyze points to be sure the stroke ends
1604                          * don't get rounded */
1605                         if (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_SOFT) {
1606                                 gp_stroke_soft_refine(gps, cull_thresh);
1607                         }
1608
1609                         gp_stroke_delete_tagged_points(gpf, gps, gps->next, GP_SPOINT_TAG, false, 0);
1610                 }
1611                 gp_update_cache(p->gpd);
1612         }
1613 }
1614
1615 /* erase strokes which fall under the eraser strokes */
1616 static void gp_stroke_doeraser(tGPsdata *p)
1617 {
1618         bGPDlayer *gpl;
1619         bGPDstroke *gps, *gpn;
1620         rcti rect;
1621         Brush *brush = p->brush;
1622         Brush *eraser = p->eraser;
1623         bool use_pressure = false;
1624         float press = 1.0f;
1625         BrushGpencilSettings *gp_settings = NULL;
1626
1627         /* detect if use pressure in eraser */
1628         if (brush->gpencil_tool == GPAINT_TOOL_ERASE) {
1629                 use_pressure = (bool)(brush->gpencil_settings->flag & GP_BRUSH_USE_PRESSURE);
1630                 gp_settings = brush->gpencil_settings;
1631         }
1632         else if ((eraser != NULL) & (eraser->gpencil_tool == GPAINT_TOOL_ERASE)) {
1633                 use_pressure = (bool)(eraser->gpencil_settings->flag & GP_BRUSH_USE_PRESSURE);
1634                 gp_settings = eraser->gpencil_settings;
1635         }
1636         if (use_pressure) {
1637                 press = p->pressure;
1638                 CLAMP(press, 0.01f, 1.0f);
1639         }
1640         /* rect is rectangle of eraser */
1641         const int calc_radius = (int)p->radius * press;
1642         rect.xmin = p->mval[0] - calc_radius;
1643         rect.ymin = p->mval[1] - calc_radius;
1644         rect.xmax = p->mval[0] + calc_radius;
1645         rect.ymax = p->mval[1] + calc_radius;
1646
1647         if (p->sa->spacetype == SPACE_VIEW3D) {
1648                 if ((gp_settings != NULL) && (gp_settings->flag & GP_BRUSH_OCCLUDE_ERASER)) {
1649                         View3D *v3d = p->sa->spacedata.first;
1650                         view3d_region_operator_needs_opengl(p->win, p->ar);
1651                         ED_view3d_autodist_init(p->depsgraph, p->ar, v3d, 0);
1652                 }
1653         }
1654
1655         /* loop over all layers too, since while it's easy to restrict editing to
1656          * only a subset of layers, it is harder to perform the same erase operation
1657          * on multiple layers...
1658          */
1659         for (gpl = p->gpd->layers.first; gpl; gpl = gpl->next) {
1660                 bGPDframe *gpf = gpl->actframe;
1661
1662                 /* only affect layer if it's editable (and visible) */
1663                 if (gpencil_layer_is_editable(gpl) == false) {
1664                         continue;
1665                 }
1666                 else if (gpf == NULL) {
1667                         continue;
1668                 }
1669
1670                 /* loop over strokes, checking segments for intersections */
1671                 for (gps = gpf->strokes.first; gps; gps = gpn) {
1672                         gpn = gps->next;
1673                         /* check if the color is editable */
1674                         if (ED_gpencil_stroke_color_use(p->ob, gpl, gps) == false) {
1675                                 continue;
1676                         }
1677                         /* Not all strokes in the datablock may be valid in the current editor/context
1678                          * (e.g. 2D space strokes in the 3D view, if the same datablock is shared)
1679                          */
1680                         if (ED_gpencil_stroke_can_use_direct(p->sa, gps)) {
1681                                 gp_stroke_eraser_dostroke(p, gpl, gpf, gps, p->mval, p->mvalo, calc_radius, &rect);
1682                         }
1683                 }
1684         }
1685 }
1686
1687 /* ******************************************* */
1688 /* Sketching Operator */
1689
1690 /* clear the session buffers (call this before AND after a paint operation) */
1691 static void gp_session_validatebuffer(tGPsdata *p)
1692 {
1693         bGPdata *gpd = p->gpd;
1694         Brush *brush = p->brush;
1695
1696         /* clear memory of buffer (or allocate it if starting a new session) */
1697         if (gpd->runtime.sbuffer) {
1698                 /* printf("\t\tGP - reset sbuffer\n"); */
1699                 memset(gpd->runtime.sbuffer, 0, sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX);
1700         }
1701         else {
1702                 /* printf("\t\tGP - allocate sbuffer\n"); */
1703                 gpd->runtime.sbuffer = MEM_callocN(sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX, "gp_session_strokebuffer");
1704         }
1705
1706         /* reset indices */
1707         gpd->runtime.sbuffer_size = 0;
1708
1709         /* reset flags */
1710         gpd->runtime.sbuffer_sflag = 0;
1711
1712         /* reset inittime */
1713         p->inittime = 0.0;
1714
1715         /* reset lazy */
1716         if (brush) {
1717                 brush->gpencil_settings->flag &= ~GP_BRUSH_STABILIZE_MOUSE_TEMP;
1718         }
1719 }
1720
1721 /* helper to get default eraser and create one if no eraser brush */
1722 static Brush *gp_get_default_eraser(Main *bmain, ToolSettings *ts)
1723 {
1724         Brush *brush_dft = NULL;
1725         Paint *paint = &ts->gp_paint->paint;
1726         Brush *brush_old = paint->brush;
1727         for (Brush *brush = bmain->brush.first; brush; brush = brush->id.next) {
1728                 if ((brush->ob_mode == OB_MODE_PAINT_GPENCIL) &&
1729                     (brush->gpencil_tool == GPAINT_TOOL_ERASE))
1730                 {
1731                         /* save first eraser to use later if no default */
1732                         if (brush_dft == NULL) {
1733                                 brush_dft = brush;
1734                         }
1735                         /* found default */
1736                         if (brush->gpencil_settings->flag & GP_BRUSH_DEFAULT_ERASER) {
1737                                 return brush;
1738                         }
1739                 }
1740         }
1741         /* if no default, but exist eraser brush, return this and set as default */
1742         if (brush_dft) {
1743                 brush_dft->gpencil_settings->flag |= GP_BRUSH_DEFAULT_ERASER;
1744                 return brush_dft;
1745         }
1746         /* create a new soft eraser brush */
1747         else {
1748                 brush_dft = BKE_brush_add_gpencil(bmain, ts, "Soft Eraser");
1749                 brush_dft->size = 30.0f;
1750                 brush_dft->gpencil_settings->flag |= (GP_BRUSH_ENABLE_CURSOR | GP_BRUSH_DEFAULT_ERASER);
1751                 brush_dft->gpencil_settings->icon_id = GP_BRUSH_ICON_ERASE_SOFT;
1752                 brush_dft->gpencil_tool = GPAINT_TOOL_ERASE;
1753                 brush_dft->gpencil_settings->eraser_mode = GP_BRUSH_ERASER_SOFT;
1754
1755                 /* reset current brush */
1756                 BKE_paint_brush_set(paint, brush_old);
1757
1758                 return brush_dft;
1759         }
1760 }
1761
1762 /* helper to set default eraser and disable others */
1763 static void gp_set_default_eraser(Main *bmain, Brush *brush_dft)
1764 {
1765         if (brush_dft == NULL) {
1766                 return;
1767         }
1768
1769         for (Brush *brush = bmain->brush.first; brush; brush = brush->id.next) {
1770                 if ((brush->gpencil_settings) && (brush->gpencil_tool == GPAINT_TOOL_ERASE)) {
1771                         if (brush == brush_dft) {
1772                                 brush->gpencil_settings->flag |= GP_BRUSH_DEFAULT_ERASER;
1773                         }
1774                         else if (brush->gpencil_settings->flag & GP_BRUSH_DEFAULT_ERASER) {
1775                                 brush->gpencil_settings->flag &= ~GP_BRUSH_DEFAULT_ERASER;
1776                         }
1777                 }
1778         }
1779 }
1780
1781 /* initialize a drawing brush */
1782 static void gp_init_drawing_brush(bContext *C, tGPsdata *p)
1783 {
1784         Scene *scene = CTX_data_scene(C);
1785         ToolSettings *ts = CTX_data_tool_settings(C);
1786
1787         Paint *paint = &ts->gp_paint->paint;
1788
1789         /* if not exist, create a new one */
1790         if (paint->brush == NULL) {
1791                 /* create new brushes */
1792                 BKE_brush_gpencil_presets(C);
1793         }
1794         /* be sure curves are initializated */
1795         curvemapping_initialize(paint->brush->gpencil_settings->curve_sensitivity);
1796         curvemapping_initialize(paint->brush->gpencil_settings->curve_strength);
1797         curvemapping_initialize(paint->brush->gpencil_settings->curve_jitter);
1798
1799         /* assign to temp tGPsdata */
1800         p->brush = paint->brush;
1801         if (paint->brush->gpencil_tool != GPAINT_TOOL_ERASE) {
1802                 p->eraser = gp_get_default_eraser(p->bmain, ts);
1803         }
1804         else {
1805                 p->eraser = paint->brush;
1806         }
1807         /* set new eraser as default */
1808         gp_set_default_eraser(p->bmain, p->eraser);
1809
1810         /* use radius of eraser */
1811         p->radius = (short)p->eraser->size;
1812
1813         /* GPXX: Need this update to synchronize brush with draw manager.
1814          * Maybe this update can be removed when the new tool system
1815          * will be in place, but while, we need this to keep drawing working.
1816          */
1817         DEG_id_tag_update(&scene->id, ID_RECALC_COPY_ON_WRITE);
1818 }
1819
1820
1821 /* initialize a paint brush and a default color if not exist */
1822 static void gp_init_colors(tGPsdata *p)
1823 {
1824         bGPdata *gpd = p->gpd;
1825         Brush *brush = p->brush;
1826
1827         Material *ma = NULL;
1828         MaterialGPencilStyle *gp_style = NULL;
1829
1830         /* use brush material */
1831         ma = BKE_gpencil_get_material_from_brush(brush);
1832
1833         /* if no brush defaults, get material and color info
1834          * NOTE: Ensures that everything we need will exist...
1835          */
1836         if ((ma == NULL) || (ma->gp_style == NULL)) {
1837                 BKE_gpencil_material_ensure(p->bmain, p->ob);
1838
1839                 /* assign always the first material to the brush */
1840                 p->material = give_current_material(p->ob, 1);
1841                 brush->gpencil_settings->material = p->material;
1842         }
1843         else {
1844                 p->material = ma;
1845         }
1846
1847         /* check if the material is already on object material slots and add it if missing */
1848         if (BKE_gpencil_get_material_index(p->ob, p->material) == 0) {
1849                 BKE_object_material_slot_add(p->bmain, p->ob);
1850                 assign_material(p->bmain, p->ob, ma, p->ob->totcol, BKE_MAT_ASSIGN_USERPREF);
1851         }
1852
1853         /* assign color information to temp tGPsdata */
1854         gp_style = p->material->gp_style;
1855         if (gp_style) {
1856
1857                 /* set colors */
1858                 if (gp_style->flag & GP_STYLE_STROKE_SHOW) {
1859                         copy_v4_v4(gpd->runtime.scolor, gp_style->stroke_rgba);
1860                 }
1861                 else {
1862                         /* if no stroke, use fill */
1863                         copy_v4_v4(gpd->runtime.scolor, gp_style->fill_rgba);
1864                 }
1865                 copy_v4_v4(gpd->runtime.sfill, gp_style->fill_rgba);
1866                 /* add some alpha to make easy the filling without hide strokes */
1867                 if (gpd->runtime.sfill[3] > 0.8f) {
1868                         gpd->runtime.sfill[3] = 0.8f;
1869                 }
1870
1871                 gpd->runtime.mode = (short)gp_style->mode;
1872                 gpd->runtime.bstroke_style = gp_style->stroke_style;
1873                 gpd->runtime.bfill_style = gp_style->fill_style;
1874         }
1875 }
1876
1877 /* (re)init new painting data */
1878 static bool gp_session_initdata(bContext *C, wmOperator *op, tGPsdata *p)
1879 {
1880         Main *bmain = CTX_data_main(C);
1881         bGPdata **gpd_ptr = NULL;
1882         ScrArea *curarea = CTX_wm_area(C);
1883         ARegion *ar = CTX_wm_region(C);
1884         ToolSettings *ts = CTX_data_tool_settings(C);
1885         Object *obact = CTX_data_active_object(C);
1886
1887         /* make sure the active view (at the starting time) is a 3d-view */
1888         if (curarea == NULL) {
1889                 p->status = GP_STATUS_ERROR;
1890                 if (G.debug & G_DEBUG)
1891                         printf("Error: No active view for painting\n");
1892                 return 0;
1893         }
1894
1895         /* pass on current scene and window */
1896         p->C = C;
1897         p->bmain = CTX_data_main(C);
1898         p->scene = CTX_data_scene(C);
1899         p->depsgraph = CTX_data_depsgraph(C);
1900         p->win = CTX_wm_window(C);
1901         p->disable_fill = RNA_boolean_get(op->ptr, "disable_fill");
1902
1903         unit_m4(p->imat);
1904         unit_m4(p->mat);
1905
1906         switch (curarea->spacetype) {
1907                 /* supported views first */
1908                 case SPACE_VIEW3D:
1909                 {
1910                         /* View3D *v3d = curarea->spacedata.first; */
1911                         /* RegionView3D *rv3d = ar->regiondata; */
1912
1913                         /* set current area
1914                          * - must verify that region data is 3D-view (and not something else)
1915                          */
1916                          /* CAUTION: If this is the "toolbar", then this will change on the first stroke */
1917                         p->sa = curarea;
1918                         p->ar = ar;
1919                         p->align_flag = &ts->gpencil_v3d_align;
1920
1921                         if (ar->regiondata == NULL) {
1922                                 p->status = GP_STATUS_ERROR;
1923                                 if (G.debug & G_DEBUG)
1924                                         printf("Error: 3D-View active region doesn't have any region data, so cannot be drawable\n");
1925                                 return 0;
1926                         }
1927
1928                         if ((!obact) || (obact->type != OB_GPENCIL)) {
1929                                 View3D *v3d = p->sa->spacedata.first;
1930                                 /* if active object doesn't exist or isn't a GP Object, create one */
1931                                 const float *cur = p->scene->cursor.location;
1932
1933                                 ushort local_view_bits = 0;
1934                                 if (v3d->localvd) {
1935                                         local_view_bits = v3d->local_view_uuid;
1936                                 }
1937                                 /* create new default object */
1938                                 obact = ED_gpencil_add_object(C, p->scene, cur, local_view_bits);
1939                         }
1940                         /* assign object after all checks to be sure we have one active */
1941                         p->ob = obact;
1942
1943                         break;
1944                 }
1945
1946                 /* unsupported views */
1947                 default:
1948                 {
1949                         p->status = GP_STATUS_ERROR;
1950                         if (G.debug & G_DEBUG)
1951                                 printf("Error: Active view not appropriate for Grease Pencil drawing\n");
1952                         return 0;
1953                 }
1954         }
1955
1956         /* get gp-data */
1957         gpd_ptr = ED_gpencil_data_get_pointers(C, &p->ownerPtr);
1958         if ((gpd_ptr == NULL) || ED_gpencil_data_owner_is_annotation(&p->ownerPtr)) {
1959                 p->status = GP_STATUS_ERROR;
1960                 if (G.debug & G_DEBUG)
1961                         printf("Error: Current context doesn't allow for any Grease Pencil data\n");
1962                 return 0;
1963         }
1964         else {
1965                 /* if no existing GPencil block exists, add one */
1966                 if (*gpd_ptr == NULL)
1967                         *gpd_ptr = BKE_gpencil_data_addnew(bmain, "GPencil");
1968                 p->gpd = *gpd_ptr;
1969         }
1970
1971         if (ED_gpencil_session_active() == 0) {
1972                 /* initialize undo stack,
1973                  * also, existing undo stack would make buffer drawn
1974                  */
1975                 gpencil_undo_init(p->gpd);
1976         }
1977
1978         /* clear out buffer (stored in gp-data), in case something contaminated it */
1979         gp_session_validatebuffer(p);
1980
1981         /* set brush and create a new one if null */
1982         gp_init_drawing_brush(C, p);
1983
1984         /* setup active color */
1985         if (curarea->spacetype == SPACE_VIEW3D) {
1986                 /* NOTE: This is only done for 3D view, as Materials aren't used for
1987                  *       annotations in 2D editors
1988                  */
1989                 gp_init_colors(p);
1990         }
1991
1992         /* lock axis (in some modes, disable) */
1993         if (((*p->align_flag & GP_PROJECT_DEPTH_VIEW) == 0) &&
1994             ((*p->align_flag & GP_PROJECT_DEPTH_STROKE) == 0))
1995         {
1996                 p->lock_axis = ts->gp_sculpt.lock_axis;
1997         }
1998         else {
1999                 p->lock_axis = 0;
2000         }
2001
2002         /* region where paint was originated */
2003         p->gpd->runtime.ar = CTX_wm_region(C);
2004
2005         return 1;
2006 }
2007
2008 /* init new painting session */
2009 static tGPsdata *gp_session_initpaint(bContext *C, wmOperator *op)
2010 {
2011         tGPsdata *p = NULL;
2012
2013         /* Create new context data */
2014         p = MEM_callocN(sizeof(tGPsdata), "GPencil Drawing Data");
2015
2016         /* Try to initialise context data
2017          * WARNING: This may not always succeed (e.g. using GP in an annotation-only context)
2018          */
2019         if (gp_session_initdata(C, op, p) == 0) {
2020                 /* Invalid state - Exit
2021                  * NOTE: It should be safe to just free the data, since failing context checks should
2022                  * only happen when no data has been allocated.
2023                  */
2024                 MEM_freeN(p);
2025                 return NULL;
2026         }
2027
2028         /* Random generator, only init once. */
2029         uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX);
2030         rng_seed ^= POINTER_AS_UINT(p);
2031         p->rng = BLI_rng_new(rng_seed);
2032
2033         /* return context data for running paint operator */
2034         return p;
2035 }
2036
2037 /* cleanup after a painting session */
2038 static void gp_session_cleanup(tGPsdata *p)
2039 {
2040         bGPdata *gpd = (p) ? p->gpd : NULL;
2041
2042         /* error checking */
2043         if (gpd == NULL)
2044                 return;
2045
2046         /* free stroke buffer */
2047         if (gpd->runtime.sbuffer) {
2048                 /* printf("\t\tGP - free sbuffer\n"); */
2049                 MEM_SAFE_FREE(gpd->runtime.sbuffer);
2050                 gpd->runtime.sbuffer = NULL;
2051         }
2052
2053         /* clear flags */
2054         gpd->runtime.sbuffer_size = 0;
2055         gpd->runtime.sbuffer_sflag = 0;
2056         p->inittime = 0.0;
2057 }
2058
2059 static void gp_session_free(tGPsdata *p)
2060 {
2061         if (p->rng != NULL) {
2062                 BLI_rng_free(p->rng);
2063         }
2064
2065         MEM_freeN(p);
2066 }
2067
2068 /* init new stroke */
2069 static void gp_paint_initstroke(tGPsdata *p, eGPencil_PaintModes paintmode, Depsgraph *depsgraph)
2070 {
2071         Scene *scene = p->scene;
2072         ToolSettings *ts = scene->toolsettings;
2073         int cfra_eval = (int)DEG_get_ctime(p->depsgraph);
2074
2075         /* get active layer (or add a new one if non-existent) */
2076         p->gpl = BKE_gpencil_layer_getactive(p->gpd);
2077         if (p->gpl == NULL) {
2078                 p->gpl = BKE_gpencil_layer_addnew(p->gpd, DATA_("GP_Layer"), true);
2079
2080                 if (p->custom_color[3]) {
2081                         copy_v3_v3(p->gpl->color, p->custom_color);
2082                 }
2083         }
2084         if ((paintmode != GP_PAINTMODE_ERASER) &&
2085             (p->gpl->flag & GP_LAYER_LOCKED))
2086         {
2087                 p->status = GP_STATUS_ERROR;
2088                 if (G.debug & G_DEBUG)
2089                         printf("Error: Cannot paint on locked layer\n");
2090                 return;
2091         }
2092
2093         /* get active frame (add a new one if not matching frame) */
2094         if (paintmode == GP_PAINTMODE_ERASER) {
2095                 /* Eraser mode:
2096                  * 1) Add new frames to all frames that we might touch,
2097                  * 2) Ensure that p->gpf refers to the frame used for the active layer
2098                  *    (to avoid problems with other tools which expect it to exist)
2099                  */
2100                 bool has_layer_to_erase = false;
2101
2102                 for (bGPDlayer *gpl = p->gpd->layers.first; gpl; gpl = gpl->next) {
2103                         /* Skip if layer not editable */
2104                         if (gpencil_layer_is_editable(gpl) == false)
2105                                 continue;
2106
2107                         /* Add a new frame if needed (and based off the active frame,
2108                          * as we need some existing strokes to erase)
2109                          *
2110                          * Note: We don't add a new frame if there's nothing there now, so
2111                          *       -> If there are no frames at all, don't add one
2112                          *       -> If there are no strokes in that frame, don't add a new empty frame
2113                          */
2114                         if (gpl->actframe && gpl->actframe->strokes.first) {
2115                                 gpl->actframe = BKE_gpencil_layer_getframe(gpl, cfra_eval, GP_GETFRAME_ADD_COPY);
2116                                 has_layer_to_erase = true;
2117                         }
2118
2119                         /* XXX: we omit GP_FRAME_PAINT here for now,
2120                          * as it is only really useful for doing
2121                          * paintbuffer drawing
2122                          */
2123                 }
2124
2125                 /* Ensure this gets set... */
2126                 p->gpf = p->gpl->actframe;
2127
2128                 /* Restrict eraser to only affecting selected strokes, if the "selection mask" is on
2129                  * (though this is only available in editmode)
2130                  */
2131                 if (p->gpd->flag & GP_DATA_STROKE_EDITMODE) {
2132                         if (ts->gp_sculpt.flag & GP_SCULPT_SETT_FLAG_SELECT_MASK) {
2133                                 p->flags |= GP_PAINTFLAG_SELECTMASK;
2134                         }
2135                 }
2136
2137                 if (has_layer_to_erase == false) {
2138                         p->status = GP_STATUS_ERROR;
2139                         return;
2140                 }
2141         }
2142         else {
2143                 /* Drawing Modes - Add a new frame if needed on the active layer */
2144                 short add_frame_mode;
2145
2146                 if (ts->gpencil_flags & GP_TOOL_FLAG_RETAIN_LAST)
2147                         add_frame_mode = GP_GETFRAME_ADD_COPY;
2148                 else
2149                         add_frame_mode = GP_GETFRAME_ADD_NEW;
2150
2151                 p->gpf = BKE_gpencil_layer_getframe(p->gpl, cfra_eval, add_frame_mode);
2152                 /* set as dirty draw manager cache */
2153                 gp_update_cache(p->gpd);
2154
2155                 if (p->gpf == NULL) {
2156                         p->status = GP_STATUS_ERROR;
2157                         if (G.debug & G_DEBUG)
2158                                 printf("Error: No frame created (gpencil_paint_init)\n");
2159                         return;
2160                 }
2161                 else {
2162                         p->gpf->flag |= GP_FRAME_PAINT;
2163                 }
2164         }
2165
2166         /* set 'eraser' for this stroke if using eraser */
2167         p->paintmode = paintmode;
2168         if (p->paintmode == GP_PAINTMODE_ERASER) {
2169                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_ERASER;
2170         }
2171         else {
2172                 /* disable eraser flags - so that we can switch modes during a session */
2173                 p->gpd->runtime.sbuffer_sflag &= ~GP_STROKE_ERASER;
2174         }
2175
2176         /* set special fill stroke mode */
2177         if (p->disable_fill == true) {
2178                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_NOFILL;
2179                 /* replace stroke color with fill color */
2180                 copy_v4_v4(p->gpd->runtime.scolor, p->gpd->runtime.sfill);
2181         }
2182
2183         /* set 'initial run' flag, which is only used to denote when a new stroke is starting */
2184         p->flags |= GP_PAINTFLAG_FIRSTRUN;
2185
2186         /* when drawing in the camera view, in 2D space, set the subrect */
2187         p->subrect = NULL;
2188         if ((*p->align_flag & GP_PROJECT_VIEWSPACE) == 0) {
2189                 if (p->sa->spacetype == SPACE_VIEW3D) {
2190                         View3D *v3d = p->sa->spacedata.first;
2191                         RegionView3D *rv3d = p->ar->regiondata;
2192
2193                         /* for camera view set the subrect */
2194                         if (rv3d->persp == RV3D_CAMOB) {
2195                                 /* no shift */
2196                                 ED_view3d_calc_camera_border(p->scene, depsgraph, p->ar, v3d, rv3d, &p->subrect_data, true);
2197                                 p->subrect = &p->subrect_data;
2198                         }
2199                 }
2200         }
2201
2202         /* init stroke point space-conversion settings... */
2203         p->gsc.gpd = p->gpd;
2204         p->gsc.gpl = p->gpl;
2205
2206         p->gsc.sa = p->sa;
2207         p->gsc.ar = p->ar;
2208         p->gsc.v2d = p->v2d;
2209
2210         p->gsc.subrect_data = p->subrect_data;
2211         p->gsc.subrect = p->subrect;
2212
2213         copy_m4_m4(p->gsc.mat, p->mat);
2214
2215
2216         /* check if points will need to be made in view-aligned space */
2217         if (*p->align_flag & GP_PROJECT_VIEWSPACE) {
2218                 switch (p->sa->spacetype) {
2219                         case SPACE_VIEW3D:
2220                         {
2221                                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_3DSPACE;
2222                                 break;
2223                         }
2224                 }
2225         }
2226 }
2227
2228 /* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
2229 static void gp_paint_strokeend(tGPsdata *p)
2230 {
2231         ToolSettings *ts = p->scene->toolsettings;
2232         /* for surface sketching, need to set the right OpenGL context stuff so that
2233          * the conversions will project the values correctly...
2234          */
2235         if (gpencil_project_check(p)) {
2236                 View3D *v3d = p->sa->spacedata.first;
2237
2238                 /* need to restore the original projection settings before packing up */
2239                 view3d_region_operator_needs_opengl(p->win, p->ar);
2240                 ED_view3d_autodist_init(p->depsgraph, p->ar, v3d, (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
2241         }
2242
2243         /* check if doing eraser or not */
2244         if ((p->gpd->runtime.sbuffer_sflag & GP_STROKE_ERASER) == 0) {
2245                 /* transfer stroke to frame */
2246                 gp_stroke_newfrombuffer(p);
2247         }
2248
2249         /* clean up buffer now */
2250         gp_session_validatebuffer(p);
2251 }
2252
2253 /* finish off stroke painting operation */
2254 static void gp_paint_cleanup(tGPsdata *p)
2255 {
2256         /* p->gpd==NULL happens when stroke failed to initialize,
2257          * for example when GP is hidden in current space (sergey)
2258          */
2259         if (p->gpd) {
2260                 /* finish off a stroke */
2261                 gp_paint_strokeend(p);
2262         }
2263
2264         /* "unlock" frame */
2265         if (p->gpf)
2266                 p->gpf->flag &= ~GP_FRAME_PAINT;
2267 }
2268
2269 /* ------------------------------- */
2270
2271 /* Helper callback for drawing the cursor itself */
2272 static void gpencil_draw_eraser(bContext *UNUSED(C), int x, int y, void *p_ptr)
2273 {
2274         tGPsdata *p = (tGPsdata *)p_ptr;
2275
2276         if (p->paintmode == GP_PAINTMODE_ERASER) {
2277                 GPUVertFormat *format = immVertexFormat();
2278                 const uint shdr_pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2279                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2280
2281                 GPU_line_smooth(true);
2282                 GPU_blend(true);
2283                 GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
2284
2285                 immUniformColor4ub(255, 100, 100, 20);
2286                 imm_draw_circle_fill_2d(shdr_pos, x, y, p->radius, 40);
2287
2288                 immUnbindProgram();
2289
2290                 immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
2291
2292                 float viewport_size[4];
2293                 GPU_viewport_size_get_f(viewport_size);
2294                 immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
2295
2296                 immUniformColor4f(1.0f, 0.39f, 0.39f, 0.78f);
2297                 immUniform1i("colors_len", 0);  /* "simple" mode */
2298                 immUniform1f("dash_width", 12.0f);
2299                 immUniform1f("dash_factor", 0.5f);
2300
2301                 imm_draw_circle_wire_2d(shdr_pos, x, y, p->radius,
2302                         /* XXX Dashed shader gives bad results with sets of small segments currently,
2303                          *     temp hack around the issue. :( */
2304                         max_ii(8, p->radius / 2));  /* was fixed 40 */
2305
2306                 immUnbindProgram();
2307
2308                 GPU_blend(false);
2309                 GPU_line_smooth(false);
2310         }
2311 }
2312
2313 /* Turn brush cursor in 3D view on/off */
2314 static void gpencil_draw_toggle_eraser_cursor(bContext *C, tGPsdata *p, short enable)
2315 {
2316         if (p->erasercursor && !enable) {
2317                 /* clear cursor */
2318                 WM_paint_cursor_end(CTX_wm_manager(C), p->erasercursor);
2319                 p->erasercursor = NULL;
2320         }
2321         else if (enable && !p->erasercursor) {
2322                 ED_gpencil_toggle_brush_cursor(p->C, false, NULL);
2323                 /* enable cursor */
2324                 p->erasercursor = WM_paint_cursor_activate(
2325                         CTX_wm_manager(C),
2326                         SPACE_TYPE_ANY, RGN_TYPE_ANY,
2327                         NULL, /* XXX */
2328                         gpencil_draw_eraser, p);
2329         }
2330 }
2331
2332 /* Check if tablet eraser is being used (when processing events) */
2333 static bool gpencil_is_tablet_eraser_active(const wmEvent *event)
2334 {
2335         if (event->tablet_data) {
2336                 const wmTabletData *wmtab = event->tablet_data;
2337                 return (wmtab->Active == EVT_TABLET_ERASER);
2338         }
2339
2340         return false;
2341 }
2342
2343 /* ------------------------------- */
2344
2345 static void gpencil_draw_exit(bContext *C, wmOperator *op)
2346 {
2347         tGPsdata *p = op->customdata;
2348
2349         /* don't assume that operator data exists at all */
2350         if (p) {
2351                 /* check size of buffer before cleanup, to determine if anything happened here */
2352                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2353                         /* turn off radial brush cursor */
2354                         gpencil_draw_toggle_eraser_cursor(C, p, false);
2355                 }
2356
2357                 /* always store the new eraser size to be used again next time
2358                  * NOTE: Do this even when not in eraser mode, as eraser may
2359                  *       have been toggled at some point.
2360                  */
2361                 if (p->eraser) {
2362                         p->eraser->size = p->radius;
2363                 }
2364
2365                 /* restore cursor to indicate end of drawing */
2366                 if (p->sa->spacetype != SPACE_VIEW3D) {
2367                         WM_cursor_modal_restore(CTX_wm_window(C));
2368                 }
2369                 else {
2370                         /* or restore paint if 3D view */
2371                         if ((p) && (p->paintmode == GP_PAINTMODE_ERASER)) {
2372                                 WM_cursor_modal_set(p->win, CURSOR_STD);
2373                         }
2374
2375                         /* drawing batch cache is dirty now */
2376                         bGPdata *gpd = CTX_data_gpencil_data(C);
2377                         if (gpd) {
2378                                 gpd->flag &= ~GP_DATA_STROKE_POLYGON;
2379                                 gp_update_cache(gpd);
2380                         }
2381                 }
2382
2383                 /* clear undo stack */
2384                 gpencil_undo_finish();
2385
2386                 /* cleanup */
2387                 gp_paint_cleanup(p);
2388                 gp_session_cleanup(p);
2389                 ED_gpencil_toggle_brush_cursor(C, true, NULL);
2390
2391                 /* finally, free the temp data */
2392                 gp_session_free(p);
2393                 p = NULL;
2394         }
2395
2396         op->customdata = NULL;
2397 }
2398
2399 static void gpencil_draw_cancel(bContext *C, wmOperator *op)
2400 {
2401         /* this is just a wrapper around exit() */
2402         gpencil_draw_exit(C, op);
2403 }
2404
2405 /* ------------------------------- */
2406
2407
2408 static int gpencil_draw_init(bContext *C, wmOperator *op, const wmEvent *event)
2409 {
2410         tGPsdata *p;
2411         eGPencil_PaintModes paintmode = RNA_enum_get(op->ptr, "mode");
2412         ToolSettings *ts = CTX_data_tool_settings(C);
2413         Brush *brush = BKE_paint_brush(&ts->gp_paint->paint);
2414
2415         /* if mode is draw and the brush is eraser, cancel */
2416         if (paintmode != GP_PAINTMODE_ERASER) {
2417                 if ((brush) && (brush->gpencil_tool == GPAINT_TOOL_ERASE)) {
2418                         return 0;
2419                 }
2420         }
2421
2422         /* check context */
2423         p = op->customdata = gp_session_initpaint(C, op);
2424         if ((p == NULL) || (p->status == GP_STATUS_ERROR)) {
2425                 /* something wasn't set correctly in context */
2426                 gpencil_draw_exit(C, op);
2427                 return 0;
2428         }
2429
2430         /* init painting data */
2431         gp_paint_initstroke(p, paintmode, CTX_data_depsgraph(C));
2432         if (p->status == GP_STATUS_ERROR) {
2433                 gpencil_draw_exit(C, op);
2434                 return 0;
2435         }
2436
2437         if (event != NULL) {
2438                 p->keymodifier = event->keymodifier;
2439         }
2440         else {
2441                 p->keymodifier = -1;
2442         }
2443
2444         p->reports = op->reports;
2445
2446         /* everything is now setup ok */
2447         return 1;
2448 }
2449
2450
2451 /* ------------------------------- */
2452
2453 /* ensure that the correct cursor icon is set */
2454 static void gpencil_draw_cursor_set(tGPsdata *p)
2455 {
2456         Brush *brush = p->brush;
2457         if ((p->paintmode == GP_PAINTMODE_ERASER) ||
2458             (brush->gpencil_tool == GPAINT_TOOL_ERASE))
2459         {
2460                 WM_cursor_modal_set(p->win, BC_CROSSCURSOR);  /* XXX need a better cursor */
2461         }
2462         else {
2463                 WM_cursor_modal_set(p->win,     CURSOR_NONE);
2464
2465         }
2466 }
2467
2468 /* update UI indicators of status, including cursor and header prints */
2469 static void gpencil_draw_status_indicators(bContext *C, tGPsdata *p)
2470 {
2471         /* header prints */
2472         switch (p->status) {
2473
2474 #if 0 /* FIXME, this never runs! */
2475                 switch (p->paintmode) {
2476                         case GP_PAINTMODE_DRAW_POLY:
2477                                 /* Provide usage tips, since this is modal, and unintuitive without hints */
2478                                 ED_workspace_status_text(
2479                                         C, IFACE_(
2480                                                 "Annotation Create Poly: LMB click to place next stroke vertex | "
2481                                                 "ESC/Enter to end  (or click outside this area)"
2482                                         ));
2483                                 break;
2484                         default:
2485                                 /* Do nothing - the others are self explanatory, exit quickly once the mouse is released
2486                                  * Showing any text would just be annoying as it would flicker.
2487                                  */
2488                                 break;
2489                 }
2490 #endif
2491
2492                 case GP_STATUS_IDLING:
2493                 {
2494                         /* print status info */
2495                         switch (p->paintmode) {
2496                                 case GP_PAINTMODE_ERASER:
2497                                 {
2498                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Erase Session: Hold and drag LMB or RMB to erase | "
2499                                                 "ESC/Enter to end  (or click outside this area)"));
2500                                         break;
2501                                 }
2502                                 case GP_PAINTMODE_DRAW_STRAIGHT:
2503                                 {
2504                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Line Session: Hold and drag LMB to draw | "
2505                                                 "ESC/Enter to end  (or click outside this area)"));
2506                                         break;
2507                                 }
2508                                 case GP_PAINTMODE_SET_CP:
2509                                 {
2510                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Guides: LMB click and release to place reference point | "
2511                                                 "Esc/RMB to cancel"));
2512                                         break;
2513                                 }
2514                                 case GP_PAINTMODE_DRAW:
2515                                 {
2516                                         GP_Sculpt_Guide *guide = &p->scene->toolsettings->gp_sculpt.guide;
2517                                         if (guide->use_guide) {
2518                                                 ED_workspace_status_text(C, IFACE_("Grease Pencil Freehand Session: Hold and drag LMB to draw | "
2519                                                         "M key to flip guide | O key to move reference point"));
2520                                         }
2521                                         else {
2522                                                 ED_workspace_status_text(C, IFACE_("Grease Pencil Freehand Session: Hold and drag LMB to draw"));
2523                                         }
2524                                         break;
2525                                 }
2526                                 case GP_PAINTMODE_DRAW_POLY:
2527                                 {
2528                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Poly Session: LMB click to place next stroke vertex | "
2529                                                 "Release Shift/ESC/Enter to end  (or click outside this area)"));
2530                                         break;
2531                                 }
2532                                 default: /* unhandled future cases */
2533                                 {
2534                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Session: ESC/Enter to end   (or click outside this area)"));
2535                                         break;
2536                                 }
2537                         }
2538                         break;
2539                 }
2540                 case GP_STATUS_ERROR:
2541                 case GP_STATUS_DONE:
2542                 {
2543                         /* clear status string */
2544                         ED_workspace_status_text(C, NULL);
2545                         break;
2546                 }
2547                 case GP_STATUS_PAINTING:
2548                         break;
2549         }
2550 }
2551
2552 /* ------------------------------- */
2553
2554 /* create a new stroke point at the point indicated by the painting context */
2555 static void gpencil_draw_apply(bContext *C, wmOperator *op, tGPsdata *p, Depsgraph *depsgraph)
2556 {
2557         bGPdata *gpd = p->gpd;
2558         tGPspoint *pt = NULL;
2559
2560         /* handle drawing/erasing -> test for erasing first */
2561         if (p->paintmode == GP_PAINTMODE_ERASER) {
2562                 /* do 'live' erasing now */
2563                 gp_stroke_doeraser(p);
2564
2565                 /* store used values */
2566                 copy_v2_v2(p->mvalo, p->mval);
2567                 p->opressure = p->pressure;
2568         }
2569         /* only add current point to buffer if mouse moved (even though we got an event, it might be just noise) */
2570         else if (gp_stroke_filtermval(p, p->mval, p->mvalo)) {
2571
2572                 /* if lazy mouse, interpolate the last and current mouse positions */
2573                 if (GPENCIL_LAZY_MODE(p->brush, p->shift)) {
2574                         float now_mouse[2];
2575                         float last_mouse[2];
2576                         copy_v2_v2(now_mouse, p->mval);
2577                         copy_v2_v2(last_mouse, p->mvalo);
2578                         interp_v2_v2v2(now_mouse, now_mouse, last_mouse, p->brush->smooth_stroke_factor);
2579                         copy_v2_v2(p->mval, now_mouse);
2580                 }
2581
2582                 /* try to add point */
2583                 short ok = gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
2584
2585                 /* handle errors while adding point */
2586                 if ((ok == GP_STROKEADD_FULL) || (ok == GP_STROKEADD_OVERFLOW)) {
2587                         /* finish off old stroke */
2588                         gp_paint_strokeend(p);
2589                         /* And start a new one!!! Else, projection errors! */
2590                         gp_paint_initstroke(p, p->paintmode, depsgraph);
2591
2592                         /* start a new stroke, starting from previous point */
2593                         /* XXX Must manually reset inittime... */
2594                         /* XXX We only need to reuse previous point if overflow! */
2595                         if (ok == GP_STROKEADD_OVERFLOW) {
2596                                 p->inittime = p->ocurtime;
2597                                 gp_stroke_addpoint(p, p->mvalo, p->opressure, p->ocurtime);
2598                         }
2599                         else {
2600                                 p->inittime = p->curtime;
2601                         }
2602                         gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
2603                 }
2604                 else if (ok == GP_STROKEADD_INVALID) {
2605                         /* the painting operation cannot continue... */
2606                         BKE_report(op->reports, RPT_ERROR, "Cannot paint stroke");
2607                         p->status = GP_STATUS_ERROR;
2608
2609                         if (G.debug & G_DEBUG)
2610                                 printf("Error: Grease-Pencil Paint - Add Point Invalid\n");
2611                         return;
2612                 }
2613
2614                 /* store used values */
2615                 copy_v2_v2(p->mvalo, p->mval);
2616                 p->opressure = p->pressure;
2617                 p->ocurtime = p->curtime;
2618
2619                 pt = (tGPspoint *)gpd->runtime.sbuffer + gpd->runtime.sbuffer_size - 1;
2620                 if (p->paintmode != GP_PAINTMODE_ERASER) {
2621                         ED_gpencil_toggle_brush_cursor(C, true, &pt->x);
2622                 }
2623         }
2624         else if ((p->brush->gpencil_settings->flag & GP_BRUSH_STABILIZE_MOUSE_TEMP) &&
2625                  (gpd->runtime.sbuffer_size > 0))
2626         {
2627                 pt = (tGPspoint *)gpd->runtime.sbuffer + gpd->runtime.sbuffer_size - 1;
2628                 if (p->paintmode != GP_PAINTMODE_ERASER) {
2629                         ED_gpencil_toggle_brush_cursor(C, true, &pt->x);
2630                 }
2631         }
2632 }
2633
2634 /* Helper to rotate point around origin */
2635 static void gp_rotate_v2_v2v2fl(float v[2], const float p[2], const float origin[2], const float angle)
2636 {
2637         float pt[2];
2638         float r[2];
2639         sub_v2_v2v2(pt, p, origin);
2640         rotate_v2_v2fl(r, pt, angle);
2641         add_v2_v2v2(v, r, origin);
2642 }
2643
2644 /* Helper to snap value to grid */
2645 static float gp_snap_to_grid_fl(float v, const float offset, const float spacing)
2646 {
2647         if (spacing > 0.0f) {
2648                 return roundf(v / spacing) * spacing + fmodf(offset, spacing);
2649         }
2650         else {
2651                 return v;
2652         }
2653 }
2654
2655 static void UNUSED_FUNCTION(gp_snap_to_grid_v2)(float v[2], const float offset[2], const float spacing)
2656 {
2657         v[0] = gp_snap_to_grid_fl(v[0], offset[0], spacing);
2658         v[1] = gp_snap_to_grid_fl(v[1], offset[1], spacing);
2659 }
2660
2661 /* get reference point - screen coords to buffer coords */
2662 static void gp_origin_set(wmOperator *op, const int mval[2])
2663 {
2664         tGPsdata *p = op->customdata;
2665         GP_Sculpt_Guide *guide = &p->scene->toolsettings->gp_sculpt.guide;
2666         float origin[2];
2667         float point[3];
2668         copy_v2fl_v2i(origin, mval);
2669         gp_stroke_convertcoords(p, origin, point, NULL);
2670         if (guide->reference_point == GP_GUIDE_REF_CUSTOM) {
2671                 copy_v3_v3(guide->location, point);
2672         }
2673         else if (guide->reference_point == GP_GUIDE_REF_CURSOR) {
2674                 copy_v3_v3(p->scene->cursor.location, point);
2675         }
2676 }
2677
2678 /* get reference point - buffer coords to screen coords */
2679 static void gp_origin_get(tGPsdata *p, float origin[2])
2680 {
2681         GP_Sculpt_Guide *guide = &p->scene->toolsettings->gp_sculpt.guide;
2682         float location[3];
2683         if (guide->reference_point == GP_GUIDE_REF_CUSTOM) {
2684                 copy_v3_v3(location, guide->location);
2685         }
2686         else if (guide->reference_point == GP_GUIDE_REF_OBJECT &&
2687                  guide->reference_object != NULL)
2688         {
2689                 copy_v3_v3(location, guide->reference_object->loc);
2690         }
2691         else {
2692                 copy_v3_v3(location, p->scene->cursor.location);
2693         }
2694         GP_SpaceConversion *gsc = &p->gsc;
2695         gp_point_3d_to_xy(gsc, p->gpd->runtime.sbuffer_sflag, location, origin);
2696 }
2697
2698 /* handle draw event */
2699 static void gpencil_draw_apply_event(bContext *C, wmOperator *op, const wmEvent *event, Depsgraph *depsgraph, float x, float y)
2700 {
2701         tGPsdata *p = op->customdata;
2702         GP_Sculpt_Guide *guide = &p->scene->toolsettings->gp_sculpt.guide;
2703         PointerRNA itemptr;
2704         float mousef[2];
2705         int tablet = 0;
2706
2707         /* convert from window-space to area-space mouse coordinates
2708          * add any x,y override position for fake events
2709          */
2710         p->mval[0] = (float)event->mval[0] - x;
2711         p->mval[1] = (float)event->mval[1] - y;
2712         p->shift = event->shift;
2713
2714         /* verify direction for straight lines */
2715         if ((guide->use_guide) || ((event->alt > 0) && (RNA_boolean_get(op->ptr, "disable_straight") == false))) {
2716                 if (p->straight == 0) {
2717                         int dx = (int)fabsf(p->mval[0] - p->mvali[0]);
2718                         int dy = (int)fabsf(p->mval[1] - p->mvali[1]);
2719                         if ((dx > 0) || (dy > 0)) {
2720                                 /* store mouse direction */
2721                                 if (dx > dy) {
2722                                         p->straight = STROKE_HORIZONTAL;
2723                                 }
2724                                 else if (dx < dy) {
2725                                         p->straight = STROKE_VERTICAL;
2726                                 }
2727                         }
2728                 }
2729         }
2730
2731         p->curtime = PIL_check_seconds_timer();
2732
2733         /* handle pressure sensitivity (which is supplied by tablets) */
2734         if (event->tablet_data) {
2735                 const wmTabletData *wmtab = event->tablet_data;
2736
2737                 tablet = (wmtab->Active != EVT_TABLET_NONE);
2738                 p->pressure = wmtab->Pressure;
2739
2740                 /* Hack for pressure sensitive eraser on D+RMB when using a tablet:
2741                  * The pen has to float over the tablet surface, resulting in
2742                  * zero pressure (T47101). Ignore pressure values if floating
2743                  * (i.e. "effectively zero" pressure), and only when the "active"
2744                  * end is the stylus (i.e. the default when not eraser)
2745                  */
2746                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2747                         if ((wmtab->Active != EVT_TABLET_ERASER) && (p->pressure < 0.001f)) {
2748                                 p->pressure = 1.0f;
2749                         }
2750                 }
2751         }
2752         else {
2753                 /* No tablet data -> No pressure info is available */
2754                 p->pressure = 1.0f;
2755         }
2756
2757         /* special eraser modes */
2758         if (p->paintmode == GP_PAINTMODE_ERASER) {
2759                 if (event->shift > 0) {
2760                         p->flags |= GP_PAINTFLAG_HARD_ERASER;
2761                 }
2762                 else {
2763                         p->flags &= ~GP_PAINTFLAG_HARD_ERASER;
2764                 }
2765                 if (event->alt > 0) {
2766                         p->flags |= GP_PAINTFLAG_STROKE_ERASER;
2767                 }
2768                 else {
2769                         p->flags &= ~GP_PAINTFLAG_STROKE_ERASER;
2770                 }
2771         }
2772
2773         /* special exception for start of strokes (i.e. maybe for just a dot) */
2774         if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
2775                 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
2776
2777                 /* set values */
2778                 copy_v2_v2(p->mvalo, p->mval);
2779                 p->opressure = p->pressure;
2780                 p->inittime = p->ocurtime = p->curtime;
2781                 p->straight = 0;
2782
2783                 /* save initial mouse */
2784                 copy_v2_v2(p->mvali, p->mval);
2785
2786                 /* calculate once and store snapping distance and origin */
2787                 RegionView3D * rv3d = p->ar->regiondata;
2788                 float scale = 1.0f;
2789                 if (rv3d->is_persp) {
2790                         float vec[3];
2791                         gp_get_3d_reference(p, vec);
2792                         mul_m4_v3(rv3d->persmat, vec);
2793                         scale = vec[2] * rv3d->pixsize;
2794                 }
2795                 else {
2796                         scale = rv3d->pixsize;
2797                 }
2798                 p->guide_spacing = guide->spacing / scale;
2799                 p->half_spacing = p->guide_spacing * 0.5f;
2800                 gp_origin_get(p, p->origin);
2801
2802                 /* special exception here for too high pressure values on first touch in
2803                  * windows for some tablets, then we just skip first touch...
2804                  */
2805                 if (tablet && (p->pressure >= 0.99f)) {
2806                         return;
2807                 }
2808
2809                 /* special exception for grid snapping
2810                  * it requires direction which needs at least two points
2811                  */
2812                 if (!ELEM(p->paintmode, GP_PAINTMODE_ERASER, GP_PAINTMODE_SET_CP) &&
2813                     guide->use_guide &&
2814                     guide->use_snapping &&
2815                     (guide->type == GP_GUIDE_GRID))
2816                 {
2817                         p->flags |= GP_PAINTFLAG_REQ_VECTOR;
2818                 }
2819         }
2820
2821         /* wait for vector then add initial point */
2822         if (p->flags & GP_PAINTFLAG_REQ_VECTOR) {
2823                 if (p->straight == 0) {
2824                         return;
2825                 }
2826
2827                 p->flags &= ~GP_PAINTFLAG_REQ_VECTOR;
2828
2829                 /* create fake events */
2830                 float tmp[2];
2831                 float pt[2];
2832                 copy_v2_v2(tmp, p->mval);
2833                 sub_v2_v2v2(pt, p->mval, p->mvali);
2834                 gpencil_draw_apply_event(C, op, event, CTX_data_depsgraph(C), pt[0], pt[1]);
2835                 if (len_v2v2(p->mval, p->mvalo)) {
2836                         sub_v2_v2v2(pt, p->mval, p->mvalo);
2837                         gpencil_draw_apply_event(C, op, event, CTX_data_depsgraph(C), pt[0], pt[1]);
2838                 }
2839                 copy_v2_v2(p->mval, tmp);
2840         }
2841
2842         /* check if stroke is straight or guided */
2843         if ((p->paintmode != GP_PAINTMODE_ERASER) &&
2844             ((p->straight) || (guide->use_guide)))
2845         {
2846                 /* guided stroke */
2847                 if (guide->use_guide) {
2848                         switch (guide->type) {
2849                                 default:
2850                                 case GP_GUIDE_CIRCULAR:
2851                                 {
2852                                         float distance;
2853                                         distance = len_v2v2(p->mvali, p->origin);
2854
2855                                         if (guide->use_snapping && (guide->spacing > 0.0f)) {
2856                                                 distance = gp_snap_to_grid_fl(distance, 0.0f, p->guide_spacing);
2857                                         }
2858
2859                                         dist_ensure_v2_v2fl(p->mval, p->origin, distance);
2860                                         break;
2861                                 }
2862                                 case GP_GUIDE_RADIAL:
2863                                 {
2864                                         if (guide->use_snapping && (guide->angle_snap > 0.0f)) {
2865                                                 float point[2];
2866                                                 float xy[2];
2867                                                 float angle;
2868                                                 float half_angle = guide->angle_snap * 0.5f;
2869                                                 sub_v2_v2v2(xy, p->mvali, p->origin);
2870                                                 angle = atan2f(xy[1], xy[0]);
2871                                                 angle += (M_PI * 2.0f);
2872                                                 angle = fmodf(angle + half_angle, guide->angle_snap);
2873                                                 angle -= half_angle;
2874                                                 gp_rotate_v2_v2v2fl(point, p->mvali, p->origin, -angle);
2875                                                 closest_to_line_v2(p->mval, p->mval, point, p->origin);
2876                                         }
2877                                         else {
2878                                                 closest_to_line_v2(p->mval, p->mval, p->mvali, p->origin);
2879                                         }
2880                                         break;
2881                                 }
2882                                 case GP_GUIDE_PARALLEL:
2883                                 {
2884                                         float point[2];
2885                                         float unit[2];
2886                                         copy_v2_v2(unit, p->mvali);
2887                                         unit[0] += 1.0f; /* start from horizontal */
2888                                         gp_rotate_v2_v2v2fl(point, unit, p->mvali, guide->angle);
2889                                         closest_to_line_v2(p->mval, p->mval, p->mvali, point);
2890
2891                                         if (guide->use_snapping && (guide->spacing > 0.0f)) {
2892                                                 gp_rotate_v2_v2v2fl(p->mval, p->mval, p->origin, -guide->angle);
2893                                                 p->mval[1] = gp_snap_to_grid_fl(p->mval[1] - p->half_spacing, p->origin[1], p->guide_spacing);
2894                                                 gp_rotate_v2_v2v2fl(p->mval, p->mval, p->origin, guide->angle);
2895                                         }
2896                                         break;
2897                                 }
2898                                 case GP_GUIDE_GRID:
2899                                 {
2900                                         if (guide->use_snapping && (guide->spacing > 0.0f)) {
2901                                                 float point[2];
2902                                                 float unit[2];
2903                                                 float angle;
2904                                                 copy_v2_v2(unit, p->mvali);
2905                                                 unit[0] += 1.0f; /* start from horizontal */
2906                                                 angle = (p->straight == STROKE_VERTICAL) ? M_PI_2 : 0.0f;
2907                                                 gp_rotate_v2_v2v2fl(point, unit, p->mvali, angle);
2908                                                 closest_to_line_v2(p->mval, p->mval, p->mvali, point);
2909
2910                                                 if (p->straight == STROKE_HORIZONTAL) {
2911                                                         p->mval[1] = gp_snap_to_grid_fl(p->mval[1] - p->half_spacing, p->origin[1], p->guide_spacing);
2912                                                 }
2913                                                 else {
2914                                                         p->mval[0] = gp_snap_to_grid_fl(p->mval[0] - p->half_spacing, p->origin[0], p->guide_spacing);
2915                                                 }
2916                                         }
2917                                         else if (p->straight == STROKE_HORIZONTAL) {
2918                                                 p->mval[1] = p->mvali[1]; /* replace y */
2919                                         }
2920                                         else {
2921                                                 p->mval[0] = p->mvali[0]; /* replace x */
2922                                         }
2923                                         break;
2924                                 }
2925                         }
2926                 }
2927                 else if (p->straight == STROKE_HORIZONTAL) {
2928                         p->mval[1] = p->mvali[1]; /* replace y */
2929                 }
2930                 else {
2931                         p->mval[0] = p->mvali[0]; /* replace x */
2932                 }
2933         }
2934
2935         /* fill in stroke data (not actually used directly by gpencil_draw_apply) */
2936         RNA_collection_add(op->ptr, "stroke", &itemptr);
2937
2938         mousef[0] = p->mval[0];
2939         mousef[1] = p->mval[1];
2940         RNA_float_set_array(&itemptr, "mouse", mousef);
2941         RNA_float_set(&itemptr, "pressure", p->pressure);
2942         RNA_boolean_set(&itemptr, "is_start", (p->flags & GP_PAINTFLAG_FIRSTRUN) != 0);
2943
2944         RNA_float_set(&itemptr, "time", p->curtime - p->inittime);
2945
2946         /* apply the current latest drawing point */
2947         gpencil_draw_apply(C, op, p, depsgraph);
2948
2949         /* force refresh */
2950         /* just active area for now, since doing whole screen is too slow */
2951         ED_region_tag_redraw(p->ar);
2952 }
2953
2954 /* ------------------------------- */
2955
2956 /* operator 'redo' (i.e. after changing some properties, but also for repeat last) */
2957 static int gpencil_draw_exec(bContext *C, wmOperator *op)
2958 {
2959         tGPsdata *p = NULL;
2960         Depsgraph *depsgraph = CTX_data_depsgraph(C);
2961
2962         /* printf("GPencil - Starting Re-Drawing\n"); */
2963
2964         /* try to initialize context data needed while drawing */
2965         if (!gpencil_draw_init(C, op, NULL)) {
2966                 MEM_SAFE_FREE(op->customdata);