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