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