Grease Pencil v2 Branch
[blender-staging.git] / source / blender / editors / gpencil / gpencil_brush.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2015, Blender Foundation
19  * This is a new part of Blender
20  *
21  * Contributor(s): Joshua Leung, Antonio Vazquez
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  *
25  * Brush based operators for editing Grease Pencil strokes
26  */
27
28 /** \file blender/editors/gpencil/gpencil_brush.c
29  *  \ingroup edgpencil
30  */
31
32
33 #include <stdio.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stddef.h>
37 #include <math.h>
38
39 #include "MEM_guardedalloc.h"
40
41 #include "BLI_blenlib.h"
42 #include "BLI_ghash.h"
43 #include "BLI_math.h"
44 #include "BLI_rand.h"
45 #include "BLI_utildefines.h"
46
47 #include "BLT_translation.h"
48
49 #include "DNA_scene_types.h"
50 #include "DNA_screen_types.h"
51 #include "DNA_space_types.h"
52 #include "DNA_view3d_types.h"
53 #include "DNA_gpencil_types.h"
54 #include "DNA_object_types.h"
55
56 #include "BKE_context.h"
57 #include "BKE_global.h"
58 #include "BKE_gpencil.h"
59 #include "BKE_library.h"
60 #include "BKE_report.h"
61 #include "BKE_screen.h"
62
63 #include "UI_interface.h"
64
65 #include "WM_api.h"
66 #include "WM_types.h"
67
68 #include "RNA_access.h"
69 #include "RNA_define.h"
70 #include "RNA_enum_types.h"
71
72 #include "UI_view2d.h"
73
74 #include "ED_gpencil.h"
75 #include "ED_screen.h"
76 #include "ED_view3d.h"
77
78 #include "BIF_gl.h"
79 #include "BIF_glutil.h"
80
81 #include "gpencil_intern.h"
82
83 /* ************************************************ */
84 /* General Brush Editing Context */
85
86 /* Context for brush operators */
87 typedef struct tGP_BrushEditData {
88         /* Current editor/region/etc. */
89         /* NOTE: This stuff is mainly needed to handle 3D view projection stuff... */
90         Scene *scene;
91         
92         ScrArea *sa;
93         ARegion *ar;
94         
95         /* Current GPencil datablock */
96         bGPdata *gpd;
97         
98         /* Brush Settings */
99         GP_BrushEdit_Settings *settings;
100         GP_EditBrush_Data *brush;
101         
102         eGP_EditBrush_Types brush_type;
103         eGP_EditBrush_Flag  flag;
104         
105         /* Space Conversion Data */
106         GP_SpaceConversion gsc;
107         
108         
109         /* Is the brush currently painting? */
110         bool is_painting;
111         
112         /* Start of new sculpt stroke */
113         bool first;
114         
115         /* Current frame */
116         int cfra;
117         
118         
119         /* Brush Runtime Data: */
120         /* - position and pressure
121          * - the *_prev variants are the previous values
122          */
123         int   mval[2], mval_prev[2];
124         float pressure, pressure_prev;
125         
126         /* - effect vector (e.g. 2D/3D translation for grab brush) */
127         float dvec[3];
128         
129         /* brush geometry (bounding box) */
130         rcti brush_rect;
131         
132         /* Custom data for certain brushes */
133         /* - map from bGPDstroke's to structs containing custom data about those strokes */
134         GHash *stroke_customdata;
135         /* - general customdata */
136         void *customdata;
137         
138         
139         /* Timer for in-place accumulation of brush effect */
140         wmTimer *timer;
141         bool timerTick; /* is this event from a timer */
142 } tGP_BrushEditData;
143
144
145 /* Callback for performing some brush operation on a single point */
146 typedef bool (*GP_BrushApplyCb)(tGP_BrushEditData *gso, bGPDstroke *gps, int i,
147                                 const int radius, const int co[2]);
148
149 /* ************************************************ */
150 /* Utility Functions */
151
152 /* Context ---------------------------------------- */
153
154 /* Get the sculpting settings */
155 static GP_BrushEdit_Settings *gpsculpt_get_settings(Scene *scene)
156 {
157         return &scene->toolsettings->gp_sculpt;
158 }
159
160 /* Get the active brush */
161 static GP_EditBrush_Data *gpsculpt_get_brush(Scene *scene)
162 {
163         GP_BrushEdit_Settings *gset = &scene->toolsettings->gp_sculpt;
164         return &gset->brush[gset->brushtype];
165 }
166
167 /* Brush Operations ------------------------------- */
168
169 /* Invert behaviour of brush? */
170 static bool gp_brush_invert_check(tGP_BrushEditData *gso)
171 {
172         /* The basic setting is the brush's setting (from the panel) */
173         bool invert = ((gso->brush->flag & GP_EDITBRUSH_FLAG_INVERT) != 0);
174         
175         /* During runtime, the user can hold down the Ctrl key to invert the basic behaviour */
176         if (gso->flag & GP_EDITBRUSH_FLAG_INVERT) {
177                 invert ^= true;
178         }
179                 
180         return invert;
181 }
182
183 /* Compute strength of effect */
184 static float gp_brush_influence_calc(tGP_BrushEditData *gso, const int radius, const int co[2])
185 {
186         GP_EditBrush_Data *brush = gso->brush;
187         
188         /* basic strength factor from brush settings */
189         float influence = brush->strength;
190         
191         /* use pressure? */
192         if (brush->flag & GP_EDITBRUSH_FLAG_USE_PRESSURE) {
193                 influence *= gso->pressure;
194         }
195         
196         /* distance fading */
197         if (brush->flag & GP_EDITBRUSH_FLAG_USE_FALLOFF) {
198                 float distance = (float)len_v2v2_int(gso->mval, co);
199                 float fac;
200                 
201                 CLAMP(distance, 0.0f, (float)radius);
202                 fac = 1.0f - (distance / (float)radius);
203                 
204                 influence *= fac;
205         }
206         
207         /* return influence */
208         return influence;
209 }
210
211 /* ************************************************ */
212 /* Brush Callbacks */
213 /* This section defines the callbacks used by each brush to perform their magic.
214  * These are called on each point within the brush's radius.
215  */
216
217 /* ----------------------------------------------- */
218 /* Smooth Brush */
219
220 /* A simple (but slower + inaccurate) smooth-brush implementation to test the algorithm for stroke smoothing */
221 static bool gp_brush_smooth_apply(tGP_BrushEditData *gso, bGPDstroke *gps, int i,
222                                   const int radius, const int co[2])
223 {
224         GP_EditBrush_Data *brush = gso->brush;
225         float inf = gp_brush_influence_calc(gso, radius, co);
226         bool affect_pressure = (brush->flag & GP_EDITBRUSH_FLAG_SMOOTH_PRESSURE) != 0;
227         /* need one flag enabled by default */
228         if ((gso->settings->flag & (GP_BRUSHEDIT_FLAG_APPLY_POSITION |
229                                     GP_BRUSHEDIT_FLAG_APPLY_STRENGTH |
230                                     GP_BRUSHEDIT_FLAG_APPLY_THICKNESS)) == 0)
231         {
232                 gso->settings->flag |= GP_BRUSHEDIT_FLAG_APPLY_POSITION;
233         }
234
235         /* perform smoothing */
236         if (gso->settings->flag & GP_BRUSHEDIT_FLAG_APPLY_POSITION) {
237                 gp_smooth_stroke(gps, i, inf, affect_pressure);
238         }
239         if (gso->settings->flag & GP_BRUSHEDIT_FLAG_APPLY_STRENGTH) {
240                 gp_smooth_stroke_strength(gps, i, inf);
241         }
242         if (gso->settings->flag & GP_BRUSHEDIT_FLAG_APPLY_THICKNESS) {
243                 gp_smooth_stroke_thickness(gps, i, inf);
244         }
245         
246         return true;
247 }
248
249 /* ----------------------------------------------- */
250 /* Line Thickness Brush */
251
252 /* Make lines thicker or thinner by the specified amounts */
253 static bool gp_brush_thickness_apply(tGP_BrushEditData *gso, bGPDstroke *gps, int i,
254                                      const int radius, const int co[2])
255 {
256         bGPDspoint *pt = gps->points + i;
257         float inf;
258         
259         /* Compute strength of effect
260          * - We divide the strength by 10, so that users can set "sane" values.
261          *   Otherwise, good default values are in the range of 0.093
262          */
263         inf = gp_brush_influence_calc(gso, radius, co) / 10.0f;
264         
265         /* apply */
266         // XXX: this is much too strong, and it should probably do some smoothing with the surrounding stuff
267         if (gp_brush_invert_check(gso)) {
268                 /* make line thinner - reduce stroke pressure */
269                 pt->pressure -= inf;
270         }
271         else {
272                 /* make line thicker - increase stroke pressure */
273                 pt->pressure += inf;
274         }
275         
276         /* Pressure should stay within [0.0, 1.0]
277          * However, it is nice for volumetric strokes to be able to exceed
278          * the upper end of this range. Therefore, we don't actually clamp
279          * down on the upper end.
280          */
281         if (pt->pressure < 0.0f)
282                 pt->pressure = 0.0f;
283         
284         return true;
285 }
286
287
288 /* ----------------------------------------------- */
289 /* Color Strength Brush */
290
291 /* Make color more or less transparent by the specified amounts */
292 static bool gp_brush_strength_apply(
293         tGP_BrushEditData *gso, bGPDstroke *gps, int i,
294         const int radius, const int co[2])
295 {
296         bGPDspoint *pt = gps->points + i;
297         float inf;
298
299         /* Compute strength of effect
300         * - We divide the strength by 10, so that users can set "sane" values.
301         *   Otherwise, good default values are in the range of 0.093
302         */
303         inf = gp_brush_influence_calc(gso, radius, co) / 10.0f;
304
305         /* apply */
306         // XXX: this is much too strong, and it should probably do some smoothing with the surrounding stuff
307         if (gp_brush_invert_check(gso)) {
308                 /* make line thinner - reduce stroke pressure */
309                 pt->strength -= inf;
310         }
311         else {
312                 /* make line thicker - increase stroke pressure */
313                 pt->strength += inf;
314         }
315
316         /* Strength should stay within [0.0, 1.0] */
317         CLAMP(pt->strength, 0.0f, 1.0f);
318
319         return true;
320 }
321
322
323 /* ----------------------------------------------- */
324 /* Grab Brush */
325
326 /* Custom data per stroke for the Grab Brush
327  *
328  * This basically defines the strength of the effect for each
329  * affected stroke point that was within the initial range of
330  * the brush region.
331  */
332 typedef struct tGPSB_Grab_StrokeData {
333         /* array of indices to corresponding points in the stroke */
334         int   *points;
335         /* array of influence weights for each of the included points */
336         float *weights;
337         
338         /* capacity of the arrays */
339         int capacity;
340         /* actual number of items currently stored */
341         int size;
342 } tGPSB_Grab_StrokeData;
343
344 /* initialise custom data for handling this stroke */
345 static void gp_brush_grab_stroke_init(tGP_BrushEditData *gso, bGPDstroke *gps)
346 {
347         tGPSB_Grab_StrokeData *data = NULL;
348         
349         BLI_assert(gps->totpoints > 0);
350         
351         /* Check if there are buffers already (from a prior run) */
352         if (BLI_ghash_haskey(gso->stroke_customdata, gps)) {
353                 /* Ensure that the caches are empty
354                  * - Since we reuse these between different strokes, we don't
355                  *   want the previous invocation's data polluting the arrays
356                  */
357                 data = BLI_ghash_lookup(gso->stroke_customdata, gps);
358                 BLI_assert(data != NULL);
359                 
360                 data->size = 0; /* minimum requirement - so that we can repopulate again */
361                 
362                 memset(data->points, 0, sizeof(int) * data->capacity);
363                 memset(data->weights, 0, sizeof(float) * data->capacity);
364         }
365         else {
366                 /* Create new instance */
367                 data = MEM_callocN(sizeof(tGPSB_Grab_StrokeData), "GP Stroke Grab Data");
368                 
369                 data->capacity = gps->totpoints;
370                 data->size = 0;
371                 
372                 data->points  = MEM_callocN(sizeof(int) * data->capacity, "GP Stroke Grab Indices");
373                 data->weights = MEM_callocN(sizeof(float) * data->capacity, "GP Stroke Grab Weights");
374                 
375                 /* hook up to the cache */
376                 BLI_ghash_insert(gso->stroke_customdata, gps, data);
377         }       
378 }
379
380 /* store references to stroke points in the initial stage */
381 static bool gp_brush_grab_store_points(tGP_BrushEditData *gso, bGPDstroke *gps, int i,
382                                        const int radius, const int co[2])
383 {
384         tGPSB_Grab_StrokeData *data = BLI_ghash_lookup(gso->stroke_customdata, gps);
385         float inf = gp_brush_influence_calc(gso, radius, co);
386         
387         BLI_assert(data != NULL);
388         BLI_assert(data->size < data->capacity);
389         
390         /* insert this point into the set of affected points */
391         data->points[data->size]  = i;
392         data->weights[data->size] = inf;
393         data->size++;
394         
395         /* done */
396         return true;
397 }
398
399 /* Compute effect vector for grab brush */
400 static void gp_brush_grab_calc_dvec(tGP_BrushEditData *gso)
401 {
402         /* Convert mouse-movements to movement vector */
403         // TODO: incorporate pressure into this?
404         // XXX: screen-space strokes in 3D space will suffer!
405         if (gso->sa->spacetype == SPACE_VIEW3D) {
406                 View3D *v3d = gso->sa->spacedata.first;
407                 RegionView3D *rv3d = gso->ar->regiondata;
408                 float *rvec = ED_view3d_cursor3d_get(gso->scene, v3d);
409                 float zfac = ED_view3d_calc_zfac(rv3d, rvec, NULL);
410                 
411                 float mval_f[2];
412                 
413                 /* convert from 2D screenspace to 3D... */
414                 mval_f[0] = (float)(gso->mval[0] - gso->mval_prev[0]);
415                 mval_f[1] = (float)(gso->mval[1] - gso->mval_prev[1]);
416                 
417                 ED_view3d_win_to_delta(gso->ar, mval_f, gso->dvec, zfac);
418         }
419         else {
420                 /* 2D - just copy */
421                 // XXX: view2d?
422                 gso->dvec[0] = (float)(gso->mval[0] - gso->mval_prev[0]);
423                 gso->dvec[1] = (float)(gso->mval[1] - gso->mval_prev[1]);
424                 gso->dvec[2] = 0.0f;  /* unused */
425         }
426 }
427
428 /* Apply grab transform to all relevant points of the affected strokes */
429 static void gp_brush_grab_apply_cached(
430         tGP_BrushEditData *gso, bGPDstroke *gps, bool parented, float diff_mat[4][4])
431 {
432         tGPSB_Grab_StrokeData *data = BLI_ghash_lookup(gso->stroke_customdata, gps);
433         int i;
434
435         /* Apply dvec to all of the stored points */
436         for (i = 0; i < data->size; i++) {
437                 bGPDspoint *pt = &gps->points[data->points[i]];
438                 float delta[3] = {0.0f};
439                 
440                 /* adjust the amount of displacement to apply */
441                 mul_v3_v3fl(delta, gso->dvec, data->weights[i]);
442                 if (!parented) {
443                         /* apply */
444                         add_v3_v3(&pt->x, delta);
445                 }
446                 else {
447                         float fpt[3];
448                         /* apply transformation */
449                         mul_v3_m4v3(fpt, diff_mat, &pt->x);
450                         /* apply */
451                         add_v3_v3(fpt, delta);
452                         copy_v3_v3(&pt->x, fpt);
453                         /* undo transformation to the init parent position */
454                         float inverse_diff_mat[4][4];
455                         invert_m4_m4(inverse_diff_mat, diff_mat);
456                         mul_m4_v3(inverse_diff_mat, &pt->x);
457                 }
458                 
459         }
460 }
461
462 /* free customdata used for handling this stroke */
463 static void gp_brush_grab_stroke_free(void *ptr)
464 {
465         tGPSB_Grab_StrokeData *data = (tGPSB_Grab_StrokeData *)ptr;
466         
467         /* free arrays */
468         MEM_freeN(data->points);
469         MEM_freeN(data->weights);
470         
471         /* ... and this item itself, since it was also allocated */
472         MEM_freeN(data);
473 }
474
475 /* ----------------------------------------------- */
476 /* Push Brush */
477 /* NOTE: Depends on gp_brush_grab_calc_dvec() */
478
479 static bool gp_brush_push_apply(tGP_BrushEditData *gso, bGPDstroke *gps, int i,
480                                 const int radius, const int co[2])
481 {
482         bGPDspoint *pt = gps->points + i;
483         float inf = gp_brush_influence_calc(gso, radius, co);
484         float delta[3] = {0.0f};
485                 
486         /* adjust the amount of displacement to apply */
487         mul_v3_v3fl(delta, gso->dvec, inf);
488         
489         /* apply */
490         add_v3_v3(&pt->x, delta);
491
492         /* done */
493         return true;
494 }
495
496 /* ----------------------------------------------- */
497 /* Pinch Brush */
498
499 /* Compute reference midpoint for the brush - this is what we'll be moving towards */
500 static void gp_brush_calc_midpoint(tGP_BrushEditData *gso)
501 {
502         if (gso->sa->spacetype == SPACE_VIEW3D) {
503                 /* Convert mouse position to 3D space
504                  * See: gpencil_paint.c :: gp_stroke_convertcoords()
505                  */
506                 View3D *v3d = gso->sa->spacedata.first;
507                 RegionView3D *rv3d = gso->ar->regiondata;
508                 float *rvec = ED_view3d_cursor3d_get(gso->scene, v3d);
509                 float zfac = ED_view3d_calc_zfac(rv3d, rvec, NULL);
510                 
511                 float mval_f[2] = {UNPACK2(gso->mval)};
512                 float mval_prj[2];
513                 float dvec[3];
514                 
515                 
516                 if (ED_view3d_project_float_global(gso->ar, rvec, mval_prj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
517                         sub_v2_v2v2(mval_f, mval_prj, mval_f);
518                         ED_view3d_win_to_delta(gso->ar, mval_f, dvec, zfac);
519                         sub_v3_v3v3(gso->dvec, rvec, dvec);
520                 }
521                 else {
522                         zero_v3(gso->dvec);
523                 }
524         }
525         else {
526                 /* Just 2D coordinates */
527                 // XXX: fix View2D offsets later
528                 gso->dvec[0] = (float)gso->mval[0];
529                 gso->dvec[1] = (float)gso->mval[1];
530                 gso->dvec[2] = 0.0f;
531         }
532 }
533
534 /* Shrink distance between midpoint and this point... */
535 static bool gp_brush_pinch_apply(tGP_BrushEditData *gso, bGPDstroke *gps, int i,
536                                  const int radius, const int co[2])
537 {
538         bGPDspoint *pt = gps->points + i;
539         float fac, inf;
540         float vec[3];
541         
542         /* Scale down standard influence value to get it more manageable...
543          *  - No damping = Unmanageable at > 0.5 strength
544          *  - Div 10     = Not enough effect
545          *  - Div 5      = Happy medium... (by trial and error)
546          */
547         inf = gp_brush_influence_calc(gso, radius, co) / 5.0f;
548         
549         /* 1) Make this point relative to the cursor/midpoint (dvec) */
550         sub_v3_v3v3(vec, &pt->x, gso->dvec);
551         
552         /* 2) Shrink the distance by pulling the point towards the midpoint
553          *    (0.0 = at midpoint, 1 = at edge of brush region)
554          *                         OR
555          *    Increase the distance (if inverting the brush action!)
556          */
557         if (gp_brush_invert_check(gso)) {
558                 /* Inflate (inverse) */
559                 fac = 1.0f + (inf * inf); /* squared to temper the effect... */
560         }
561         else {
562                 /* Shrink (default) */
563                 fac = 1.0f - (inf * inf); /* squared to temper the effect... */
564         }
565         mul_v3_fl(vec, fac);
566         
567         /* 3) Translate back to original space, with the shrinkage applied */
568         add_v3_v3v3(&pt->x, gso->dvec, vec);
569         
570         /* done */
571         return true;
572 }
573
574 /* ----------------------------------------------- */
575 /* Twist Brush - Rotate Around midpoint */
576
577 /* Take the screenspace coordinates of the point, rotate this around the brush midpoint,
578  * convert the rotated point and convert it into "data" space
579  */
580
581 static bool gp_brush_twist_apply(tGP_BrushEditData *gso, bGPDstroke *gps, int i,
582                                  const int radius, const int co[2])
583 {
584         bGPDspoint *pt = gps->points + i;
585         float angle, inf;
586         
587         /* Angle to rotate by */
588         inf = gp_brush_influence_calc(gso, radius, co);
589         angle = DEG2RADF(1.0f) * inf;
590         
591         if (gp_brush_invert_check(gso)) {
592                 /* invert angle that we rotate by */
593                 angle *= -1;
594         }
595         
596         /* Rotate in 2D or 3D space? */
597         if (gps->flag & GP_STROKE_3DSPACE) {
598                 /* Perform rotation in 3D space... */
599                 RegionView3D *rv3d = gso->ar->regiondata;
600                 float rmat[3][3];
601                 float axis[3];
602                 float vec[3];
603                 
604                 /* Compute rotation matrix - rotate around view vector by angle */
605                 negate_v3_v3(axis, rv3d->persinv[2]);
606                 normalize_v3(axis);
607                 
608                 axis_angle_normalized_to_mat3(rmat, axis, angle);
609                 
610                 /* Rotate point (no matrix-space transforms needed, as GP points are in world space) */
611                 sub_v3_v3v3(vec, &pt->x, gso->dvec); /* make relative to center (center is stored in dvec) */
612                 mul_m3_v3(rmat, vec);
613                 add_v3_v3v3(&pt->x, vec, gso->dvec); /* restore */
614         }
615         else {
616                 const float axis[3] = {0.0f, 0.0f, 1.0f};
617                 float vec[3] = {0.0f};
618                 float rmat[3][3];
619                 
620                 /* Express position of point relative to cursor, ready to rotate */
621                 // XXX: There is still some offset here, but it's close to working as expected...
622                 vec[0] = (float)(co[0] - gso->mval[0]);
623                 vec[1] = (float)(co[1] - gso->mval[1]);
624                 
625                 /* rotate point */
626                 axis_angle_normalized_to_mat3(rmat, axis, angle);
627                 mul_m3_v3(rmat, vec);
628                 
629                 /* Convert back to screen-coordinates */
630                 vec[0] += (float)gso->mval[0];
631                 vec[1] += (float)gso->mval[1];
632                 
633                 /* Map from screen-coordinates to final coordinate space */
634                 if (gps->flag & GP_STROKE_2DSPACE) {
635                         View2D *v2d = gso->gsc.v2d;
636                         UI_view2d_region_to_view(v2d, vec[0], vec[1], &pt->x, &pt->y);
637                 }
638                 else {
639                         // XXX
640                         copy_v2_v2(&pt->x, vec);
641                 }
642         }
643         
644         /* done */
645         return true;
646 }
647
648
649 /* ----------------------------------------------- */
650 /* Randomize Brush */
651
652 /* Apply some random jitter to the point */
653 static bool gp_brush_randomize_apply(tGP_BrushEditData *gso, bGPDstroke *gps, int i,
654                                      const int radius, const int co[2])
655 {
656         bGPDspoint *pt = gps->points + i;
657         
658         /* Amount of jitter to apply depends on the distance of the point to the cursor,
659          * as well as the strength of the brush
660          */
661         const float inf = gp_brush_influence_calc(gso, radius, co) / 2.0f;
662         const float fac = BLI_frand() * inf;
663         /* need one flag enabled by default */
664         if ((gso->settings->flag & (GP_BRUSHEDIT_FLAG_APPLY_POSITION |
665                                     GP_BRUSHEDIT_FLAG_APPLY_STRENGTH |
666                                     GP_BRUSHEDIT_FLAG_APPLY_THICKNESS)) == 0)
667         {
668                 gso->settings->flag |= GP_BRUSHEDIT_FLAG_APPLY_POSITION;
669         }
670
671         /* apply random to position */
672         if (gso->settings->flag & GP_BRUSHEDIT_FLAG_APPLY_POSITION) {
673                 /* Jitter is applied perpendicular to the mouse movement vector
674                  * - We compute all effects in screenspace (since it's easier)
675                  *   and then project these to get the points/distances in
676                  *   viewspace as needed
677                  */
678                 float mvec[2], svec[2];
679
680                 /* mouse movement in ints -> floats */
681                 mvec[0] = (float)(gso->mval[0] - gso->mval_prev[0]);
682                 mvec[1] = (float)(gso->mval[1] - gso->mval_prev[1]);
683
684                 /* rotate mvec by 90 degrees... */
685                 svec[0] = -mvec[1];
686                 svec[1] =  mvec[0];
687
688                 /* scale the displacement by the random displacement, and apply */
689                 if (BLI_frand() > 0.5f) {
690                         mul_v2_fl(svec, -fac);
691                 }
692                 else {
693                         mul_v2_fl(svec, fac);
694                 }
695
696                 //printf("%f %f (%f), nco = {%f %f}, co = %d %d\n", svec[0], svec[1], fac, nco[0], nco[1], co[0], co[1]);
697
698                 /* convert to dataspace */
699                 if (gps->flag & GP_STROKE_3DSPACE) {
700                         /* 3D: Project to 3D space */
701                         if (gso->sa->spacetype == SPACE_VIEW3D) {
702                                 bool flip;
703                                 RegionView3D *rv3d = gso->ar->regiondata;
704                                 float zfac = ED_view3d_calc_zfac(rv3d, &pt->x, &flip);
705                                 if (flip == false) {
706                                         float dvec[3];
707                                         ED_view3d_win_to_delta(gso->gsc.ar, svec, dvec, zfac);
708                                         add_v3_v3(&pt->x, dvec);
709                                 }
710                         }
711                         else {
712                                 /* ERROR */
713                                 BLI_assert("3D stroke being sculpted in non-3D view");
714                         }
715                 }
716                 else {
717                         /* 2D: As-is */
718                         // XXX: v2d scaling/offset?
719                         float nco[2];
720                         nco[0] = (float)co[0] + svec[0];
721                         nco[1] = (float)co[1] + svec[1];
722
723                         copy_v2_v2(&pt->x, nco);
724                 }
725         }
726         /* apply random to strength */
727         if (gso->settings->flag & GP_BRUSHEDIT_FLAG_APPLY_STRENGTH) {
728                 if (BLI_frand() > 0.5f) {
729                         pt->strength += fac;
730                 }
731                 else {
732                         pt->strength -= fac;
733                 }
734                 CLAMP_MIN(pt->strength, 0.0f);
735                 CLAMP_MAX(pt->strength, 1.0f);
736         }
737         /* apply random to thickness (use pressure) */
738         if (gso->settings->flag & GP_BRUSHEDIT_FLAG_APPLY_THICKNESS) {
739                 if (BLI_frand() > 0.5f) {
740                         pt->pressure += fac;
741                 }
742                 else {
743                         pt->pressure -= fac;
744                 }
745                 /* only limit lower value */
746                 CLAMP_MIN(pt->pressure, 0.0f);
747         }
748
749         /* done */
750         return true;
751 }
752
753 /* ************************************************ */
754 /* Non Callback-Based Brushes */
755
756 /* Clone Brush ------------------------------------- */
757 /* How this brush currently works:
758  * - If this is start of the brush stroke, paste immediately under the cursor
759  *   by placing the midpoint of the buffer strokes under the cursor now
760  *
761  * - Otherwise, in:
762  *   "Stamp Mode" - Move the newly pasted strokes so that their center follows the cursor
763  *   "Continuous" - Repeatedly just paste new copies for where the brush is now
764  */
765
766 /* Custom state data for clone brush */
767 typedef struct tGPSB_CloneBrushData {
768         /* midpoint of the strokes on the clipboard */
769         float buffer_midpoint[3];
770         
771         /* number of strokes in the paste buffer (and/or to be created each time) */
772         size_t totitems;
773         
774         /* for "stamp" mode, the currently pasted brushes */
775         bGPDstroke **new_strokes;
776 } tGPSB_CloneBrushData;
777
778 /* Initialise "clone" brush data */
779 static void gp_brush_clone_init(bContext *C, tGP_BrushEditData *gso)
780 {
781         tGPSB_CloneBrushData *data;
782         bGPDstroke *gps;
783         
784         /* init custom data */
785         gso->customdata = data = MEM_callocN(sizeof(tGPSB_CloneBrushData), "CloneBrushData");
786         
787         /* compute midpoint of strokes on clipboard */
788         for (gps = gp_strokes_copypastebuf.first; gps; gps = gps->next) {
789                 if (ED_gpencil_stroke_can_use(C, gps)) {
790                         const float dfac = 1.0f / ((float)gps->totpoints);
791                         float mid[3] = {0.0f};
792                         
793                         bGPDspoint *pt;
794                         int i;
795                         
796                         /* compute midpoint of this stroke */
797                         for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) {
798                                 float co[3];
799                                 
800                                 mul_v3_v3fl(co, &pt->x, dfac);
801                                 add_v3_v3(mid, co);
802                         }
803                         
804                         /* combine this stroke's data with the main data */
805                         add_v3_v3(data->buffer_midpoint, mid);
806                         data->totitems++;
807                 }
808         }
809         
810         /* Divide the midpoint by the number of strokes, to finish averaging it */
811         if (data->totitems > 1) {
812                 mul_v3_fl(data->buffer_midpoint, 1.0f / (float)data->totitems);
813         }
814         
815         /* Create a buffer for storing the current strokes */
816         if (1 /*gso->brush->mode == GP_EDITBRUSH_CLONE_MODE_STAMP*/) {
817                 data->new_strokes = MEM_callocN(sizeof(bGPDstroke *) * data->totitems, "cloned strokes ptr array");
818         }
819 }
820
821 /* Free custom data used for "clone" brush */
822 static void gp_brush_clone_free(tGP_BrushEditData *gso)
823 {
824         tGPSB_CloneBrushData *data = gso->customdata;
825         
826         /* free strokes array */
827         if (data->new_strokes) {
828                 MEM_freeN(data->new_strokes);
829                 data->new_strokes = NULL;
830         }
831         
832         /* free the customdata itself */
833         MEM_freeN(data);
834         gso->customdata = NULL;
835 }
836
837 /* Create new copies of the strokes on the clipboard */
838 static void gp_brush_clone_add(bContext *C, tGP_BrushEditData *gso)
839 {
840         tGPSB_CloneBrushData *data = gso->customdata;
841         
842         Scene *scene = gso->scene;
843         bGPDlayer *gpl = CTX_data_active_gpencil_layer(C);
844         bGPDframe *gpf = gpencil_layer_getframe(gpl, CFRA, true);
845         bGPDstroke *gps;
846         
847         float delta[3];
848         size_t strokes_added = 0;
849         
850         /* Compute amount to offset the points by */
851         /* NOTE: This assumes that screenspace strokes are NOT used in the 3D view... */
852         
853         gp_brush_calc_midpoint(gso); /* this puts the cursor location into gso->dvec */
854         sub_v3_v3v3(delta, gso->dvec, data->buffer_midpoint);
855         
856         /* Copy each stroke into the layer */
857         for (gps = gp_strokes_copypastebuf.first; gps; gps = gps->next) {
858                 if (ED_gpencil_stroke_can_use(C, gps)) {
859                         bGPDstroke *new_stroke;
860                         bGPDspoint *pt;
861                         int i;
862                         
863                         /* Make a new stroke */
864                         new_stroke = MEM_dupallocN(gps);
865                         
866                         new_stroke->points = MEM_dupallocN(gps->points);
867                         new_stroke->triangles = MEM_dupallocN(gps->triangles);
868                         
869                         new_stroke->next = new_stroke->prev = NULL;
870                         BLI_addtail(&gpf->strokes, new_stroke);
871                         
872                         /* Adjust all the stroke's points, so that the strokes
873                          * get pasted relative to where the cursor is now
874                          */
875                         for (i = 0, pt = new_stroke->points; i < new_stroke->totpoints; i++, pt++) {
876                                 /* assume that the delta can just be applied, and then everything works */
877                                 add_v3_v3(&pt->x, delta);
878                         }
879                         
880                         /* Store ref for later */
881                         if ((data->new_strokes) && (strokes_added < data->totitems)) {
882                                 data->new_strokes[strokes_added] = new_stroke;
883                                 strokes_added++;
884                         }
885                 }
886         }
887 }
888
889 /* Move newly-added strokes around - "Stamp" mode of the Clone brush */
890 static void gp_brush_clone_adjust(tGP_BrushEditData *gso)
891 {
892         tGPSB_CloneBrushData *data = gso->customdata;
893         size_t snum;
894         
895         /* Compute the amount of movement to apply (overwrites dvec) */
896         gp_brush_grab_calc_dvec(gso);
897         
898         /* For each of the stored strokes, apply the offset to each point */
899         /* NOTE: Again this assumes that in the 3D view, we only have 3d space and not screenspace strokes... */
900         for (snum = 0; snum < data->totitems; snum++) {
901                 bGPDstroke *gps = data->new_strokes[snum];
902                 bGPDspoint *pt;
903                 int i;
904                 
905                 for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) {
906                         if (gso->brush->flag & GP_EDITBRUSH_FLAG_USE_FALLOFF) {
907                                 /* "Smudge" Effect when falloff is enabled */
908                                 float delta[3] = {0.0f};
909                                 int sco[2] = {0};
910                                 float influence;
911                                 
912                                 /* compute influence on point */
913                                 gp_point_to_xy(&gso->gsc, gps, pt, &sco[0], &sco[1]);
914                                 influence = gp_brush_influence_calc(gso, gso->brush->size, sco);
915                                 
916                                 /* adjust the amount of displacement to apply */
917                                 mul_v3_v3fl(delta, gso->dvec, influence);
918                                 
919                                 /* apply */
920                                 add_v3_v3(&pt->x, delta);
921                         }
922                         else {
923                                 /* Just apply the offset - All points move perfectly in sync with the cursor */
924                                 add_v3_v3(&pt->x, gso->dvec);
925                         }
926                 }
927         }
928 }
929
930 /* Entrypoint for applying "clone" brush */
931 static bool gpsculpt_brush_apply_clone(bContext *C, tGP_BrushEditData *gso)
932 {
933         /* Which "mode" are we operating in? */
934         if (gso->first) {
935                 /* Create initial clones */
936                 gp_brush_clone_add(C, gso);
937         }
938         else {
939                 /* Stamp or Continous Mode */
940                 if (1 /*gso->brush->mode == GP_EDITBRUSH_CLONE_MODE_STAMP*/) {
941                         /* Stamp - Proceed to translate the newly added strokes */
942                         gp_brush_clone_adjust(gso);
943                 }
944                 else {
945                         /* Continuous - Just keep pasting everytime we move */
946                         /* TODO: The spacing of repeat should be controlled using a "stepsize" or similar property? */
947                         gp_brush_clone_add(C, gso);
948                 }
949         }
950         
951         return true;
952 }
953
954 /* ************************************************ */
955 /* Cursor drawing */
956
957 /* Helper callback for drawing the cursor itself */
958 static void gp_brush_drawcursor(bContext *C, int x, int y, void *UNUSED(customdata))
959 {
960         GP_EditBrush_Data *brush = gpsculpt_get_brush(CTX_data_scene(C));
961         
962         if (brush) {
963                 glPushMatrix();
964                 
965                 glTranslatef((float)x, (float)y, 0.0f);
966                 
967                 glEnable(GL_LINE_SMOOTH);
968                 glEnable(GL_BLEND);
969                 
970                 /* Inner Ring: Light color for action of the brush */
971                 /* TODO: toggle between add and remove? */
972                 glColor4ub(255, 255, 255, 200);
973                 glutil_draw_lined_arc(0.0, M_PI * 2.0, brush->size, 40);
974                 
975                 /* Outer Ring: Dark color for contrast on light backgrounds (e.g. gray on white) */
976                 glColor3ub(30, 30, 30);
977                 glutil_draw_lined_arc(0.0, M_PI * 2.0, brush->size + 1, 40);
978                 
979                 glDisable(GL_BLEND);
980                 glDisable(GL_LINE_SMOOTH);
981                 
982                 glPopMatrix();
983         }
984 }
985
986 /* Turn brush cursor in on/off */
987 static void gpencil_toggle_brush_cursor(bContext *C, bool enable)
988 {
989         GP_BrushEdit_Settings *gset = gpsculpt_get_settings(CTX_data_scene(C));
990         
991         if (gset->paintcursor && !enable) {
992                 /* clear cursor */
993                 WM_paint_cursor_end(CTX_wm_manager(C), gset->paintcursor);
994                 gset->paintcursor = NULL;
995         }
996         else if (enable) {
997                 /* enable cursor */
998                 gset->paintcursor = WM_paint_cursor_activate(CTX_wm_manager(C), 
999                                                              NULL, 
1000                                                              gp_brush_drawcursor, NULL);
1001         }
1002 }
1003
1004
1005 /* ************************************************ */
1006 /* Header Info for GPencil Sculpt */
1007
1008 static void gpsculpt_brush_header_set(bContext *C, tGP_BrushEditData *gso)
1009 {
1010         const char *brush_name = NULL;
1011         char str[UI_MAX_DRAW_STR] = "";
1012         
1013         RNA_enum_name(rna_enum_gpencil_sculpt_brush_items, gso->brush_type, &brush_name);
1014         
1015         BLI_snprintf(str, sizeof(str),
1016                      IFACE_("GPencil Sculpt: %s Stroke  | LMB to paint | RMB/Escape to Exit"
1017                             " | Ctrl to Invert Action | Wheel Up/Down for Size "
1018                             " | Shift-Wheel Up/Down for Strength"),
1019                      (brush_name) ? brush_name : "<?>");
1020         
1021         ED_area_headerprint(CTX_wm_area(C), str);
1022 }
1023
1024 /* ************************************************ */
1025 /* Grease Pencil Sculpting Operator */
1026
1027 /* Init/Exit ----------------------------------------------- */
1028
1029 static bool gpsculpt_brush_init(bContext *C, wmOperator *op)
1030 {
1031         Scene *scene = CTX_data_scene(C);
1032         tGP_BrushEditData *gso;
1033         
1034         /* setup operator data */
1035         gso = MEM_callocN(sizeof(tGP_BrushEditData), "tGP_BrushEditData");
1036         op->customdata = gso;
1037         
1038         /* store state */
1039         gso->settings = gpsculpt_get_settings(scene);
1040         gso->brush = gpsculpt_get_brush(scene);
1041         
1042         gso->brush_type = gso->settings->brushtype;
1043         
1044         
1045         gso->is_painting = false;
1046         gso->first = true;
1047         
1048         gso->gpd = ED_gpencil_data_get_active(C);
1049         gso->cfra = INT_MAX; /* NOTE: So that first stroke will get handled in init_stroke() */
1050         
1051         gso->scene = scene;
1052         
1053         gso->sa = CTX_wm_area(C);
1054         gso->ar = CTX_wm_region(C);
1055         
1056         /* initialise custom data for brushes */
1057         switch (gso->brush_type) {
1058                 case GP_EDITBRUSH_TYPE_CLONE:
1059                 {
1060                         bGPDstroke *gps;
1061                         bool found = false;
1062                         
1063                         /* check that there are some usable strokes in the buffer */
1064                         for (gps = gp_strokes_copypastebuf.first; gps; gps = gps->next) {
1065                                 if (ED_gpencil_stroke_can_use(C, gps)) {
1066                                         found = true;
1067                                         break;
1068                                 }
1069                         }
1070                         
1071                         if (found == false) {
1072                                 /* STOP HERE! Nothing to paste! */
1073                                 BKE_report(op->reports, RPT_ERROR, 
1074                                            "Copy some strokes to the clipboard before using the Clone brush to paste copies of them");
1075                                            
1076                                 MEM_freeN(gso);
1077                                 op->customdata = NULL;
1078                                 return false;
1079                         }
1080                         else {
1081                                 /* initialise customdata */
1082                                 gp_brush_clone_init(C, gso);
1083                         }
1084                         break;
1085                 }
1086                 
1087                 case GP_EDITBRUSH_TYPE_GRAB:
1088                 {
1089                         /* initialise the cache needed for this brush */
1090                         gso->stroke_customdata = BLI_ghash_ptr_new("GP Grab Brush - Strokes Hash");
1091                         break;
1092                 }
1093                         
1094                 /* Others - No customdata needed */
1095                 default:
1096                         break;
1097         }
1098         
1099         
1100         /* setup space conversions */
1101         gp_point_conversion_init(C, &gso->gsc);
1102         
1103         /* update header */
1104         gpsculpt_brush_header_set(C, gso);
1105         
1106         /* setup cursor drawing */
1107         WM_cursor_modal_set(CTX_wm_window(C), BC_CROSSCURSOR);
1108         gpencil_toggle_brush_cursor(C, true);
1109         
1110         return true;
1111 }
1112
1113 static void gpsculpt_brush_exit(bContext *C, wmOperator *op)
1114 {
1115         tGP_BrushEditData *gso = op->customdata;
1116         wmWindow *win = CTX_wm_window(C);
1117         
1118         /* free brush-specific data */
1119         switch (gso->brush_type) {
1120                 case GP_EDITBRUSH_TYPE_GRAB:
1121                 {
1122                         /* Free per-stroke customdata
1123                          * - Keys don't need to be freed, as those are the strokes
1124                          * - Values assigned to those keys do, as they are custom structs
1125                          */
1126                         BLI_ghash_free(gso->stroke_customdata, NULL, gp_brush_grab_stroke_free);
1127                         break;
1128                 }
1129                 
1130                 case GP_EDITBRUSH_TYPE_CLONE:
1131                 {
1132                         /* Free customdata */
1133                         gp_brush_clone_free(gso);
1134                         break;
1135                 }
1136                 
1137                 default:
1138                         break;
1139         }
1140         
1141         /* unregister timer (only used for realtime) */
1142         if (gso->timer) {
1143                 WM_event_remove_timer(CTX_wm_manager(C), win, gso->timer);
1144         }
1145
1146         /* disable cursor and headerprints */
1147         ED_area_headerprint(CTX_wm_area(C), NULL);
1148         WM_cursor_modal_restore(win);
1149         gpencil_toggle_brush_cursor(C, false);
1150         
1151         /* free operator data */
1152         MEM_freeN(gso);
1153         op->customdata = NULL;
1154 }
1155
1156 /* poll callback for stroke sculpting operator(s) */
1157 static int gpsculpt_brush_poll(bContext *C)
1158 {
1159         /* NOTE: this is a bit slower, but is the most accurate... */
1160         return CTX_DATA_COUNT(C, editable_gpencil_strokes) != 0;
1161 }
1162
1163 /* Init Sculpt Stroke ---------------------------------- */
1164
1165 static void gpsculpt_brush_init_stroke(tGP_BrushEditData *gso)
1166 {
1167         Scene *scene = gso->scene;
1168         bGPdata *gpd = gso->gpd;
1169         bGPDlayer *gpl;
1170         int cfra = CFRA;
1171         
1172         /* only try to add a new frame if this is the first stroke, or the frame has changed */
1173         if ((gpd == NULL) || (cfra == gso->cfra))
1174                 return;
1175         
1176         /* go through each layer, and ensure that we've got a valid frame to use */
1177         for (gpl = gpd->layers.first; gpl; gpl = gpl->next) {
1178                 /* only editable and visible layers are considered */
1179                 if (gpencil_layer_is_editable(gpl) && (gpl->actframe != NULL)) {
1180                         bGPDframe *gpf = gpl->actframe;
1181                         
1182                         /* Make a new frame to work on if the layer's frame and the current scene frame don't match up 
1183                          * - This is useful when animating as it saves that "uh-oh" moment when you realize you've
1184                          *   spent too much time editing the wrong frame...
1185                          */
1186                         // XXX: should this be allowed when framelock is enabled?
1187                         if (gpf->framenum != cfra) {
1188                                 gpencil_frame_addcopy(gpl, cfra);
1189                         }
1190                 }
1191         }
1192         
1193         /* save off new current frame, so that next update works fine */
1194         gso->cfra = cfra;
1195 }
1196
1197 /* Apply ----------------------------------------------- */
1198
1199 /* Apply brush operation to points in this stroke */
1200 static bool gpsculpt_brush_do_stroke(
1201         tGP_BrushEditData *gso, bGPDstroke *gps, bool parented,
1202         float diff_mat[4][4], GP_BrushApplyCb apply)
1203 {
1204         GP_SpaceConversion *gsc = &gso->gsc;
1205         rcti *rect = &gso->brush_rect;
1206         const int radius = gso->brush->size;
1207         
1208         bGPDspoint *pt1, *pt2;
1209         int pc1[2] = {0};
1210         int pc2[2] = {0};
1211         int i;
1212         bool include_last = false;
1213         bool changed = false;
1214
1215         if (gps->totpoints == 1) {
1216                 if (!parented) {
1217                         gp_point_to_xy(gsc, gps, gps->points, &pc1[0], &pc1[1]);
1218                 }
1219                 else {
1220                         bGPDspoint pt_temp;
1221                         gp_point_to_parent_space(gps->points, diff_mat, &pt_temp);
1222                         gp_point_to_xy(gsc, gps, &pt_temp, &pc1[0], &pc1[1]);
1223                 }
1224                 
1225                 /* do boundbox check first */
1226                 if ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) {
1227                         /* only check if point is inside */
1228                         if (len_v2v2_int(gso->mval, pc1) <= radius) {
1229                                 /* apply operation to this point */
1230                                 changed = apply(gso, gps, 0, radius, pc1);
1231                         }
1232                 }
1233         }
1234         else {
1235                 /* Loop over the points in the stroke, checking for intersections 
1236                  *  - an intersection means that we touched the stroke
1237                  */
1238                 for (i = 0; (i + 1) < gps->totpoints; i++) {
1239                         /* Get points to work with */
1240                         pt1 = gps->points + i;
1241                         pt2 = gps->points + i + 1;
1242                         
1243                         /* Skip if neither one is selected (and we are only allowed to edit/consider selected points) */
1244                         if (gso->settings->flag & GP_BRUSHEDIT_FLAG_SELECT_MASK) {
1245                                 if (!(pt1->flag & GP_SPOINT_SELECT) && !(pt2->flag & GP_SPOINT_SELECT)) {
1246                                         include_last = false;
1247                                         continue;
1248                                 }
1249                         }
1250                         if (!parented) {
1251                                 gp_point_to_xy(gsc, gps, pt1, &pc1[0], &pc1[1]);
1252                                 gp_point_to_xy(gsc, gps, pt2, &pc2[0], &pc2[1]);
1253                         }
1254                         else {
1255                                 bGPDspoint npt;
1256                                 gp_point_to_parent_space(pt1, diff_mat, &npt);
1257                                 gp_point_to_xy(gsc, gps, &npt, &pc1[0], &pc1[1]);
1258
1259                                 gp_point_to_parent_space(pt2, diff_mat, &npt);
1260                                 gp_point_to_xy(gsc, gps, &npt, &pc2[0], &pc2[1]);
1261                         }
1262
1263
1264                         /* Check that point segment of the boundbox of the selection stroke */
1265                         if (((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) ||
1266                             ((!ELEM(V2D_IS_CLIPPED, pc2[0], pc2[1])) && BLI_rcti_isect_pt(rect, pc2[0], pc2[1])))
1267                         {
1268                                 /* Check if point segment of stroke had anything to do with
1269                                  * brush region  (either within stroke painted, or on its lines)
1270                                  *  - this assumes that linewidth is irrelevant
1271                                  */
1272                                 if (gp_stroke_inside_circle(gso->mval, gso->mval_prev, radius, pc1[0], pc1[1], pc2[0], pc2[1])) {
1273                                         /* Apply operation to these points */
1274                                         bool ok = false;
1275                                         
1276                                         /* To each point individually... */
1277                                         ok = apply(gso, gps, i, radius, pc1);
1278                                         
1279                                         /* Only do the second point if this is the last segment,
1280                                          * and it is unlikely that the point will get handled
1281                                          * otherwise. 
1282                                          * 
1283                                          * NOTE: There is a small risk here that the second point wasn't really
1284                                          *       actually in-range. In that case, it only got in because
1285                                          *       the line linking the points was!
1286                                          */
1287                                         if (i + 1 == gps->totpoints - 1) {
1288                                                 ok |= apply(gso, gps, i + 1, radius, pc2);
1289                                                 include_last = false;
1290                                         }
1291                                         else {
1292                                                 include_last = true;
1293                                         }
1294                                         
1295                                         changed |= ok;
1296                                 }
1297                                 else if (include_last) {
1298                                         /* This case is for cases where for whatever reason the second vert (1st here) doesn't get included
1299                                          * because the whole edge isn't in bounds, but it would've qualified since it did with the
1300                                          * previous step (but wasn't added then, to avoid double-ups) 
1301                                          */
1302                                         changed |= apply(gso, gps, i, radius, pc1);
1303                                         include_last = false;
1304                                 }
1305                         }
1306                 }
1307         }
1308         
1309         return changed;
1310 }
1311
1312 /* Perform two-pass brushes which modify the existing strokes */
1313 static bool gpsculpt_brush_apply_standard(bContext *C, tGP_BrushEditData *gso)
1314 {
1315         bool changed = false;
1316         
1317         /* Calculate brush-specific data which applies equally to all points */
1318         switch (gso->brush_type) {
1319                 case GP_EDITBRUSH_TYPE_GRAB: /* Grab points */
1320                 case GP_EDITBRUSH_TYPE_PUSH: /* Push points */
1321                 {
1322                         /* calculate amount of displacement to apply */
1323                         gp_brush_grab_calc_dvec(gso);
1324                         break;
1325                 }
1326                 
1327                 case GP_EDITBRUSH_TYPE_PINCH: /* Pinch points */
1328                 case GP_EDITBRUSH_TYPE_TWIST: /* Twist points around midpoint */
1329                 {
1330                         /* calculate midpoint of the brush (in data space) */
1331                         gp_brush_calc_midpoint(gso);
1332                         break;
1333                 }
1334                 
1335                 case GP_EDITBRUSH_TYPE_RANDOMIZE: /* Random jitter */
1336                 {
1337                         /* compute the displacement vector for the cursor (in data space) */
1338                         gp_brush_grab_calc_dvec(gso);
1339                         break;
1340                 }
1341                 
1342                 default:
1343                         break;
1344         }
1345         
1346         
1347         /* Find visible strokes, and perform operations on those if hit */
1348         float diff_mat[4][4];
1349         bool parented = false;
1350
1351         CTX_DATA_BEGIN(C, bGPDlayer *, gpl, editable_gpencil_layers)
1352         {
1353                 /* calculate difference matrix if parent object */
1354                 if (gpl->parent != NULL) {
1355                         ED_gpencil_parent_location(gpl, diff_mat);
1356                         parented = true;
1357                 }
1358                 else {
1359                         parented = false;
1360                 }
1361
1362                 bGPDframe *gpf = gpl->actframe;
1363                 bGPDstroke *gps;
1364                 for (gps = gpf->strokes.first; gps; gps = gps->next) {
1365                         /* skip strokes that are invalid for current view */
1366                         if (ED_gpencil_stroke_can_use(C, gps) == false)
1367                                 continue;
1368                         /* check if the color is editable */
1369                         if (ED_gpencil_stroke_color_use(gpl, gps) == false) {
1370                                 continue;
1371                         }
1372
1373                         switch (gso->brush_type) {
1374                                 case GP_EDITBRUSH_TYPE_SMOOTH: /* Smooth strokes */
1375                                 {
1376                                         changed |= gpsculpt_brush_do_stroke(gso, gps, parented, diff_mat, gp_brush_smooth_apply);
1377                                         break;
1378                                 }
1379
1380                                 case GP_EDITBRUSH_TYPE_THICKNESS: /* Adjust stroke thickness */
1381                                 {
1382                                         changed |= gpsculpt_brush_do_stroke(gso, gps, parented, diff_mat, gp_brush_thickness_apply);
1383                                         break;
1384                                 }
1385
1386                                 case GP_EDITBRUSH_TYPE_STRENGTH: /* Adjust stroke color strength */
1387                                 {
1388                                         changed |= gpsculpt_brush_do_stroke(gso, gps, parented, diff_mat, gp_brush_strength_apply);
1389                                         break;
1390                                 }
1391
1392                                 case GP_EDITBRUSH_TYPE_GRAB: /* Grab points */
1393                                 {
1394                                         if (gso->first) {
1395                                                 /* First time this brush stroke is being applied:
1396                                                  * 1) Prepare data buffers (init/clear) for this stroke
1397                                                  * 2) Use the points now under the cursor
1398                                                  */
1399                                                 gp_brush_grab_stroke_init(gso, gps);
1400                                                 changed |= gpsculpt_brush_do_stroke(gso, gps, parented, diff_mat, gp_brush_grab_store_points);
1401                                         }
1402                                         else {
1403                                                 /* Apply effect to the stored points */
1404                                                 gp_brush_grab_apply_cached(gso, gps, parented, diff_mat);
1405                                                 changed |= true;
1406                                         }
1407                                         break;
1408                                 }
1409
1410                                 case GP_EDITBRUSH_TYPE_PUSH: /* Push points */
1411                                 {
1412                                         changed |= gpsculpt_brush_do_stroke(gso, gps, parented, diff_mat, gp_brush_push_apply);
1413                                         break;
1414                                 }
1415
1416                                 case GP_EDITBRUSH_TYPE_PINCH: /* Pinch points */
1417                                 {
1418                                         changed |= gpsculpt_brush_do_stroke(gso, gps, parented, diff_mat, gp_brush_pinch_apply);
1419                                         break;
1420                                 }
1421
1422                                 case GP_EDITBRUSH_TYPE_TWIST: /* Twist points around midpoint */
1423                                 {
1424                                         changed |= gpsculpt_brush_do_stroke(gso, gps, parented, diff_mat, gp_brush_twist_apply);
1425                                         break;
1426                                 }
1427
1428                                 case GP_EDITBRUSH_TYPE_RANDOMIZE: /* Apply jitter */
1429                                 {
1430                                         changed |= gpsculpt_brush_do_stroke(gso, gps, parented, diff_mat, gp_brush_randomize_apply);
1431                                         break;
1432                                 }
1433
1434                                 default:
1435                                         printf("ERROR: Unknown type of GPencil Sculpt brush - %u\n", gso->brush_type);
1436                                         break;
1437                         }
1438                         /* Triangulation must be calculated if changed */
1439                         if (changed) {
1440                                 gps->flag |= GP_STROKE_RECALC_CACHES;
1441                                 gps->tot_triangles = 0;
1442                         }
1443                 }
1444         }
1445         CTX_DATA_END;
1446
1447         return changed;
1448 }
1449
1450 /* Calculate settings for applying brush */
1451 static void gpsculpt_brush_apply(bContext *C, wmOperator *op, PointerRNA *itemptr)
1452 {
1453         tGP_BrushEditData *gso = op->customdata;
1454         const int radius = gso->brush->size;
1455         float mousef[2];
1456         int mouse[2];
1457         bool changed = false;
1458         
1459         /* Get latest mouse coordinates */
1460         RNA_float_get_array(itemptr, "mouse", mousef);
1461         gso->mval[0] = mouse[0] = (int)(mousef[0]);
1462         gso->mval[1] = mouse[1] = (int)(mousef[1]);
1463         
1464         gso->pressure = RNA_float_get(itemptr, "pressure");
1465         
1466         if (RNA_boolean_get(itemptr, "pen_flip"))
1467                 gso->flag |= GP_EDITBRUSH_FLAG_INVERT;
1468         else
1469                 gso->flag &= ~GP_EDITBRUSH_FLAG_INVERT;
1470         
1471         
1472         /* Store coordinates as reference, if operator just started running */
1473         if (gso->first) {
1474                 gso->mval_prev[0]  = gso->mval[0];
1475                 gso->mval_prev[1]  = gso->mval[1];
1476                 gso->pressure_prev = gso->pressure;
1477         }
1478         
1479         /* Update brush_rect, so that it represents the bounding rectangle of brush */
1480         gso->brush_rect.xmin = mouse[0] - radius;
1481         gso->brush_rect.ymin = mouse[1] - radius;
1482         gso->brush_rect.xmax = mouse[0] + radius;
1483         gso->brush_rect.ymax = mouse[1] + radius;
1484         
1485         
1486         /* Apply brush */
1487         if (gso->brush_type == GP_EDITBRUSH_TYPE_CLONE) {
1488                 changed = gpsculpt_brush_apply_clone(C, gso);
1489         }
1490         else {
1491                 changed = gpsculpt_brush_apply_standard(C, gso);
1492         }
1493         
1494         
1495         /* Updates */
1496         if (changed) {
1497                 WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
1498         }
1499         
1500         /* Store values for next step */
1501         gso->mval_prev[0]  = gso->mval[0];
1502         gso->mval_prev[1]  = gso->mval[1];
1503         gso->pressure_prev = gso->pressure;
1504         gso->first = false;
1505 }
1506
1507 /* Running --------------------------------------------- */
1508
1509 /* helper - a record stroke, and apply paint event */
1510 static void gpsculpt_brush_apply_event(bContext *C, wmOperator *op, const wmEvent *event)
1511 {
1512         tGP_BrushEditData *gso = op->customdata;
1513         PointerRNA itemptr;
1514         float mouse[2];
1515         int tablet = 0;
1516         
1517         mouse[0] = event->mval[0] + 1;
1518         mouse[1] = event->mval[1] + 1;
1519         
1520         /* fill in stroke */
1521         RNA_collection_add(op->ptr, "stroke", &itemptr);
1522         
1523         RNA_float_set_array(&itemptr, "mouse", mouse);
1524         RNA_boolean_set(&itemptr, "pen_flip", event->ctrl != false);
1525         RNA_boolean_set(&itemptr, "is_start", gso->first);
1526         
1527         /* handle pressure sensitivity (which is supplied by tablets) */
1528         if (event->tablet_data) {
1529                 const wmTabletData *wmtab = event->tablet_data;
1530                 float pressure = wmtab->Pressure;
1531                 
1532                 tablet = (wmtab->Active != EVT_TABLET_NONE);
1533                 
1534                 /* special exception here for too high pressure values on first touch in
1535                  * windows for some tablets: clamp the values to be sane
1536                  */
1537                 if (tablet && (pressure >= 0.99f)) {
1538                         pressure = 1.0f;
1539                 }
1540                 RNA_float_set(&itemptr, "pressure", pressure);
1541         }
1542         else {
1543                 RNA_float_set(&itemptr, "pressure", 1.0f);
1544         }
1545         
1546         /* apply */
1547         gpsculpt_brush_apply(C, op, &itemptr);
1548 }
1549
1550 /* reapply */
1551 static int gpsculpt_brush_exec(bContext *C, wmOperator *op)
1552 {
1553         if (!gpsculpt_brush_init(C, op))
1554                 return OPERATOR_CANCELLED;
1555         
1556         RNA_BEGIN(op->ptr, itemptr, "stroke") 
1557         {
1558                 gpsculpt_brush_apply(C, op, &itemptr);
1559         }
1560         RNA_END;
1561         
1562         gpsculpt_brush_exit(C, op);
1563         
1564         return OPERATOR_FINISHED;
1565 }
1566
1567
1568 /* start modal painting */
1569 static int gpsculpt_brush_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1570 {
1571         tGP_BrushEditData *gso = NULL;
1572         const bool is_modal = RNA_boolean_get(op->ptr, "wait_for_input");
1573         bool needs_timer = false;
1574         float brush_rate = 0.0f;
1575         
1576         /* init painting data */
1577         if (!gpsculpt_brush_init(C, op))
1578                 return OPERATOR_CANCELLED;
1579         
1580         gso = op->customdata;
1581         
1582         /* initialise type-specific data (used for the entire session) */
1583         switch (gso->brush_type) {
1584                 /* Brushes requiring timer... */
1585                 case GP_EDITBRUSH_TYPE_THICKNESS:
1586                         brush_rate = 0.01f; // XXX: hardcoded
1587                         needs_timer = true;
1588                         break;
1589                         
1590                 case GP_EDITBRUSH_TYPE_STRENGTH:
1591                         brush_rate = 0.01f; // XXX: hardcoded
1592                         needs_timer = true;
1593                         break;
1594
1595                 case GP_EDITBRUSH_TYPE_PINCH:
1596                         brush_rate = 0.001f; // XXX: hardcoded
1597                         needs_timer = true;
1598                         break;
1599                 
1600                 case GP_EDITBRUSH_TYPE_TWIST:
1601                         brush_rate = 0.01f; // XXX: hardcoded
1602                         needs_timer = true;
1603                         break;
1604                         
1605                 default:
1606                         break;
1607         }
1608         
1609         /* register timer for increasing influence by hovering over an area */
1610         if (needs_timer) {
1611                 gso->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, brush_rate);
1612         }
1613         
1614         /* register modal handler */
1615         WM_event_add_modal_handler(C, op);
1616         
1617         /* start drawing immediately? */
1618         if (is_modal == false) {
1619                 ARegion *ar = CTX_wm_region(C);
1620                 
1621                 /* ensure that we'll have a new frame to draw on */
1622                 gpsculpt_brush_init_stroke(gso);
1623                 
1624                 /* apply first dab... */
1625                 gso->is_painting = true;
1626                 gpsculpt_brush_apply_event(C, op, event);
1627                 
1628                 /* redraw view with feedback */
1629                 ED_region_tag_redraw(ar);
1630         }
1631         
1632         return OPERATOR_RUNNING_MODAL;
1633 }
1634
1635 /* painting - handle events */
1636 static int gpsculpt_brush_modal(bContext *C, wmOperator *op, const wmEvent *event)
1637 {
1638         tGP_BrushEditData *gso = op->customdata;
1639         const bool is_modal = RNA_boolean_get(op->ptr, "wait_for_input");
1640         bool redraw_region = false;
1641         bool redraw_toolsettings = false;
1642         
1643         /* The operator can be in 2 states: Painting and Idling */
1644         if (gso->is_painting) {
1645                 /* Painting  */
1646                 switch (event->type) {
1647                         /* Mouse Move = Apply somewhere else */
1648                         case MOUSEMOVE:
1649                         case INBETWEEN_MOUSEMOVE:
1650                                 /* apply brush effect at new position */
1651                                 gpsculpt_brush_apply_event(C, op, event);
1652                                 
1653                                 /* force redraw, so that the cursor will at least be valid */
1654                                 redraw_region = true;
1655                                 break;
1656                         
1657                         /* Timer Tick - Only if this was our own timer */
1658                         case TIMER:
1659                                 if (event->customdata == gso->timer) {
1660                                         gso->timerTick = true;
1661                                         gpsculpt_brush_apply_event(C, op, event);
1662                                         gso->timerTick = false;
1663                                 }
1664                                 break;
1665                                 
1666                         /* Adjust brush settings */
1667                         /* FIXME: Step increments and modifier keys are hardcoded here! */
1668                         case WHEELUPMOUSE:
1669                         case PADPLUSKEY:
1670                                 if (event->shift) {
1671                                         /* increase strength */
1672                                         gso->brush->strength += 0.05f;
1673                                         CLAMP_MAX(gso->brush->strength, 1.0f);
1674                                 }
1675                                 else {
1676                                         /* increase brush size */
1677                                         gso->brush->size += 3;
1678                                         CLAMP_MAX(gso->brush->size, 300);
1679                                 }
1680                                 
1681                                 redraw_region = true;
1682                                 redraw_toolsettings = true;
1683                                 break;
1684                         
1685                         case WHEELDOWNMOUSE: 
1686                         case PADMINUS:
1687                                 if (event->shift) {
1688                                         /* decrease strength */
1689                                         gso->brush->strength -= 0.05f;
1690                                         CLAMP_MIN(gso->brush->strength, 0.0f);
1691                                 }
1692                                 else {
1693                                         /* decrease brush size */
1694                                         gso->brush->size -= 3;
1695                                         CLAMP_MIN(gso->brush->size, 1);
1696                                 }
1697                                 
1698                                 redraw_region = true;
1699                                 redraw_toolsettings = true;
1700                                 break;
1701                         
1702                         /* Painting mbut release = Stop painting (back to idle) */
1703                         case LEFTMOUSE:
1704                                 //BLI_assert(event->val == KM_RELEASE);
1705                                 if (is_modal) {
1706                                         /* go back to idling... */
1707                                         gso->is_painting = false;
1708                                 }
1709                                 else {
1710                                         /* end sculpt session, since we're not modal */
1711                                         gso->is_painting = false;
1712                                         
1713                                         gpsculpt_brush_exit(C, op);
1714                                         return OPERATOR_FINISHED;
1715                                 }
1716                                 break;
1717                                 
1718                         /* Abort painting if any of the usual things are tried */
1719                         case MIDDLEMOUSE:
1720                         case RIGHTMOUSE:
1721                         case ESCKEY:
1722                                 gpsculpt_brush_exit(C, op);
1723                                 return OPERATOR_FINISHED;
1724                 }
1725         }
1726         else {
1727                 /* Idling */
1728                 BLI_assert(is_modal == true);
1729                 
1730                 switch (event->type) {
1731                         /* Painting mbut press = Start painting (switch to painting state) */
1732                         case LEFTMOUSE:
1733                                 /* do initial "click" apply */
1734                                 gso->is_painting = true;
1735                                 gso->first = true;
1736                                 
1737                                 gpsculpt_brush_init_stroke(gso);
1738                                 gpsculpt_brush_apply_event(C, op, event);
1739                                 break;
1740                                 
1741                         /* Exit modal operator, based on the "standard" ops */
1742                         case RIGHTMOUSE:
1743                         case ESCKEY:
1744                                 gpsculpt_brush_exit(C, op);
1745                                 return OPERATOR_FINISHED;
1746                                 
1747                         /* MMB is often used for view manipulations */
1748                         case MIDDLEMOUSE:
1749                                 return OPERATOR_PASS_THROUGH;
1750                         
1751                         /* Mouse movements should update the brush cursor - Just redraw the active region */
1752                         case MOUSEMOVE:
1753                         case INBETWEEN_MOUSEMOVE:
1754                                 redraw_region = true;
1755                                 break;
1756                         
1757                         /* Adjust brush settings */
1758                         /* FIXME: Step increments and modifier keys are hardcoded here! */
1759                         case WHEELUPMOUSE:
1760                         case PADPLUSKEY:
1761                                 if (event->shift) {
1762                                         /* increase strength */
1763                                         gso->brush->strength += 0.05f;
1764                                         CLAMP_MAX(gso->brush->strength, 1.0f);
1765                                 }
1766                                 else {
1767                                         /* increase brush size */
1768                                         gso->brush->size += 3;
1769                                         CLAMP_MAX(gso->brush->size, 300);
1770                                 }
1771                                 
1772                                 redraw_region = true;
1773                                 redraw_toolsettings = true;
1774                                 break;
1775                         
1776                         case WHEELDOWNMOUSE: 
1777                         case PADMINUS:
1778                                 if (event->shift) {
1779                                         /* decrease strength */
1780                                         gso->brush->strength -= 0.05f;
1781                                         CLAMP_MIN(gso->brush->strength, 0.0f);
1782                                 }
1783                                 else {
1784                                         /* decrease brush size */
1785                                         gso->brush->size -= 3;
1786                                         CLAMP_MIN(gso->brush->size, 1);
1787                                 }
1788                                 
1789                                 redraw_region = true;
1790                                 redraw_toolsettings = true;
1791                                 break;
1792                         
1793                         /* Change Frame - Allowed */
1794                         case LEFTARROWKEY:
1795                         case RIGHTARROWKEY:
1796                         case UPARROWKEY:
1797                         case DOWNARROWKEY:
1798                                 return OPERATOR_PASS_THROUGH;
1799                         
1800                         /* Unhandled event */
1801                         default:
1802                                 break;
1803                 }
1804         }
1805         
1806         /* Redraw region? */
1807         if (redraw_region) {
1808                 ARegion *ar = CTX_wm_region(C);
1809                 ED_region_tag_redraw(ar);
1810         }
1811         
1812         /* Redraw toolsettings (brush settings)? */
1813         if (redraw_toolsettings) {
1814                 WM_event_add_notifier(C, NC_SCENE | ND_TOOLSETTINGS, NULL);
1815         }
1816         
1817         return OPERATOR_RUNNING_MODAL;
1818 }
1819
1820
1821 /* Operator --------------------------------------------- */
1822
1823 void GPENCIL_OT_brush_paint(wmOperatorType *ot)
1824 {
1825         PropertyRNA *prop;
1826         
1827         /* identifiers */
1828         ot->name = "Stroke Sculpt";
1829         ot->idname = "GPENCIL_OT_brush_paint";
1830         ot->description = "Apply tweaks to strokes by painting over the strokes"; // XXX
1831         
1832         /* api callbacks */
1833         ot->exec = gpsculpt_brush_exec;
1834         ot->invoke = gpsculpt_brush_invoke;
1835         ot->modal = gpsculpt_brush_modal;
1836         ot->cancel = gpsculpt_brush_exit;
1837         ot->poll = gpsculpt_brush_poll;
1838
1839         /* flags */
1840         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
1841
1842         /* properties */
1843         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
1844         
1845         prop = RNA_def_boolean(ot->srna, "wait_for_input", true, "Wait for Input",
1846                                "Enter a mini 'sculpt-mode' if enabled, otherwise, exit after drawing a single stroke");
1847         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1848 }
1849
1850 /* ************************************************ */