Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / sculpt_paint / paint_stroke.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) 2009 by Nicholas Bishop
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Jason Wilkins, Tom Musgrove.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  *
27  */
28
29 /** \file blender/editors/sculpt_paint/paint_stroke.c
30  *  \ingroup edsculpt
31  */
32
33
34 #include "MEM_guardedalloc.h"
35
36 #include "BLI_math.h"
37 #include "BLI_utildefines.h"
38 #include "BLI_rand.h"
39 #include "BLI_listbase.h"
40
41 #include "DNA_object_types.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_brush_types.h"
44 #include "DNA_curve_types.h"
45
46 #include "RNA_access.h"
47
48 #include "BKE_context.h"
49 #include "BKE_paint.h"
50 #include "BKE_brush.h"
51 #include "BKE_curve.h"
52 #include "BKE_colortools.h"
53 #include "BKE_image.h"
54 #include "BKE_mesh.h"
55
56 #include "WM_api.h"
57 #include "WM_types.h"
58
59 #include "BIF_gl.h"
60 #include "BIF_glutil.h"
61
62 #include "GPU_immediate.h"
63
64 #include "ED_screen.h"
65 #include "ED_view3d.h"
66
67 #include "IMB_imbuf_types.h"
68
69 #include "paint_intern.h"
70
71 #include <float.h>
72 #include <math.h>
73
74 //#define DEBUG_TIME
75
76 #ifdef DEBUG_TIME
77 #  include "PIL_time_utildefines.h"
78 #endif
79
80 typedef struct PaintSample {
81         float mouse[2];
82         float pressure;
83 } PaintSample;
84
85 typedef struct PaintStroke {
86         void *mode_data;
87         void *stroke_cursor;
88         wmTimer *timer;
89
90         /* Cached values */
91         ViewContext vc;
92         Brush *brush;
93         UnifiedPaintSettings *ups;
94
95         /* used for lines and curves */
96         ListBase line;
97
98         /* Paint stroke can use up to PAINT_MAX_INPUT_SAMPLES prior inputs
99          * to smooth the stroke */
100         PaintSample samples[PAINT_MAX_INPUT_SAMPLES];
101         int num_samples;
102         int cur_sample;
103
104         float last_mouse_position[2];
105         /* space distance covered so far */
106         float stroke_distance;
107
108         /* Set whether any stroke step has yet occurred
109          * e.g. in sculpt mode, stroke doesn't start until cursor
110          * passes over the mesh */
111         bool stroke_started;
112         /* Set when enough motion was found for rake rotation */
113         bool rake_started;
114         /* event that started stroke, for modal() return */
115         int event_type;
116         /* check if stroke variables have been initialized */
117         bool stroke_init;
118         /* check if various brush mapping variables have been initialized */
119         bool brush_init;
120         float initial_mouse[2];
121         /* cached_pressure stores initial pressure for size pressure influence mainly */
122         float cached_size_pressure;
123         /* last pressure will store last pressure value for use in interpolation for space strokes */
124         float last_pressure;
125         int stroke_mode;
126
127         float zoom_2d;
128         int pen_flip;
129         
130         /* line constraint */
131         bool constrain_line;
132         float constrained_pos[2];
133
134         StrokeGetLocation get_location;
135         StrokeTestStart test_start;
136         StrokeUpdateStep update_step;
137         StrokeRedraw redraw;
138         StrokeDone done;
139 } PaintStroke;
140
141 /*** Cursors ***/
142 static void paint_draw_smooth_cursor(bContext *C, int x, int y, void *customdata)
143 {
144         Paint *paint = BKE_paint_get_active_from_context(C);
145         Brush *brush = BKE_paint_brush(paint);
146         PaintStroke *stroke = customdata;
147
148         if (stroke && brush) {
149                 glEnable(GL_LINE_SMOOTH);
150                 glEnable(GL_BLEND);
151
152                 unsigned int pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
153                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
154                 immUniformColor4ubv(paint->paint_cursor_col);
155
156                 immBegin(GWN_PRIM_LINES, 2);
157                 immVertex2f(pos, x, y);
158                 immVertex2f(pos, stroke->last_mouse_position[0], stroke->last_mouse_position[1]);
159                 immEnd();
160
161                 immUnbindProgram();
162
163                 glDisable(GL_BLEND);
164                 glDisable(GL_LINE_SMOOTH);
165         }
166 }
167
168 static void paint_draw_line_cursor(bContext *C, int x, int y, void *customdata)
169 {
170         Paint *paint = BKE_paint_get_active_from_context(C);
171         PaintStroke *stroke = customdata;
172
173         glEnable(GL_LINE_SMOOTH);
174
175         uint shdr_pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
176
177         immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
178
179         float viewport_size[4];
180         glGetFloatv(GL_VIEWPORT, viewport_size);
181         immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
182
183         immUniform1i("num_colors", 2);  /* "advanced" mode */
184         const float alpha = (float)paint->paint_cursor_col[3] / 255.0f;
185         immUniformArray4fv("colors", (float *)(float[][4]){{0.0f, 0.0f, 0.0f, alpha}, {1.0f, 1.0f, 1.0f, alpha}}, 2);
186         immUniform1f("dash_width", 6.0f);
187
188         immBegin(GWN_PRIM_LINES, 2);
189
190         if (stroke->constrain_line) {
191                 immVertex2f(shdr_pos, stroke->last_mouse_position[0], stroke->last_mouse_position[1]);
192                 immVertex2f(shdr_pos, stroke->constrained_pos[0], stroke->constrained_pos[1]);
193         }
194         else {
195                 immVertex2f(shdr_pos, stroke->last_mouse_position[0], stroke->last_mouse_position[1]);
196                 immVertex2f(shdr_pos, x, y);
197         }
198
199         immEnd();
200
201         immUnbindProgram();
202
203         glDisable(GL_LINE_SMOOTH);
204 }
205
206 static bool paint_tool_require_location(Brush *brush, ePaintMode mode)
207 {
208         switch (mode) {
209                 case ePaintSculpt:
210                         if (ELEM(brush->sculpt_tool, SCULPT_TOOL_GRAB, SCULPT_TOOL_ROTATE,
211                                                      SCULPT_TOOL_SNAKE_HOOK, SCULPT_TOOL_THUMB))
212                         {
213                                 return false;
214                         }
215                         else {
216                                 return true;
217                         }
218                 default:
219                         break;
220         }
221
222         return true;
223 }
224
225 /* Initialize the stroke cache variants from operator properties */
226 static bool paint_brush_update(bContext *C,
227                                Brush *brush,
228                                ePaintMode mode,
229                                struct PaintStroke *stroke,
230                                const float mouse_init[2],
231                                float mouse[2], float pressure,
232                                float location[3])
233 {
234         Scene *scene = CTX_data_scene(C);
235         UnifiedPaintSettings *ups = stroke->ups;
236         bool location_sampled = false;
237         bool location_success = false;
238         /* Use to perform all operations except applying the stroke,
239          * needed for operations that require cursor motion (rake). */
240         bool is_dry_run = false;
241         bool do_random = false;
242         bool do_random_mask = false;
243         /* XXX: Use pressure value from first brush step for brushes which don't
244          *      support strokes (grab, thumb). They depends on initial state and
245          *      brush coord/pressure/etc.
246          *      It's more an events design issue, which doesn't split coordinate/pressure/angle
247          *      changing events. We should avoid this after events system re-design */
248         if (!stroke->brush_init) {
249                 copy_v2_v2(stroke->initial_mouse, mouse);
250                 copy_v2_v2(ups->last_rake, mouse);
251                 copy_v2_v2(ups->tex_mouse, mouse);
252                 copy_v2_v2(ups->mask_tex_mouse, mouse);
253                 stroke->cached_size_pressure = pressure;
254
255                 ups->do_linear_conversion = false;
256                 ups->colorspace = NULL;
257
258                 /* check here if color sampling the main brush should do color conversion. This is done here
259                  * to avoid locking up to get the image buffer during sampling */
260                 if (brush->mtex.tex && brush->mtex.tex->type == TEX_IMAGE && brush->mtex.tex->ima) {
261                         ImBuf *tex_ibuf = BKE_image_pool_acquire_ibuf(brush->mtex.tex->ima, &brush->mtex.tex->iuser, NULL);
262                         if (tex_ibuf && tex_ibuf->rect_float == NULL) {
263                                 ups->do_linear_conversion = true;
264                                 ups->colorspace = tex_ibuf->rect_colorspace;
265                         }
266                         BKE_image_pool_release_ibuf(brush->mtex.tex->ima, tex_ibuf, NULL);
267                 }
268
269                 stroke->brush_init = true;
270         }
271
272         if (paint_supports_dynamic_size(brush, mode)) {
273                 copy_v2_v2(ups->tex_mouse, mouse);
274                 copy_v2_v2(ups->mask_tex_mouse, mouse);
275                 stroke->cached_size_pressure = pressure;
276         }
277
278         /* Truly temporary data that isn't stored in properties */
279
280         ups->stroke_active = true;
281         ups->size_pressure_value = stroke->cached_size_pressure;
282
283         ups->pixel_radius = BKE_brush_size_get(scene, brush);
284
285         if (BKE_brush_use_size_pressure(scene, brush) && paint_supports_dynamic_size(brush, mode)) {
286                 ups->pixel_radius *= stroke->cached_size_pressure;
287         }
288
289         if (paint_supports_dynamic_tex_coords(brush, mode)) {
290
291                 if (ELEM(brush->mtex.brush_map_mode,
292                          MTEX_MAP_MODE_VIEW,
293                          MTEX_MAP_MODE_AREA,
294                          MTEX_MAP_MODE_RANDOM))
295                 {
296                         do_random = true;
297                 }
298
299                 if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_RANDOM)
300                         BKE_brush_randomize_texture_coords(ups, false);
301                 else {
302                         copy_v2_v2(ups->tex_mouse, mouse);
303                 }
304
305                 /* take care of mask texture, if any */
306                 if (brush->mask_mtex.tex) {
307
308                         if (ELEM(brush->mask_mtex.brush_map_mode,
309                                  MTEX_MAP_MODE_VIEW,
310                                  MTEX_MAP_MODE_AREA,
311                                  MTEX_MAP_MODE_RANDOM))
312                         {
313                                 do_random_mask = true;
314                         }
315
316                         if (brush->mask_mtex.brush_map_mode == MTEX_MAP_MODE_RANDOM)
317                                 BKE_brush_randomize_texture_coords(ups, true);
318                         else {
319                                 copy_v2_v2(ups->mask_tex_mouse, mouse);
320                         }
321                 }
322         }
323
324
325         if (brush->flag & BRUSH_ANCHORED) {
326                 bool hit = false;
327                 float halfway[2];
328
329                 const float dx = mouse[0] - stroke->initial_mouse[0];
330                 const float dy = mouse[1] - stroke->initial_mouse[1];
331
332                 ups->anchored_size = ups->pixel_radius = sqrtf(dx * dx + dy * dy);
333
334                 ups->brush_rotation = ups->brush_rotation_sec = atan2f(dx, dy) + (float)M_PI;
335
336                 if (brush->flag & BRUSH_EDGE_TO_EDGE) {
337                         halfway[0] = dx * 0.5f + stroke->initial_mouse[0];
338                         halfway[1] = dy * 0.5f + stroke->initial_mouse[1];
339
340                         if (stroke->get_location) {
341                                 if (stroke->get_location(C, location, halfway)) {
342                                         hit = true;
343                                         location_sampled = true;
344                                         location_success = true;
345                                 }
346                                 else if (!paint_tool_require_location(brush, mode)) {
347                                         hit = true;
348                                 }
349                         }
350                         else {
351                                 hit = true;
352                         }
353                 }
354                 if (hit) {
355                         copy_v2_v2(ups->anchored_initial_mouse, halfway);
356                         copy_v2_v2(ups->tex_mouse, halfway);
357                         copy_v2_v2(ups->mask_tex_mouse, halfway);
358                         copy_v2_v2(mouse, halfway);
359                         ups->anchored_size /= 2.0f;
360                         ups->pixel_radius  /= 2.0f;
361                         stroke->stroke_distance = ups->pixel_radius;
362                 }
363                 else {
364                         copy_v2_v2(ups->anchored_initial_mouse, stroke->initial_mouse);
365                         copy_v2_v2(mouse, stroke->initial_mouse);
366                         stroke->stroke_distance = ups->pixel_radius;
367                 }
368                 ups->pixel_radius /= stroke->zoom_2d;
369                 ups->draw_anchored = true;
370         }
371         else {
372                 /* here we are using the initial mouse coordinate because we do not want the rake
373                  * result to depend on jittering */
374                 if (!stroke->brush_init) {
375                         copy_v2_v2(ups->last_rake, mouse_init);
376                 }
377                 /* curve strokes do their own rake calculation */
378                 else if (!(brush->flag & BRUSH_CURVE)) {
379                         if (!paint_calculate_rake_rotation(ups, brush, mouse_init)) {
380                                 /* Not enough motion to define an angle. */
381                                 if (!stroke->rake_started) {
382                                         is_dry_run = true;
383                                 }
384                         }
385                         else {
386                                 stroke->rake_started = true;
387                         }
388                 }
389         }
390
391         if (do_random) {
392                 if (brush->mtex.brush_angle_mode & MTEX_ANGLE_RANDOM) {
393                         ups->brush_rotation += -brush->mtex.random_angle / 2.0f +
394                                                brush->mtex.random_angle * BLI_frand();
395                 }
396         }
397
398         if (do_random_mask) {
399                 if (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RANDOM) {
400                         ups->brush_rotation_sec += -brush->mask_mtex.random_angle / 2.0f +
401                                                    brush->mask_mtex.random_angle * BLI_frand();
402                 }
403         }
404
405         if (!location_sampled) {
406                 if (stroke->get_location) {
407                         if (stroke->get_location(C, location, mouse))
408                                 location_success = true;
409                         else if (!paint_tool_require_location(brush, mode))
410                                 location_success = true;
411                 }
412                 else {
413                         zero_v3(location);
414                         location_success = true;
415                 }
416         }
417
418         return location_success && (is_dry_run == false);
419 }
420
421 static bool paint_stroke_use_jitter(ePaintMode mode, Brush *brush, bool invert)
422 {
423         bool use_jitter = (brush->flag & BRUSH_ABSOLUTE_JITTER) ?
424                 (brush->jitter_absolute != 0) : (brush->jitter != 0);
425
426         /* jitter-ed brush gives weird and unpredictable result for this
427          * kinds of stroke, so manually disable jitter usage (sergey) */
428         use_jitter &= (brush->flag & (BRUSH_DRAG_DOT | BRUSH_ANCHORED)) == 0;
429         use_jitter &= (!ELEM(mode, ePaintTexture2D, ePaintTextureProjective) ||
430                        !(invert && brush->imagepaint_tool == PAINT_TOOL_CLONE));
431
432
433         return use_jitter;
434 }
435
436 /* Put the location of the next stroke dot into the stroke RNA and apply it to the mesh */
437 static void paint_brush_stroke_add_step(bContext *C, wmOperator *op, const float mouse_in[2], float pressure)
438 {
439         Scene *scene = CTX_data_scene(C);
440         Paint *paint = BKE_paint_get_active_from_context(C);
441         ePaintMode mode = BKE_paintmode_get_active_from_context(C);
442         Brush *brush = BKE_paint_brush(paint);
443         PaintStroke *stroke = op->customdata;
444         UnifiedPaintSettings *ups = stroke->ups;
445         float mouse_out[2];
446         PointerRNA itemptr;
447         float location[3];
448
449 /* the following code is adapted from texture paint. It may not be needed but leaving here
450  * just in case for reference (code in texpaint removed as part of refactoring).
451  * It's strange that only texpaint had these guards. */
452 #if 0
453         /* special exception here for too high pressure values on first touch in
454          * windows for some tablets, then we just skip first touch ..  */
455         if (tablet && (pressure >= 0.99f) && ((pop->s.brush->flag & BRUSH_SPACING_PRESSURE) || BKE_brush_use_alpha_pressure(scene, pop->s.brush) || BKE_brush_use_size_pressure(scene, pop->s.brush)))
456                 return;
457
458         /* This can be removed once fixed properly in
459          * BKE_brush_painter_paint(BrushPainter *painter, BrushFunc func, float *pos, double time, float pressure, void *user)
460          * at zero pressure we should do nothing 1/2^12 is 0.0002 which is the sensitivity of the most sensitive pen tablet available */
461         if (tablet && (pressure < 0.0002f) && ((pop->s.brush->flag & BRUSH_SPACING_PRESSURE) || BKE_brush_use_alpha_pressure(scene, pop->s.brush) || BKE_brush_use_size_pressure(scene, pop->s.brush)))
462                 return;
463 #endif
464
465         /* copy last position -before- jittering, or space fill code
466          * will create too many dabs */
467         copy_v2_v2(stroke->last_mouse_position, mouse_in);
468         stroke->last_pressure = pressure;
469
470         if (paint_stroke_use_jitter(mode, brush, stroke->stroke_mode == BRUSH_STROKE_INVERT)) {
471                 float delta[2];
472                 float factor = stroke->zoom_2d;
473
474                 if (brush->flag & BRUSH_JITTER_PRESSURE)
475                         factor *= pressure;
476
477                 BKE_brush_jitter_pos(scene, brush, mouse_in, mouse_out);
478
479                 /* XXX: meh, this is round about because
480                  * BKE_brush_jitter_pos isn't written in the best way to
481                  * be reused here */
482                 if (factor != 1.0f) {
483                         sub_v2_v2v2(delta, mouse_out, mouse_in);
484                         mul_v2_fl(delta, factor);
485                         add_v2_v2v2(mouse_out, mouse_in, delta);
486                 }
487         }
488         else {
489                 copy_v2_v2(mouse_out, mouse_in);
490         }
491
492
493         ups->last_hit = paint_brush_update(C, brush, mode, stroke, mouse_in, mouse_out, pressure, location);
494         copy_v3_v3(ups->last_location, location);
495         if (!ups->last_hit) {
496                 return;
497         }
498
499         /* Add to stroke */
500         RNA_collection_add(op->ptr, "stroke", &itemptr);
501         RNA_float_set(&itemptr, "size", ups->pixel_radius);
502         RNA_float_set_array(&itemptr, "location", location);
503         RNA_float_set_array(&itemptr, "mouse", mouse_out);
504         RNA_boolean_set(&itemptr, "pen_flip", stroke->pen_flip);
505         RNA_float_set(&itemptr, "pressure", pressure);
506
507         stroke->update_step(C, stroke, &itemptr);
508
509         /* don't record this for now, it takes up a lot of memory when doing long
510          * strokes with small brush size, and operators have register disabled */
511         RNA_collection_clear(op->ptr, "stroke");
512 }
513
514 /* Returns zero if no sculpt changes should be made, non-zero otherwise */
515 static bool paint_smooth_stroke(
516         PaintStroke *stroke, const PaintSample *sample, ePaintMode mode,
517         float r_mouse[2], float *r_pressure)
518 {
519         if (paint_supports_smooth_stroke(stroke->brush, mode)) {
520                 float radius = stroke->brush->smooth_stroke_radius * stroke->zoom_2d;
521                 float u = stroke->brush->smooth_stroke_factor;
522
523                 /* If the mouse is moving within the radius of the last move,
524                  * don't update the mouse position. This allows sharp turns. */
525                 if (len_squared_v2v2(stroke->last_mouse_position, sample->mouse) < SQUARE(radius)) {
526                         return false;
527                 }
528
529                 interp_v2_v2v2(r_mouse, sample->mouse, stroke->last_mouse_position, u);
530                 *r_pressure = interpf(sample->pressure, stroke->last_pressure, u);
531         }
532         else {
533                 r_mouse[0] = sample->mouse[0];
534                 r_mouse[1] = sample->mouse[1];
535                 *r_pressure = sample->pressure;
536         }
537
538         return true;
539 }
540
541 static float paint_space_stroke_spacing(const Scene *scene, PaintStroke *stroke, float size_pressure, float spacing_pressure)
542 {
543         /* brushes can have a minimum size of 1.0 but with pressure it can be smaller then a pixel
544          * causing very high step sizes, hanging blender [#32381] */
545         const float size_clamp = max_ff(1.0f, BKE_brush_size_get(scene, stroke->brush) * size_pressure);
546         float spacing = stroke->brush->spacing;
547
548         /* apply spacing pressure */
549         if (stroke->brush->flag & BRUSH_SPACING_PRESSURE)
550                 spacing = spacing * (1.5f - spacing_pressure);
551
552         /* stroke system is used for 2d paint too, so we need to account for
553          * the fact that brush can be scaled there. */
554         spacing *= stroke->zoom_2d;
555
556         return max_ff(1.0, size_clamp * spacing / 50.0f);
557 }
558
559
560
561 static float paint_stroke_overlapped_curve(Brush *br, float x, float spacing)
562 {
563         int i;
564         const int n = 100 / spacing;
565         const float h = spacing / 50.0f;
566         const float x0 = x - 1;
567
568         float sum;
569
570         sum = 0;
571         for (i = 0; i < n; i++) {
572                 float xx;
573
574                 xx = fabsf(x0 + i * h);
575
576                 if (xx < 1.0f)
577                         sum += BKE_brush_curve_strength(br, xx, 1);
578         }
579
580         return sum;
581 }
582
583 static float paint_stroke_integrate_overlap(Brush *br, float factor)
584 {
585         int i;
586         int m;
587         float g;
588         float max;
589
590         float spacing = br->spacing * factor;
591
592         if (!(br->flag & BRUSH_SPACE_ATTEN && (br->spacing < 100)))
593                 return 1.0;
594
595         m = 10;
596         g = 1.0f / m;
597         max = 0;
598         for (i = 0; i < m; i++) {
599                 float overlap = fabs(paint_stroke_overlapped_curve(br, i * g, spacing));
600
601                 if (overlap > max)
602                         max = overlap;
603         }
604
605         if (max == 0.0f)
606                 return 1.0f;
607         else
608                 return 1.0f / max;
609 }
610
611 static float paint_space_stroke_spacing_variable(const Scene *scene, PaintStroke *stroke, float pressure, float dpressure, float length)
612 {
613         if (BKE_brush_use_size_pressure(scene, stroke->brush)) {
614                 /* use pressure to modify size. set spacing so that at 100%, the circles
615                  * are aligned nicely with no overlap. for this the spacing needs to be
616                  * the average of the previous and next size. */
617                 float s = paint_space_stroke_spacing(scene, stroke, 1.0f, pressure);
618                 float q = s * dpressure / (2.0f * length);
619                 float pressure_fac = (1.0f + q) / (1.0f - q);
620
621                 float last_size_pressure = stroke->last_pressure;
622                 float new_size_pressure = stroke->last_pressure * pressure_fac;
623
624                 /* average spacing */
625                 float last_spacing = paint_space_stroke_spacing(scene, stroke, last_size_pressure, pressure);
626                 float new_spacing = paint_space_stroke_spacing(scene, stroke, new_size_pressure, pressure);
627
628                 return 0.5f * (last_spacing + new_spacing);
629         }
630         else {
631                 /* no size pressure */
632                 return paint_space_stroke_spacing(scene, stroke, 1.0f, pressure);
633         }
634 }
635
636 /* For brushes with stroke spacing enabled, moves mouse in steps
637  * towards the final mouse location. */
638 static int paint_space_stroke(bContext *C, wmOperator *op, const float final_mouse[2], float final_pressure)
639 {
640         const Scene *scene = CTX_data_scene(C);
641         PaintStroke *stroke = op->customdata;
642         UnifiedPaintSettings *ups = stroke->ups;
643         int cnt = 0;
644
645         float pressure, dpressure;
646         float mouse[2], dmouse[2];
647         float length;
648         float no_pressure_spacing = paint_space_stroke_spacing(scene, stroke, 1.0f, 1.0f);
649
650         sub_v2_v2v2(dmouse, final_mouse, stroke->last_mouse_position);
651
652         pressure = stroke->last_pressure;
653         dpressure = final_pressure - stroke->last_pressure;
654
655         length = normalize_v2(dmouse);
656
657         while (length > 0.0f) {
658                 float spacing = paint_space_stroke_spacing_variable(scene, stroke, pressure, dpressure, length);
659
660                 if (length >= spacing) {
661                         mouse[0] = stroke->last_mouse_position[0] + dmouse[0] * spacing;
662                         mouse[1] = stroke->last_mouse_position[1] + dmouse[1] * spacing;
663                         pressure = stroke->last_pressure + (spacing / length) * dpressure;
664
665                         ups->overlap_factor = paint_stroke_integrate_overlap(stroke->brush, spacing / no_pressure_spacing);
666
667                         stroke->stroke_distance += spacing / stroke->zoom_2d;
668                         paint_brush_stroke_add_step(C, op, mouse, pressure);
669
670                         length -= spacing;
671                         pressure = stroke->last_pressure;
672                         dpressure = final_pressure - stroke->last_pressure;
673
674                         cnt++;
675                 }
676                 else {
677                         break;
678                 }
679         }
680
681         return cnt;
682 }
683
684 /**** Public API ****/
685
686 PaintStroke *paint_stroke_new(bContext *C,
687                               wmOperator *op,
688                               StrokeGetLocation get_location,
689                               StrokeTestStart test_start,
690                               StrokeUpdateStep update_step,
691                               StrokeRedraw redraw,
692                               StrokeDone done, int event_type)
693 {
694         PaintStroke *stroke = MEM_callocN(sizeof(PaintStroke), "PaintStroke");
695         ToolSettings *toolsettings = CTX_data_tool_settings(C);
696         UnifiedPaintSettings *ups = &toolsettings->unified_paint_settings;
697         Paint *p = BKE_paint_get_active_from_context(C);
698         Brush *br = stroke->brush = BKE_paint_brush(p);
699         float zoomx, zoomy;
700
701         ED_view3d_viewcontext_init(C, &stroke->vc);
702
703         stroke->get_location = get_location;
704         stroke->test_start = test_start;
705         stroke->update_step = update_step;
706         stroke->redraw = redraw;
707         stroke->done = done;
708         stroke->event_type = event_type; /* for modal, return event */
709         stroke->ups = ups;
710         stroke->stroke_mode = RNA_enum_get(op->ptr, "mode");
711
712         get_imapaint_zoom(C, &zoomx, &zoomy);
713         stroke->zoom_2d = max_ff(zoomx, zoomy);
714
715         if (stroke->stroke_mode == BRUSH_STROKE_INVERT) {
716                 if (br->flag & (BRUSH_CURVE)) {
717                         RNA_enum_set(op->ptr, "mode", BRUSH_STROKE_NORMAL);
718                 }
719         }
720         /* initialize here */
721         ups->overlap_factor = 1.0;
722         ups->stroke_active = true;
723         
724         zero_v3(ups->average_stroke_accum);
725         ups->average_stroke_counter = 0;
726         
727         /* initialize here to avoid initialization conflict with threaded strokes */
728         curvemapping_initialize(br->curve);
729         if (p->flags & PAINT_USE_CAVITY_MASK)
730                 curvemapping_initialize(p->cavity_curve);
731
732         BKE_paint_set_overlay_override(br->overlay_flags);
733
734         return stroke;
735 }
736
737 void paint_stroke_data_free(struct wmOperator *op)
738 {
739         BKE_paint_set_overlay_override(0);
740         MEM_SAFE_FREE(op->customdata);
741 }
742
743 static void stroke_done(struct bContext *C, struct wmOperator *op)
744 {
745         struct PaintStroke *stroke = op->customdata;
746         UnifiedPaintSettings *ups = stroke->ups;
747
748         ups->draw_anchored = false;
749         ups->stroke_active = false;
750
751         /* reset rotation here to avoid doing so in cursor display */
752         if (!(stroke->brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE))
753                 ups->brush_rotation = 0.0f;
754
755         if (!(stroke->brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE))
756                 ups->brush_rotation_sec = 0.0f;
757
758         if (stroke->stroke_started) {
759                 if (stroke->redraw)
760                         stroke->redraw(C, stroke, true);
761
762                 if (stroke->done)
763                         stroke->done(C, stroke);
764         }
765
766         if (stroke->timer) {
767                 WM_event_remove_timer(
768                         CTX_wm_manager(C),
769                         CTX_wm_window(C),
770                         stroke->timer);
771         }
772
773         if (stroke->stroke_cursor)
774                 WM_paint_cursor_end(CTX_wm_manager(C), stroke->stroke_cursor);
775
776         BLI_freelistN(&stroke->line);
777
778         paint_stroke_data_free(op);
779 }
780
781 /* Returns zero if the stroke dots should not be spaced, non-zero otherwise */
782 bool paint_space_stroke_enabled(Brush *br, ePaintMode mode)
783 {
784         return (br->flag & BRUSH_SPACE) && paint_supports_dynamic_size(br, mode);
785 }
786
787 static bool sculpt_is_grab_tool(Brush *br)
788 {
789         return ELEM(br->sculpt_tool,
790                      SCULPT_TOOL_GRAB,
791                      SCULPT_TOOL_THUMB,
792                      SCULPT_TOOL_ROTATE,
793                      SCULPT_TOOL_SNAKE_HOOK);
794 }
795
796 /* return true if the brush size can change during paint (normally used for pressure) */
797 bool paint_supports_dynamic_size(Brush *br, ePaintMode mode)
798 {
799         if (br->flag & BRUSH_ANCHORED)
800                 return false;
801
802         switch (mode) {
803                 case ePaintSculpt:
804                         if (sculpt_is_grab_tool(br))
805                                 return false;
806                         break;
807
808                 case ePaintTexture2D: /* fall through */
809                 case ePaintTextureProjective:
810                         if ((br->imagepaint_tool == PAINT_TOOL_FILL) &&
811                             (br->flag & BRUSH_USE_GRADIENT))
812                         {
813                                 return false;
814                         }
815                         break;
816
817                 default:
818                         break;
819         }
820         return true;
821 }
822
823 bool paint_supports_smooth_stroke(Brush *br, ePaintMode mode)
824 {
825         if (!(br->flag & BRUSH_SMOOTH_STROKE) ||
826             (br->flag & (BRUSH_ANCHORED | BRUSH_DRAG_DOT | BRUSH_LINE)))
827         {
828                 return false;
829         }
830
831         switch (mode) {
832                 case ePaintSculpt:
833                         if (sculpt_is_grab_tool(br))
834                                 return false;
835                         break;
836                 default:
837                         break;
838         }
839         return true;
840 }
841
842 bool paint_supports_texture(ePaintMode mode)
843 {
844         /* omit: PAINT_WEIGHT, PAINT_SCULPT_UV, PAINT_INVALID */
845         return ELEM(mode, ePaintSculpt, ePaintVertex, ePaintTextureProjective, ePaintTexture2D);
846 }
847
848 /* return true if the brush size can change during paint (normally used for pressure) */
849 bool paint_supports_dynamic_tex_coords(Brush *br, ePaintMode mode)
850 {
851         if (br->flag & BRUSH_ANCHORED)
852                 return false;
853
854         switch (mode) {
855                 case ePaintSculpt:
856                         if (sculpt_is_grab_tool(br))
857                                 return false;
858                         break;
859                 default:
860                         break;
861         }
862         return true;
863 }
864
865 #define PAINT_STROKE_MODAL_CANCEL 1
866
867 /* called in paint_ops.c, on each regeneration of keymaps  */
868 struct wmKeyMap *paint_stroke_modal_keymap(struct wmKeyConfig *keyconf)
869 {
870         static struct EnumPropertyItem modal_items[] = {
871                 {PAINT_STROKE_MODAL_CANCEL, "CANCEL", 0,
872                 "Cancel",
873                 "Cancel and undo a stroke in progress"},
874
875                 { 0 }
876         };
877
878         static const char *name = "Paint Stroke Modal";
879
880         struct wmKeyMap *keymap = WM_modalkeymap_get(keyconf, name);
881
882         /* this function is called for each spacetype, only needs to add map once */
883         if (!keymap) {
884                 keymap = WM_modalkeymap_add(keyconf, name, modal_items);
885
886                 /* items for modal map */
887                 WM_modalkeymap_add_item(
888                         keymap, ESCKEY, KM_PRESS, KM_ANY, 0, PAINT_STROKE_MODAL_CANCEL);
889         }
890
891         return keymap;
892 }
893
894 static void paint_stroke_add_sample(const Paint *paint,
895                                     PaintStroke *stroke,
896                                     float x, float y, float pressure)
897 {
898         PaintSample *sample = &stroke->samples[stroke->cur_sample];
899         int max_samples = CLAMPIS(paint->num_input_samples, 1, PAINT_MAX_INPUT_SAMPLES);
900
901         sample->mouse[0] = x;
902         sample->mouse[1] = y;
903         sample->pressure = pressure;
904
905         stroke->cur_sample++;
906         if (stroke->cur_sample >= max_samples)
907                 stroke->cur_sample = 0;
908         if (stroke->num_samples < max_samples)
909                 stroke->num_samples++;
910 }
911
912 static void paint_stroke_sample_average(const PaintStroke *stroke,
913                                         PaintSample *average)
914 {
915         int i;
916         
917         memset(average, 0, sizeof(*average));
918
919         BLI_assert(stroke->num_samples > 0);
920         
921         for (i = 0; i < stroke->num_samples; i++) {
922                 add_v2_v2(average->mouse, stroke->samples[i].mouse);
923                 average->pressure += stroke->samples[i].pressure;
924         }
925
926         mul_v2_fl(average->mouse, 1.0f / stroke->num_samples);
927         average->pressure /= stroke->num_samples;
928
929         /*printf("avg=(%f, %f), num=%d\n", average->mouse[0], average->mouse[1], stroke->num_samples);*/
930 }
931
932 /**
933  * Slightly different version of spacing for line/curve strokes,
934  * makes sure the dabs stay on the line path.
935  */
936 static void paint_line_strokes_spacing(
937         bContext *C, wmOperator *op, PaintStroke *stroke, float spacing, float *length_residue,
938         const float old_pos[2], const float new_pos[2])
939 {
940         UnifiedPaintSettings *ups = stroke->ups;
941
942         float mouse[2], dmouse[2];
943         float length;
944
945         sub_v2_v2v2(dmouse, new_pos, old_pos);
946         copy_v2_v2(stroke->last_mouse_position, old_pos);
947
948         length = normalize_v2(dmouse);
949
950         BLI_assert(length >= 0.0f);
951
952         if (length == 0.0f)
953                 return;
954
955         while (length > 0.0f) {
956                 float spacing_final = spacing - *length_residue;
957                 length += *length_residue;
958                 *length_residue = 0.0;
959
960                 if (length >= spacing) {
961                         mouse[0] = stroke->last_mouse_position[0] + dmouse[0] * spacing_final;
962                         mouse[1] = stroke->last_mouse_position[1] + dmouse[1] * spacing_final;
963
964                         ups->overlap_factor = paint_stroke_integrate_overlap(stroke->brush, 1.0);
965
966                         stroke->stroke_distance += spacing / stroke->zoom_2d;
967                         paint_brush_stroke_add_step(C, op, mouse, 1.0);
968
969                         length -= spacing;
970                         spacing_final = spacing;
971                 }
972                 else {
973                         break;
974                 }
975         }
976
977         *length_residue = length;
978 }
979
980
981 static void paint_stroke_line_end(bContext *C, wmOperator *op, PaintStroke *stroke, float mouse[2])
982 {
983         Brush *br = stroke->brush;
984         if (stroke->stroke_started && (br->flag & BRUSH_LINE)) {
985                 stroke->ups->overlap_factor = paint_stroke_integrate_overlap(br, 1.0);
986
987                 paint_brush_stroke_add_step(C, op, stroke->last_mouse_position, 1.0);
988                 paint_space_stroke(C, op, mouse, 1.0);
989         }
990 }
991
992 static bool paint_stroke_curve_end(bContext *C, wmOperator *op, PaintStroke *stroke)
993 {
994         Brush *br = stroke->brush;
995
996         if (br->flag & BRUSH_CURVE) {
997                 UnifiedPaintSettings *ups = &CTX_data_tool_settings(C)->unified_paint_settings;
998                 const Scene *scene = CTX_data_scene(C);
999                 const float spacing = paint_space_stroke_spacing(scene, stroke, 1.0f, 1.0f);
1000                 PaintCurve *pc = br->paint_curve;
1001                 PaintCurvePoint *pcp;
1002                 float length_residue = 0.0f;
1003                 int i;
1004
1005                 if (!pc)
1006                         return true;
1007
1008 #ifdef DEBUG_TIME
1009                 TIMEIT_START_AVERAGED(whole_stroke);
1010 #endif
1011
1012                 pcp = pc->points;
1013                 stroke->ups->overlap_factor = paint_stroke_integrate_overlap(br, 1.0);
1014
1015                 for (i = 0; i < pc->tot_points - 1; i++, pcp++) {
1016                         int j;
1017                         float data[(PAINT_CURVE_NUM_SEGMENTS + 1) * 2];
1018                         float tangents[(PAINT_CURVE_NUM_SEGMENTS + 1) * 2];
1019                         PaintCurvePoint *pcp_next = pcp + 1;
1020                         bool do_rake = false;
1021
1022                         for (j = 0; j < 2; j++) {
1023                                 BKE_curve_forward_diff_bezier(
1024                                         pcp->bez.vec[1][j],
1025                                         pcp->bez.vec[2][j],
1026                                         pcp_next->bez.vec[0][j],
1027                                         pcp_next->bez.vec[1][j],
1028                                         data + j, PAINT_CURVE_NUM_SEGMENTS, sizeof(float[2]));
1029                         }
1030
1031                         if ((br->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) ||
1032                             (br->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE))
1033                         {
1034                                 do_rake = true;
1035                                 for (j = 0; j < 2; j++) {
1036                                         BKE_curve_forward_diff_tangent_bezier(
1037                                                 pcp->bez.vec[1][j],
1038                                                 pcp->bez.vec[2][j],
1039                                                 pcp_next->bez.vec[0][j],
1040                                                 pcp_next->bez.vec[1][j],
1041                                                 tangents + j, PAINT_CURVE_NUM_SEGMENTS, sizeof(float[2]));
1042                                 }
1043                         }
1044
1045                         for (j = 0; j < PAINT_CURVE_NUM_SEGMENTS; j++) {
1046                                 if (do_rake) {
1047                                         float rotation = atan2f(tangents[2 * j], tangents[2 * j + 1]);
1048                                         paint_update_brush_rake_rotation(ups, br, rotation);
1049                                 }
1050
1051                                 if (!stroke->stroke_started) {
1052                                         stroke->last_pressure = 1.0;
1053                                         copy_v2_v2(stroke->last_mouse_position, data + 2 * j);
1054                                         stroke->stroke_started = stroke->test_start(C, op, stroke->last_mouse_position);
1055
1056                                         if (stroke->stroke_started) {
1057                                                 paint_brush_stroke_add_step(C, op, data + 2 * j, 1.0);
1058                                                 paint_line_strokes_spacing(C, op, stroke, spacing, &length_residue, data + 2 * j, data + 2 * (j + 1));
1059                                         }
1060                                 }
1061                                 else {
1062                                         paint_line_strokes_spacing(C, op, stroke, spacing, &length_residue, data + 2 * j, data + 2 * (j + 1));
1063                                 }
1064                         }
1065                 }
1066
1067                 stroke_done(C, op);
1068
1069 #ifdef DEBUG_TIME
1070                 TIMEIT_END_AVERAGED(whole_stroke);
1071 #endif
1072
1073                 return true;
1074         }
1075
1076         return false;
1077 }
1078
1079 static void paint_stroke_line_constrain(PaintStroke *stroke, float mouse[2])
1080 {
1081         if (stroke->constrain_line) {
1082                 float line[2];
1083                 float angle, len, res;
1084                 
1085                 sub_v2_v2v2(line, mouse, stroke->last_mouse_position);
1086                 angle = atan2f(line[1], line[0]);
1087                 len = len_v2(line);
1088                 
1089                 /* divide angle by PI/4 */
1090                 angle = 4.0f * angle / (float)M_PI;
1091                 
1092                 /* now take residue */
1093                 res = angle - floorf(angle);
1094                 
1095                 /* residue decides how close we are at a certain angle */
1096                 if (res <= 0.5f) {
1097                         angle = floorf(angle) * (float)M_PI_4;
1098                 }
1099                 else {
1100                         angle = (floorf(angle) + 1.0f) * (float)M_PI_4;
1101                 }
1102                 
1103                 mouse[0] = stroke->constrained_pos[0] = len * cosf(angle) + stroke->last_mouse_position[0];
1104                 mouse[1] = stroke->constrained_pos[1] = len * sinf(angle) + stroke->last_mouse_position[1];
1105         }
1106 }
1107
1108 int paint_stroke_modal(bContext *C, wmOperator *op, const wmEvent *event)
1109 {
1110         Paint *p = BKE_paint_get_active_from_context(C);
1111         ePaintMode mode = BKE_paintmode_get_active_from_context(C);
1112         PaintStroke *stroke = op->customdata;
1113         Brush *br = stroke->brush;
1114         PaintSample sample_average;
1115         float mouse[2];
1116         bool first_dab = false;
1117         bool first_modal = false;
1118         bool redraw = false;
1119         float pressure;
1120
1121         /* see if tablet affects event. Line, anchored and drag dot strokes do not support pressure */
1122         pressure = (br->flag & (BRUSH_LINE | BRUSH_ANCHORED | BRUSH_DRAG_DOT)) ? 1.0f : WM_event_tablet_data(event, &stroke->pen_flip, NULL);
1123
1124         paint_stroke_add_sample(p, stroke, event->mval[0], event->mval[1], pressure);
1125         paint_stroke_sample_average(stroke, &sample_average);
1126
1127 #ifdef WITH_INPUT_NDOF
1128         /* let NDOF motion pass through to the 3D view so we can paint and rotate simultaneously!
1129          * this isn't perfect... even when an extra MOUSEMOVE is spoofed, the stroke discards it
1130          * since the 2D deltas are zero -- code in this file needs to be updated to use the
1131          * post-NDOF_MOTION MOUSEMOVE */
1132         if (event->type == NDOF_MOTION)
1133                 return OPERATOR_PASS_THROUGH;
1134 #endif
1135
1136         /* one time initialization */
1137         if (!stroke->stroke_init) {
1138                 if (paint_stroke_curve_end(C, op, stroke))
1139                         return OPERATOR_FINISHED;
1140
1141                 if (paint_supports_smooth_stroke(br, mode))
1142                         stroke->stroke_cursor =
1143                             WM_paint_cursor_activate(CTX_wm_manager(C), paint_poll, paint_draw_smooth_cursor, stroke);
1144
1145                 stroke->stroke_init = true;
1146                 first_modal = true;
1147         }
1148
1149         /* one time stroke initialization */
1150         if (!stroke->stroke_started) {
1151                 stroke->last_pressure = sample_average.pressure;
1152                 copy_v2_v2(stroke->last_mouse_position, sample_average.mouse);
1153                 stroke->stroke_started = stroke->test_start(C, op, sample_average.mouse);
1154                 BLI_assert((stroke->stroke_started & ~1) == 0);  /* 0/1 */
1155
1156                 if (stroke->stroke_started) {
1157                         if (br->flag & BRUSH_AIRBRUSH)
1158                                 stroke->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, stroke->brush->rate);
1159
1160                         if (br->flag & BRUSH_LINE) {
1161                                 stroke->stroke_cursor =
1162                                         WM_paint_cursor_activate(CTX_wm_manager(C), paint_poll, paint_draw_line_cursor, stroke);
1163                         }
1164
1165                         first_dab = true;
1166                 }
1167         }
1168
1169         /* Cancel */
1170         if (event->type == EVT_MODAL_MAP && event->val == PAINT_STROKE_MODAL_CANCEL) {
1171                 if (op->type->cancel) {
1172                         op->type->cancel(C, op);
1173                 }
1174                 else {
1175                         paint_stroke_cancel(C, op);
1176                 }
1177                 return OPERATOR_CANCELLED;
1178         }
1179
1180         if (event->type == stroke->event_type && !first_modal) {
1181                 if (event->val == KM_RELEASE) {
1182                         copy_v2_fl2(mouse, event->mval[0], event->mval[1]);
1183                         paint_stroke_line_constrain(stroke, mouse);
1184                         paint_stroke_line_end(C, op, stroke, mouse);
1185                         stroke_done(C, op);
1186                         return OPERATOR_FINISHED;
1187                 }
1188         }
1189         else if (ELEM(event->type, RETKEY, SPACEKEY)) {
1190                 paint_stroke_line_end(C, op, stroke, sample_average.mouse);
1191                 stroke_done(C, op);
1192                 return OPERATOR_FINISHED;
1193         }
1194         else if (br->flag & BRUSH_LINE) {
1195                 if (event->alt)
1196                         stroke->constrain_line = true;
1197                 else 
1198                         stroke->constrain_line = false;
1199
1200                 copy_v2_fl2(mouse, event->mval[0], event->mval[1]);
1201                 paint_stroke_line_constrain(stroke, mouse);
1202                 
1203                 if (stroke->stroke_started && (first_modal || (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)))) {
1204                         if ((br->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) || (br->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE)) {
1205                                 copy_v2_v2(stroke->ups->last_rake, stroke->last_mouse_position);
1206                         }
1207                         paint_calculate_rake_rotation(stroke->ups, br, mouse);
1208                 }
1209         }
1210         else if (first_modal ||
1211                  /* regular dabs */
1212                  (!(br->flag & (BRUSH_AIRBRUSH)) && (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE))) ||
1213                  /* airbrush */
1214                  ((br->flag & BRUSH_AIRBRUSH) && event->type == TIMER && event->customdata == stroke->timer))
1215         {
1216                 if (paint_smooth_stroke(stroke, &sample_average, mode, mouse, &pressure)) {
1217                         if (stroke->stroke_started) {
1218                                 if (paint_space_stroke_enabled(br, mode)) {
1219                                         if (paint_space_stroke(C, op, mouse, pressure))
1220                                                 redraw = true;
1221                                 }
1222                                 else {
1223                                         float dmouse[2];
1224                                         sub_v2_v2v2(dmouse, mouse, stroke->last_mouse_position);
1225                                         stroke->stroke_distance += len_v2(dmouse);
1226                                         paint_brush_stroke_add_step(C, op, mouse, pressure);
1227                                         redraw = true;
1228                                 }
1229                         }
1230                 }
1231         }
1232
1233         /* we want the stroke to have the first daub at the start location
1234          * instead of waiting till we have moved the space distance */
1235         if (first_dab &&
1236             paint_space_stroke_enabled(br, mode) &&
1237             !(br->flag & BRUSH_SMOOTH_STROKE))
1238         {
1239                 stroke->ups->overlap_factor = paint_stroke_integrate_overlap(br, 1.0);
1240                 paint_brush_stroke_add_step(C, op, sample_average.mouse, sample_average.pressure);
1241                 redraw = true;
1242         }
1243
1244         /* do updates for redraw. if event is inbetween mousemove there are more
1245          * coming, so postpone potentially slow redraw updates until all are done */
1246         if (event->type != INBETWEEN_MOUSEMOVE) {
1247                 wmWindow *window = CTX_wm_window(C);
1248                 ARegion *ar = CTX_wm_region(C);
1249
1250                 /* At the very least, invalidate the cursor */
1251                 if (ar && (p->flags & PAINT_SHOW_BRUSH))
1252                         WM_paint_cursor_tag_redraw(window, ar);
1253
1254                 if (redraw && stroke->redraw)
1255                         stroke->redraw(C, stroke, false);
1256         }
1257
1258         return OPERATOR_RUNNING_MODAL;
1259 }
1260
1261 int paint_stroke_exec(bContext *C, wmOperator *op)
1262 {
1263         PaintStroke *stroke = op->customdata;
1264
1265         /* only when executed for the first time */
1266         if (stroke->stroke_started == 0) {
1267                 PropertyRNA *strokeprop;
1268                 PointerRNA firstpoint;
1269                 float mouse[2];
1270
1271                 strokeprop = RNA_struct_find_property(op->ptr, "stroke");
1272
1273                 if (RNA_property_collection_lookup_int(op->ptr, strokeprop, 0, &firstpoint)) {
1274                         RNA_float_get_array(&firstpoint, "mouse", mouse);
1275                         stroke->stroke_started = stroke->test_start(C, op, mouse);
1276                 }
1277         }
1278
1279         if (stroke->stroke_started) {
1280                 RNA_BEGIN (op->ptr, itemptr, "stroke")
1281                 {
1282                         stroke->update_step(C, stroke, &itemptr);
1283                 }
1284                 RNA_END;
1285         }
1286
1287         bool ok = (stroke->stroke_started != 0);
1288
1289         stroke_done(C, op);
1290
1291         return ok ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
1292 }
1293
1294 void paint_stroke_cancel(bContext *C, wmOperator *op)
1295 {
1296         stroke_done(C, op);
1297 }
1298
1299 ViewContext *paint_stroke_view_context(PaintStroke *stroke)
1300 {
1301         return &stroke->vc;
1302 }
1303
1304 void *paint_stroke_mode_data(struct PaintStroke *stroke)
1305 {
1306         return stroke->mode_data;
1307 }
1308
1309 bool paint_stroke_flipped(struct PaintStroke *stroke)
1310 {
1311         return stroke->pen_flip;
1312 }
1313
1314 float paint_stroke_distance_get(struct PaintStroke *stroke)
1315 {
1316         return stroke->stroke_distance;
1317 }
1318
1319 void paint_stroke_set_mode_data(PaintStroke *stroke, void *mode_data)
1320 {
1321         stroke->mode_data = mode_data;
1322 }
1323
1324 int paint_poll(bContext *C)
1325 {
1326         Paint *p = BKE_paint_get_active_from_context(C);
1327         Object *ob = CTX_data_active_object(C);
1328         ScrArea *sa = CTX_wm_area(C);
1329         ARegion *ar = CTX_wm_region(C);
1330
1331         return p && ob && BKE_paint_brush(p) &&
1332                (sa && ELEM(sa->spacetype, SPACE_VIEW3D, SPACE_IMAGE)) &&
1333                (ar && ar->regiontype == RGN_TYPE_WINDOW);
1334 }