Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / curve / editcurve_paint.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  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/editors/curve/editcurve_paint.c
22  *  \ingroup edcurve
23  */
24
25 #include "DNA_object_types.h"
26 #include "DNA_scene_types.h"
27
28 #include "MEM_guardedalloc.h"
29
30 #include "BLI_blenlib.h"
31 #include "BLI_math.h"
32 #include "BLI_mempool.h"
33
34 #include "BKE_context.h"
35 #include "BKE_curve.h"
36 #include "BKE_fcurve.h"
37 #include "BKE_main.h"
38 #include "BKE_report.h"
39
40 #include "DEG_depsgraph.h"
41
42 #include "WM_api.h"
43 #include "WM_types.h"
44
45 #include "ED_space_api.h"
46 #include "ED_screen.h"
47 #include "ED_view3d.h"
48 #include "ED_curve.h"
49
50 #include "BIF_gl.h"
51
52 #include "GPU_batch.h"
53 #include "GPU_batch_presets.h"
54 #include "GPU_immediate.h"
55 #include "GPU_immediate_util.h"
56 #include "GPU_matrix.h"
57 #include "GPU_state.h"
58
59 #include "curve_intern.h"
60
61 #include "UI_resources.h"
62
63 #include "RNA_access.h"
64 #include "RNA_define.h"
65
66 #include "RNA_enum_types.h"
67
68 #define USE_SPLINE_FIT
69
70 #ifdef USE_SPLINE_FIT
71 #include "curve_fit_nd.h"
72 #endif
73
74 /* Distance between input samples */
75 #define STROKE_SAMPLE_DIST_MIN_PX 1
76 #define STROKE_SAMPLE_DIST_MAX_PX 3
77
78 /* Distance between start/end points to consider cyclic */
79 #define STROKE_CYCLIC_DIST_PX     8
80
81 /* -------------------------------------------------------------------- */
82
83 /** \name StrokeElem / #RNA_OperatorStrokeElement Conversion Functions
84  * \{ */
85
86 struct StrokeElem {
87         float mval[2];
88         float location_world[3];
89         float location_local[3];
90
91         /* surface normal, may be zero'd */
92         float normal_world[3];
93         float normal_local[3];
94
95         float pressure;
96 };
97
98 struct CurveDrawData {
99         Depsgraph *depsgraph;
100
101         short init_event_type;
102         short curve_type;
103
104         /* projecting 2D into 3D space */
105         struct {
106                 /* use a plane or project to the surface */
107                 bool use_plane;
108                 float    plane[4];
109
110                 /* use 'rv3d->depths', note that this will become 'damaged' while drawing, but thats OK. */
111                 bool use_depth;
112
113                 /* offset projection by this value */
114                 bool use_offset;
115                 float    offset[3];  /* worldspace */
116                 float    surface_offset;
117                 bool     use_surface_offset_absolute;
118         } project;
119
120         /* cursor sampling */
121         struct {
122                 /* use substeps, needed for nicely interpolating depth */
123                 bool use_substeps;
124         } sample;
125
126         struct {
127                 float min, max, range;
128         } radius;
129
130         struct {
131                 float mouse[2];
132                 /* used incase we can't calculate the depth */
133                 float location_world[3];
134
135                 float location_world_valid[3];
136
137                 const struct StrokeElem *selem;
138         } prev;
139
140         ViewContext vc;
141         enum {
142                 CURVE_DRAW_IDLE = 0,
143                 CURVE_DRAW_PAINTING = 1,
144         } state;
145
146         /* StrokeElem */
147         BLI_mempool *stroke_elem_pool;
148
149         void *draw_handle_view;
150 };
151
152 static float stroke_elem_radius_from_pressure(const struct CurveDrawData *cdd, const float pressure)
153 {
154         const Curve *cu = cdd->vc.obedit->data;
155         return ((pressure * cdd->radius.range) + cdd->radius.min) * cu->ext2;
156 }
157
158 static float stroke_elem_radius(const struct CurveDrawData *cdd, const struct StrokeElem *selem)
159 {
160         return stroke_elem_radius_from_pressure(cdd, selem->pressure);
161 }
162
163 static void stroke_elem_pressure_set(const struct CurveDrawData *cdd, struct StrokeElem *selem, float pressure)
164 {
165         if ((cdd->project.surface_offset != 0.0f) &&
166             !cdd->project.use_surface_offset_absolute &&
167             !is_zero_v3(selem->normal_local))
168         {
169                 const float adjust = stroke_elem_radius_from_pressure(cdd, pressure) -
170                                      stroke_elem_radius_from_pressure(cdd, selem->pressure);
171                 madd_v3_v3fl(selem->location_local, selem->normal_local, adjust);
172                 mul_v3_m4v3(selem->location_world, cdd->vc.obedit->obmat, selem->location_local);
173         }
174         selem->pressure = pressure;
175 }
176
177 static void stroke_elem_interp(
178         struct StrokeElem *selem_out,
179         const struct StrokeElem *selem_a,  const struct StrokeElem *selem_b, float t)
180 {
181         interp_v2_v2v2(selem_out->mval, selem_a->mval, selem_b->mval, t);
182         interp_v3_v3v3(selem_out->location_world, selem_a->location_world, selem_b->location_world, t);
183         interp_v3_v3v3(selem_out->location_local, selem_a->location_local, selem_b->location_local, t);
184         selem_out->pressure = interpf(selem_a->pressure, selem_b->pressure, t);
185 }
186
187
188 /**
189  * Sets the depth from #StrokeElem.mval
190  */
191 static bool stroke_elem_project(
192         const struct CurveDrawData *cdd,
193         const int mval_i[2], const float mval_fl[2],
194         float surface_offset, const float radius,
195         float r_location_world[3], float r_normal_world[3])
196 {
197         ARegion *ar = cdd->vc.ar;
198         RegionView3D *rv3d = cdd->vc.rv3d;
199
200         bool is_location_world_set = false;
201
202         /* project to 'location_world' */
203         if (cdd->project.use_plane) {
204                 /* get the view vector to 'location' */
205                 if (ED_view3d_win_to_3d_on_plane(ar, cdd->project.plane, mval_fl, true, r_location_world)) {
206                         if (r_normal_world) {
207                                 zero_v3(r_normal_world);
208                         }
209                         is_location_world_set = true;
210                 }
211         }
212         else {
213                 const ViewDepths *depths = rv3d->depths;
214                 if (depths &&
215                     ((unsigned int)mval_i[0] < depths->w) &&
216                     ((unsigned int)mval_i[1] < depths->h))
217                 {
218                         const double depth = (double)ED_view3d_depth_read_cached(&cdd->vc, mval_i);
219                         if ((depth > depths->depth_range[0]) && (depth < depths->depth_range[1])) {
220                                 if (ED_view3d_depth_unproject(ar, mval_i, depth, r_location_world)) {
221                                         is_location_world_set = true;
222                                         if (r_normal_world) {
223                                                 zero_v3(r_normal_world);
224                                         }
225
226                                         if (surface_offset != 0.0f) {
227                                                 const float offset = cdd->project.use_surface_offset_absolute ? 1.0f : radius;
228                                                 float normal[3];
229                                                 if (ED_view3d_depth_read_cached_normal(&cdd->vc, mval_i, normal)) {
230                                                         madd_v3_v3fl(r_location_world, normal, offset * surface_offset);
231                                                         if (r_normal_world) {
232                                                                 copy_v3_v3(r_normal_world, normal);
233                                                         }
234                                                 }
235                                         }
236                                 }
237                         }
238                 }
239         }
240
241         if (is_location_world_set) {
242                 if (cdd->project.use_offset) {
243                         add_v3_v3(r_location_world, cdd->project.offset);
244                 }
245         }
246
247         return is_location_world_set;
248 }
249
250 static bool stroke_elem_project_fallback(
251         const struct CurveDrawData *cdd,
252         const int mval_i[2], const float mval_fl[2],
253         const float surface_offset, const float radius,
254         const float location_fallback_depth[3],
255         float r_location_world[3], float r_location_local[3],
256         float r_normal_world[3], float r_normal_local[3])
257 {
258         bool is_depth_found = stroke_elem_project(
259                 cdd, mval_i, mval_fl,
260                 surface_offset, radius,
261                 r_location_world, r_normal_world);
262         if (is_depth_found == false) {
263                 ED_view3d_win_to_3d(cdd->vc.v3d, cdd->vc.ar, location_fallback_depth, mval_fl, r_location_world);
264                 zero_v3(r_normal_local);
265         }
266         mul_v3_m4v3(r_location_local, cdd->vc.obedit->imat, r_location_world);
267
268         if (!is_zero_v3(r_normal_world)) {
269                 copy_v3_v3(r_normal_local, r_normal_world);
270                 mul_transposed_mat3_m4_v3(cdd->vc.obedit->obmat, r_normal_local);
271                 normalize_v3(r_normal_local);
272         }
273         else {
274                 zero_v3(r_normal_local);
275         }
276
277         return is_depth_found;
278 }
279
280 /**
281  * \note #StrokeElem.mval & #StrokeElem.pressure must be set first.
282  */
283 static bool stroke_elem_project_fallback_elem(
284         const struct CurveDrawData *cdd,
285         const float location_fallback_depth[3],
286         struct StrokeElem *selem)
287 {
288         const int mval_i[2] = {UNPACK2(selem->mval)};
289         const float radius = stroke_elem_radius(cdd, selem);
290         return stroke_elem_project_fallback(
291                 cdd, mval_i, selem->mval,
292                 cdd->project.surface_offset, radius,
293                 location_fallback_depth,
294                 selem->location_world, selem->location_local,
295                 selem->normal_world, selem->normal_local);
296 }
297
298 /** \} */
299
300
301 /* -------------------------------------------------------------------- */
302
303 /** \name Operator/Stroke Conversion
304  * \{ */
305
306 static void curve_draw_stroke_to_operator_elem(
307         wmOperator *op, const struct StrokeElem *selem)
308 {
309         PointerRNA itemptr;
310         RNA_collection_add(op->ptr, "stroke", &itemptr);
311
312         RNA_float_set_array(&itemptr, "mouse", selem->mval);
313         RNA_float_set_array(&itemptr, "location", selem->location_world);
314         RNA_float_set(&itemptr, "pressure", selem->pressure);
315 }
316
317 static void curve_draw_stroke_from_operator_elem(
318         wmOperator *op, PointerRNA *itemptr)
319 {
320         struct CurveDrawData *cdd = op->customdata;
321
322         struct StrokeElem *selem = BLI_mempool_calloc(cdd->stroke_elem_pool);
323
324         RNA_float_get_array(itemptr, "mouse", selem->mval);
325         RNA_float_get_array(itemptr, "location", selem->location_world);
326         mul_v3_m4v3(selem->location_local, cdd->vc.obedit->imat, selem->location_world);
327         selem->pressure = RNA_float_get(itemptr, "pressure");
328 }
329
330 static void curve_draw_stroke_to_operator(wmOperator *op)
331 {
332         struct CurveDrawData *cdd = op->customdata;
333
334         BLI_mempool_iter iter;
335         const struct StrokeElem *selem;
336
337         BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
338         for (selem = BLI_mempool_iterstep(&iter); selem; selem = BLI_mempool_iterstep(&iter)) {
339                 curve_draw_stroke_to_operator_elem(op, selem);
340         }
341 }
342
343 static void curve_draw_stroke_from_operator(wmOperator *op)
344 {
345         RNA_BEGIN (op->ptr, itemptr, "stroke")
346         {
347                 curve_draw_stroke_from_operator_elem(op, &itemptr);
348         }
349         RNA_END;
350 }
351
352 /** \} */
353
354
355 /* -------------------------------------------------------------------- */
356
357 /** \name Operator Callbacks & Helpers
358  * \{ */
359
360 static void curve_draw_stroke_3d(const struct bContext *UNUSED(C), ARegion *UNUSED(ar), void *arg)
361 {
362         wmOperator *op = arg;
363         struct CurveDrawData *cdd = op->customdata;
364
365         const int stroke_len = BLI_mempool_len(cdd->stroke_elem_pool);
366
367         if (stroke_len == 0) {
368                 return;
369         }
370
371         Object *obedit = cdd->vc.obedit;
372         Curve *cu = obedit->data;
373
374         if (cu->ext2 > 0.0f) {
375                 BLI_mempool_iter iter;
376                 const struct StrokeElem *selem;
377
378                 const float  location_zero[3] = {0};
379                 const float *location_prev = location_zero;
380
381                 float color[3];
382                 UI_GetThemeColor3fv(TH_WIRE, color);
383
384                 GPUBatch *sphere = GPU_batch_preset_sphere(0);
385                 GPU_batch_program_set_builtin(sphere, GPU_SHADER_3D_UNIFORM_COLOR);
386                 GPU_batch_uniform_3fv(sphere, "color", color);
387
388                 /* scale to edit-mode space */
389                 GPU_matrix_push();
390                 GPU_matrix_mul(obedit->obmat);
391
392                 BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
393                 for (selem = BLI_mempool_iterstep(&iter); selem; selem = BLI_mempool_iterstep(&iter)) {
394                         GPU_matrix_translate_3f(
395                                 selem->location_local[0] - location_prev[0],
396                                 selem->location_local[1] - location_prev[1],
397                                 selem->location_local[2] - location_prev[2]);
398                         location_prev = selem->location_local;
399
400                         const float radius = stroke_elem_radius(cdd, selem);
401
402                         GPU_matrix_push();
403                         GPU_matrix_scale_1f(radius);
404                         GPU_batch_draw(sphere);
405                         GPU_matrix_pop();
406
407                         location_prev = selem->location_local;
408                 }
409
410                 GPU_matrix_pop();
411         }
412
413         if (stroke_len > 1) {
414                 float (*coord_array)[3] = MEM_mallocN(sizeof(*coord_array) * stroke_len, __func__);
415
416                 {
417                         BLI_mempool_iter iter;
418                         const struct StrokeElem *selem;
419                         int i;
420                         BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
421                         for (selem = BLI_mempool_iterstep(&iter), i = 0; selem; selem = BLI_mempool_iterstep(&iter), i++) {
422                                 copy_v3_v3(coord_array[i], selem->location_world);
423                         }
424                 }
425
426                 {
427                         GPUVertFormat *format = immVertexFormat();
428                         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 3, GPU_FETCH_FLOAT);
429                         immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR);
430
431                         GPU_depth_test(false);
432                         GPU_blend(true);
433                         GPU_line_smooth(true);
434                         GPU_line_width(3.0f);
435
436                         imm_cpack(0x0);
437                         immBegin(GPU_PRIM_LINE_STRIP, stroke_len);
438                         for (int i = 0; i < stroke_len; i++) {
439                                 immVertex3fv(pos, coord_array[i]);
440                         }
441                         immEnd();
442
443                         GPU_line_width(1.0f);
444
445                         imm_cpack(0xffffffff);
446                         immBegin(GPU_PRIM_LINE_STRIP, stroke_len);
447                         for (int i = 0; i < stroke_len; i++) {
448                                 immVertex3fv(pos, coord_array[i]);
449                         }
450                         immEnd();
451
452                         /* Reset defaults */
453                         GPU_depth_test(true);
454                         GPU_blend(false);
455                         GPU_line_smooth(false);
456
457                         immUnbindProgram();
458                 }
459
460                 MEM_freeN(coord_array);
461         }
462 }
463
464 static void curve_draw_event_add(wmOperator *op, const wmEvent *event)
465 {
466         struct CurveDrawData *cdd = op->customdata;
467         Object *obedit = cdd->vc.obedit;
468
469         invert_m4_m4(obedit->imat, obedit->obmat);
470
471         struct StrokeElem *selem = BLI_mempool_calloc(cdd->stroke_elem_pool);
472
473         ARRAY_SET_ITEMS(selem->mval, event->mval[0], event->mval[1]);
474
475         /* handle pressure sensitivity (which is supplied by tablets) */
476         if (event->tablet_data) {
477                 const wmTabletData *wmtab = event->tablet_data;
478                 selem->pressure = wmtab->Pressure;
479         }
480         else {
481                 selem->pressure = 1.0f;
482         }
483
484         bool is_depth_found = stroke_elem_project_fallback_elem(
485                 cdd, cdd->prev.location_world_valid, selem);
486
487         if (is_depth_found) {
488                 /* use the depth if a fallback wasn't used */
489                 copy_v3_v3(cdd->prev.location_world_valid, selem->location_world);
490         }
491         copy_v3_v3(cdd->prev.location_world, selem->location_world);
492
493         float len_sq = len_squared_v2v2(cdd->prev.mouse, selem->mval);
494         copy_v2_v2(cdd->prev.mouse, selem->mval);
495
496         if (cdd->sample.use_substeps && cdd->prev.selem) {
497                 const struct StrokeElem selem_target = *selem;
498                 struct StrokeElem *selem_new_last = selem;
499                 if (len_sq >= SQUARE(STROKE_SAMPLE_DIST_MAX_PX)) {
500                         int n = (int)ceil(sqrt((double)len_sq)) / STROKE_SAMPLE_DIST_MAX_PX ;
501
502                         for (int i = 1; i < n; i++) {
503                                 struct StrokeElem *selem_new = selem_new_last;
504                                 stroke_elem_interp(selem_new, cdd->prev.selem, &selem_target, (float)i / n);
505
506                                 const bool is_depth_found_substep = stroke_elem_project_fallback_elem(
507                                         cdd, cdd->prev.location_world_valid, selem_new);
508                                 if (is_depth_found == false) {
509                                         if (is_depth_found_substep) {
510                                                 copy_v3_v3(cdd->prev.location_world_valid, selem_new->location_world);
511                                         }
512                                 }
513
514                                 selem_new_last = BLI_mempool_calloc(cdd->stroke_elem_pool);
515                         }
516                 }
517                 selem = selem_new_last;
518                 *selem_new_last = selem_target;
519         }
520
521         cdd->prev.selem = selem;
522
523         ED_region_tag_redraw(cdd->vc.ar);
524 }
525
526 static void curve_draw_event_add_first(wmOperator *op, const wmEvent *event)
527 {
528         struct CurveDrawData *cdd = op->customdata;
529         const CurvePaintSettings *cps = &cdd->vc.scene->toolsettings->curve_paint_settings;
530
531         /* add first point */
532         curve_draw_event_add(op, event);
533
534         if ((cps->depth_mode == CURVE_PAINT_PROJECT_SURFACE) && cdd->project.use_depth &&
535             (cps->flag & CURVE_PAINT_FLAG_DEPTH_STROKE_ENDPOINTS))
536         {
537                 RegionView3D *rv3d = cdd->vc.rv3d;
538
539                 cdd->project.use_depth = false;
540                 cdd->project.use_plane = true;
541
542                 float normal[3] = {0.0f};
543                 if (ELEM(cps->surface_plane,
544                          CURVE_PAINT_SURFACE_PLANE_NORMAL_VIEW,
545                          CURVE_PAINT_SURFACE_PLANE_NORMAL_SURFACE))
546                 {
547                         if (ED_view3d_depth_read_cached_normal(&cdd->vc, event->mval, normal)) {
548                                 if (cps->surface_plane == CURVE_PAINT_SURFACE_PLANE_NORMAL_VIEW) {
549                                         float cross_a[3], cross_b[3];
550                                         cross_v3_v3v3(cross_a, rv3d->viewinv[2], normal);
551                                         cross_v3_v3v3(cross_b, normal, cross_a);
552                                         copy_v3_v3(normal, cross_b);
553                                 }
554                         }
555                 }
556
557                 /* CURVE_PAINT_SURFACE_PLANE_VIEW or fallback */
558                 if (is_zero_v3(normal)) {
559                         copy_v3_v3(normal, rv3d->viewinv[2]);
560                 }
561
562                 normalize_v3_v3(cdd->project.plane, normal);
563                 cdd->project.plane[3] = -dot_v3v3(cdd->project.plane, cdd->prev.location_world_valid);
564
565                 /* Special case for when we only have offset applied on the first-hit,
566                  * the remaining stroke must be offset too. */
567                 if (cdd->project.surface_offset != 0.0f) {
568                         const float mval_fl[2] = {UNPACK2(event->mval)};
569
570                         float location_no_offset[3];
571
572                         if (stroke_elem_project(
573                                 cdd, event->mval, mval_fl, 0.0f, 0.0f,
574                                 location_no_offset, NULL))
575                         {
576                                 sub_v3_v3v3(cdd->project.offset, cdd->prev.location_world_valid, location_no_offset);
577                                 if (!is_zero_v3(cdd->project.offset)) {
578                                         cdd->project.use_offset = true;
579                                 }
580                         }
581                 }
582                 /* end special case */
583
584         }
585
586         cdd->init_event_type = event->type;
587         cdd->state = CURVE_DRAW_PAINTING;
588 }
589
590 static bool curve_draw_init(bContext *C, wmOperator *op, bool is_invoke)
591 {
592         BLI_assert(op->customdata == NULL);
593
594         struct CurveDrawData *cdd = MEM_callocN(sizeof(*cdd), __func__);
595
596         cdd->depsgraph = CTX_data_depsgraph(C);
597
598         if (is_invoke) {
599                 ED_view3d_viewcontext_init(C, &cdd->vc);
600                 if (ELEM(NULL, cdd->vc.ar, cdd->vc.rv3d, cdd->vc.v3d, cdd->vc.win, cdd->vc.scene)) {
601                         MEM_freeN(cdd);
602                         BKE_report(op->reports, RPT_ERROR, "Unable to access 3D viewport");
603                         return false;
604                 }
605         }
606         else {
607                 cdd->vc.bmain = CTX_data_main(C);
608                 cdd->vc.depsgraph = CTX_data_depsgraph(C);
609                 cdd->vc.scene = CTX_data_scene(C);
610                 cdd->vc.view_layer = CTX_data_view_layer(C);
611                 cdd->vc.obedit = CTX_data_edit_object(C);
612         }
613
614         op->customdata = cdd;
615
616         const CurvePaintSettings *cps = &cdd->vc.scene->toolsettings->curve_paint_settings;
617
618         cdd->curve_type = cps->curve_type;
619
620         cdd->radius.min = cps->radius_min;
621         cdd->radius.max = cps->radius_max;
622         cdd->radius.range = cps->radius_max - cps->radius_min;
623         cdd->project.surface_offset = cps->surface_offset;
624         cdd->project.use_surface_offset_absolute = (cps->flag & CURVE_PAINT_FLAG_DEPTH_STROKE_OFFSET_ABS) != 0;
625
626         cdd->stroke_elem_pool = BLI_mempool_create(
627                 sizeof(struct StrokeElem), 0, 512, BLI_MEMPOOL_ALLOW_ITER);
628
629         return true;
630 }
631
632
633 static void curve_draw_exit(wmOperator *op)
634 {
635         struct CurveDrawData *cdd = op->customdata;
636         if (cdd) {
637                 if (cdd->draw_handle_view) {
638                         ED_region_draw_cb_exit(cdd->vc.ar->type, cdd->draw_handle_view);
639                         WM_cursor_modal_restore(cdd->vc.win);
640                 }
641
642                 if (cdd->stroke_elem_pool) {
643                         BLI_mempool_destroy(cdd->stroke_elem_pool);
644                 }
645
646                 MEM_freeN(cdd);
647                 op->customdata = NULL;
648         }
649 }
650
651 /**
652  * Initialize values before calling 'exec' (when running interactively).
653  */
654 static void curve_draw_exec_precalc(wmOperator *op)
655 {
656         struct CurveDrawData *cdd = op->customdata;
657         const CurvePaintSettings *cps = &cdd->vc.scene->toolsettings->curve_paint_settings;
658         PropertyRNA *prop;
659
660         prop = RNA_struct_find_property(op->ptr, "fit_method");
661         if (!RNA_property_is_set(op->ptr, prop)) {
662                 RNA_property_enum_set(op->ptr, prop, cps->fit_method);
663         }
664
665         prop = RNA_struct_find_property(op->ptr, "corner_angle");
666         if (!RNA_property_is_set(op->ptr, prop)) {
667                 const float corner_angle = (cps->flag & CURVE_PAINT_FLAG_CORNERS_DETECT) ? cps->corner_angle : (float)M_PI;
668                 RNA_property_float_set(op->ptr, prop, corner_angle);
669         }
670
671         prop = RNA_struct_find_property(op->ptr, "error_threshold");
672         if (!RNA_property_is_set(op->ptr, prop)) {
673
674                 /* error isnt set so we'll have to calculate it from the pixel values */
675                 BLI_mempool_iter iter;
676                 const struct StrokeElem *selem, *selem_prev;
677
678                 float len_3d = 0.0f, len_2d = 0.0f;
679                 float scale_px;  /* pixel to local space scale */
680
681                 int i = 0;
682                 BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
683                 selem_prev = BLI_mempool_iterstep(&iter);
684                 for (selem = BLI_mempool_iterstep(&iter); selem; selem = BLI_mempool_iterstep(&iter), i++) {
685                         len_3d += len_v3v3(selem->location_local, selem_prev->location_local);
686                         len_2d += len_v2v2(selem->mval, selem_prev->mval);
687                         selem_prev = selem;
688                 }
689                 scale_px = ((len_3d > 0.0f) && (len_2d > 0.0f)) ?  (len_3d / len_2d) : 0.0f;
690                 float error_threshold = (cps->error_threshold * U.pixelsize) * scale_px;
691                 RNA_property_float_set(op->ptr, prop, error_threshold);
692         }
693
694         prop = RNA_struct_find_property(op->ptr, "use_cyclic");
695         if (!RNA_property_is_set(op->ptr, prop)) {
696                 bool use_cyclic = false;
697
698                 if (BLI_mempool_len(cdd->stroke_elem_pool) > 2) {
699                         BLI_mempool_iter iter;
700                         const struct StrokeElem *selem, *selem_first, *selem_last;
701
702                         BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
703                         selem_first = selem_last = BLI_mempool_iterstep(&iter);
704                         for (selem = BLI_mempool_iterstep(&iter); selem; selem = BLI_mempool_iterstep(&iter)) {
705                                 selem_last = selem;
706                         }
707
708                         if (len_squared_v2v2(
709                                 selem_first->mval,
710                                 selem_last->mval) <= SQUARE(STROKE_CYCLIC_DIST_PX * U.pixelsize))
711                         {
712                                 use_cyclic = true;
713                         }
714                 }
715
716                 RNA_property_boolean_set(op->ptr, prop, use_cyclic);
717         }
718
719
720         if ((cps->radius_taper_start != 0.0f) ||
721             (cps->radius_taper_end   != 0.0f))
722         {
723                 /* note, we could try to de-duplicate the length calculations above */
724                 const int stroke_len = BLI_mempool_len(cdd->stroke_elem_pool);
725
726                 BLI_mempool_iter iter;
727                 struct StrokeElem *selem, *selem_prev;
728
729                 float *lengths = MEM_mallocN(sizeof(float) * stroke_len, __func__);
730                 struct StrokeElem **selem_array = MEM_mallocN(sizeof(*selem_array) * stroke_len, __func__);
731                 lengths[0] = 0.0f;
732
733                 float len_3d = 0.0f;
734
735                 int i = 1;
736                 BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
737                 selem_prev = BLI_mempool_iterstep(&iter);
738                 selem_array[0] = selem_prev;
739                 for (selem = BLI_mempool_iterstep(&iter); selem; selem = BLI_mempool_iterstep(&iter), i++) {
740                         const float len_3d_segment = len_v3v3(selem->location_local, selem_prev->location_local);
741                         len_3d += len_3d_segment;
742                         lengths[i] = len_3d;
743                         selem_array[i] = selem;
744                         selem_prev = selem;
745                 }
746
747                 if (cps->radius_taper_start != 0.0f) {
748                         const float len_taper_max = cps->radius_taper_start * len_3d;
749                         for (i = 0; i < stroke_len && lengths[i] < len_taper_max; i++) {
750                                 const float pressure_new = selem_array[i]->pressure * (lengths[i] / len_taper_max);
751                                 stroke_elem_pressure_set(cdd, selem_array[i], pressure_new);
752                         }
753                 }
754
755                 if (cps->radius_taper_end != 0.0f) {
756                         const float len_taper_max = cps->radius_taper_end * len_3d;
757                         const float len_taper_min = len_3d - len_taper_max;
758                         for (i = stroke_len - 1; i > 0 && lengths[i] > len_taper_min; i--) {
759                                 const float pressure_new = selem_array[i]->pressure * ((len_3d - lengths[i]) / len_taper_max);
760                                 stroke_elem_pressure_set(cdd, selem_array[i], pressure_new);
761                         }
762                 }
763
764                 MEM_freeN(lengths);
765                 MEM_freeN(selem_array);
766         }
767 }
768
769 static int curve_draw_exec(bContext *C, wmOperator *op)
770 {
771         if (op->customdata == NULL) {
772                 if (!curve_draw_init(C, op, false)) {
773                         return OPERATOR_CANCELLED;
774                 }
775         }
776
777         struct CurveDrawData *cdd = op->customdata;
778
779         const CurvePaintSettings *cps = &cdd->vc.scene->toolsettings->curve_paint_settings;
780         Object *obedit = cdd->vc.obedit;
781         Curve *cu = obedit->data;
782         ListBase *nurblist = object_editcurve_get(obedit);
783
784         int stroke_len = BLI_mempool_len(cdd->stroke_elem_pool);
785
786         const bool is_3d = (cu->flag & CU_3D) != 0;
787         invert_m4_m4(obedit->imat, obedit->obmat);
788
789         if (BLI_mempool_len(cdd->stroke_elem_pool) == 0) {
790                 curve_draw_stroke_from_operator(op);
791                 stroke_len = BLI_mempool_len(cdd->stroke_elem_pool);
792         }
793
794         ED_curve_deselect_all(cu->editnurb);
795
796         const float radius_min = cps->radius_min;
797         const float radius_max = cps->radius_max;
798         const float radius_range = cps->radius_max - cps->radius_min;
799
800         Nurb *nu = MEM_callocN(sizeof(Nurb), __func__);
801         nu->pntsv = 0;
802         nu->resolu = cu->resolu;
803         nu->resolv = cu->resolv;
804         nu->flag |= CU_SMOOTH;
805
806         const bool use_pressure_radius =
807                 (cps->flag & CURVE_PAINT_FLAG_PRESSURE_RADIUS) ||
808                 ((cps->radius_taper_start != 0.0f) ||
809                  (cps->radius_taper_end   != 0.0f));
810
811         if (cdd->curve_type == CU_BEZIER) {
812                 nu->type = CU_BEZIER;
813
814 #ifdef USE_SPLINE_FIT
815
816                 /* Allow to interpolate multiple channels */
817                 int dims = 3;
818                 struct {
819                         int radius;
820                 } coords_indices;
821                 coords_indices.radius = use_pressure_radius ? dims++ : -1;
822
823                 float *coords = MEM_mallocN(sizeof(*coords) * stroke_len * dims, __func__);
824
825                 float       *cubic_spline = NULL;
826                 unsigned int cubic_spline_len = 0;
827
828                 /* error in object local space */
829                 const int fit_method = RNA_enum_get(op->ptr, "fit_method");
830                 const float error_threshold = RNA_float_get(op->ptr, "error_threshold");
831                 const float corner_angle = RNA_float_get(op->ptr, "corner_angle");
832                 const bool use_cyclic = RNA_boolean_get(op->ptr, "use_cyclic");
833
834                 {
835                         BLI_mempool_iter iter;
836                         const struct StrokeElem *selem;
837                         float *co = coords;
838
839                         BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
840                         for (selem = BLI_mempool_iterstep(&iter); selem; selem = BLI_mempool_iterstep(&iter), co += dims) {
841                                 copy_v3_v3(co, selem->location_local);
842                                 if (coords_indices.radius != -1) {
843                                         co[coords_indices.radius] = selem->pressure;
844                                 }
845
846                                 /* remove doubles */
847                                 if ((co != coords) && UNLIKELY(memcmp(co, co - dims, sizeof(float) * dims) == 0)) {
848                                         co -= dims;
849                                         stroke_len--;
850                                 }
851                         }
852                 }
853
854                 unsigned int *corners = NULL;
855                 unsigned int  corners_len = 0;
856
857                 if ((fit_method == CURVE_PAINT_FIT_METHOD_SPLIT) && (corner_angle < (float)M_PI)) {
858                         /* this could be configurable... */
859                         const float corner_radius_min = error_threshold / 8;
860                         const float corner_radius_max = error_threshold * 2;
861                         const unsigned int samples_max = 16;
862
863                         curve_fit_corners_detect_fl(
864                                 coords, stroke_len, dims,
865                                 corner_radius_min, corner_radius_max,
866                                 samples_max, corner_angle,
867                                 &corners, &corners_len);
868                 }
869
870                 unsigned int *corners_index = NULL;
871                 unsigned int  corners_index_len = 0;
872                 unsigned int  calc_flag = CURVE_FIT_CALC_HIGH_QUALIY;
873
874                 if ((stroke_len > 2) && use_cyclic) {
875                         calc_flag |= CURVE_FIT_CALC_CYCLIC;
876                 }
877
878                 int result;
879                 if (fit_method == CURVE_PAINT_FIT_METHOD_REFIT) {
880                         result = curve_fit_cubic_to_points_refit_fl(
881                                 coords, stroke_len, dims, error_threshold, calc_flag,
882                                 NULL, 0, corner_angle,
883                                 &cubic_spline, &cubic_spline_len,
884                                 NULL,
885                                 &corners_index, &corners_index_len);
886                 }
887                 else {
888                         result = curve_fit_cubic_to_points_fl(
889                                 coords, stroke_len, dims, error_threshold, calc_flag,
890                                 corners, corners_len,
891                                 &cubic_spline, &cubic_spline_len,
892                                 NULL,
893                                 &corners_index, &corners_index_len);
894                 }
895
896                 MEM_freeN(coords);
897                 if (corners) {
898                         free(corners);
899                 }
900
901                 if (result == 0) {
902                         nu->pntsu = cubic_spline_len;
903                         nu->bezt = MEM_callocN(sizeof(BezTriple) * nu->pntsu, __func__);
904
905                         float *co = cubic_spline;
906                         BezTriple *bezt = nu->bezt;
907                         for (int j = 0; j < cubic_spline_len; j++, bezt++, co += (dims * 3)) {
908                                 const float *handle_l = co + (dims * 0);
909                                 const float *pt       = co + (dims * 1);
910                                 const float *handle_r = co + (dims * 2);
911
912                                 copy_v3_v3(bezt->vec[0], handle_l);
913                                 copy_v3_v3(bezt->vec[1], pt);
914                                 copy_v3_v3(bezt->vec[2], handle_r);
915
916                                 if (coords_indices.radius != -1) {
917                                         bezt->radius = (pt[coords_indices.radius] * cdd->radius.range) + cdd->radius.min;
918                                 }
919                                 else {
920                                         bezt->radius = radius_max;
921                                 }
922
923                                 bezt->h1 = bezt->h2 = HD_ALIGN;  /* will set to free in second pass */
924                                 bezt->f1 = bezt->f2 = bezt->f3 = SELECT;
925                         }
926
927                         if (corners_index) {
928                                 /* ignore the first and last */
929                                 unsigned int i_start = 0, i_end = corners_index_len;
930
931                                 if ((corners_index_len >= 2) &&
932                                     (calc_flag & CURVE_FIT_CALC_CYCLIC) == 0)
933                                 {
934                                         i_start += 1;
935                                         i_end   -= 1;
936                                 }
937
938                                 for (unsigned int i = i_start; i < i_end; i++) {
939                                         bezt = &nu->bezt[corners_index[i]];
940                                         bezt->h1 = bezt->h2 = HD_FREE;
941                                 }
942                         }
943
944                         if (calc_flag & CURVE_FIT_CALC_CYCLIC) {
945                                 nu->flagu |= CU_NURB_CYCLIC;
946                         }
947                 }
948
949                 if (corners_index) {
950                         free(corners_index);
951                 }
952
953                 if (cubic_spline) {
954                         free(cubic_spline);
955                 }
956
957 #else
958                 nu->pntsu = stroke_len;
959                 nu->bezt = MEM_callocN(nu->pntsu * sizeof(BezTriple), __func__);
960
961                 BezTriple *bezt = nu->bezt;
962
963                 {
964                         BLI_mempool_iter iter;
965                         const struct StrokeElem *selem;
966
967                         BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
968                         for (selem = BLI_mempool_iterstep(&iter); selem; selem = BLI_mempool_iterstep(&iter)) {
969                                 copy_v3_v3(bezt->vec[1], selem->location_local);
970                                 if (!is_3d) {
971                                         bezt->vec[1][2] = 0.0f;
972                                 }
973
974                                 if (use_pressure_radius) {
975                                         bezt->radius = selem->pressure;
976                                 }
977                                 else {
978                                         bezt->radius = radius_max;
979                                 }
980
981                                 bezt->h1 = bezt->h2 = HD_AUTO;
982
983                                 bezt->f1 |= SELECT;
984                                 bezt->f2 |= SELECT;
985                                 bezt->f3 |= SELECT;
986
987                                 bezt++;
988                         }
989                 }
990 #endif
991
992                 BKE_nurb_handles_calc(nu);
993         }
994         else {  /* CU_POLY */
995                 BLI_mempool_iter iter;
996                 const struct StrokeElem *selem;
997
998                 nu->pntsu = stroke_len;
999                 nu->pntsv = 1;
1000                 nu->type = CU_POLY;
1001                 nu->bp = MEM_callocN(nu->pntsu * sizeof(BPoint), __func__);
1002
1003                 /* Misc settings. */
1004                 nu->resolu = cu->resolu;
1005                 nu->resolv = 1;
1006                 nu->orderu = 4;
1007                 nu->orderv = 1;
1008
1009                 BPoint *bp = nu->bp;
1010
1011                 BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
1012                 for (selem = BLI_mempool_iterstep(&iter); selem; selem = BLI_mempool_iterstep(&iter)) {
1013                         copy_v3_v3(bp->vec, selem->location_local);
1014                         if (!is_3d) {
1015                                 bp->vec[2] = 0.0f;
1016                         }
1017
1018                         if (use_pressure_radius) {
1019                                 bp->radius = (selem->pressure * radius_range) + radius_min;
1020                         }
1021                         else {
1022                                 bp->radius = cps->radius_max;
1023                         }
1024                         bp->f1 = SELECT;
1025                         bp->vec[3] = 1.0f;
1026
1027                         bp++;
1028                 }
1029
1030                 BKE_nurb_knot_calc_u(nu);
1031         }
1032
1033         BLI_addtail(nurblist, nu);
1034
1035         BKE_curve_nurb_active_set(cu, nu);
1036         cu->actvert = nu->pntsu - 1;
1037
1038         WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
1039         DEG_id_tag_update(obedit->data, 0);
1040
1041         curve_draw_exit(op);
1042
1043         return OPERATOR_FINISHED;
1044 }
1045
1046 static int curve_draw_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1047 {
1048         if (RNA_struct_property_is_set(op->ptr, "stroke")) {
1049                 return curve_draw_exec(C, op);
1050         }
1051
1052         if (!curve_draw_init(C, op, true)) {
1053                 return OPERATOR_CANCELLED;
1054         }
1055
1056         struct CurveDrawData *cdd = op->customdata;
1057
1058         const CurvePaintSettings *cps = &cdd->vc.scene->toolsettings->curve_paint_settings;
1059
1060         const bool is_modal = RNA_boolean_get(op->ptr, "wait_for_input");
1061
1062         /* fallback (incase we can't find the depth on first test) */
1063         {
1064                 const float mval_fl[2] = {UNPACK2(event->mval)};
1065                 float center[3];
1066                 negate_v3_v3(center, cdd->vc.rv3d->ofs);
1067                 ED_view3d_win_to_3d(cdd->vc.v3d, cdd->vc.ar, center, mval_fl, cdd->prev.location_world);
1068                 copy_v3_v3(cdd->prev.location_world_valid, cdd->prev.location_world);
1069         }
1070
1071         cdd->draw_handle_view = ED_region_draw_cb_activate(
1072                 cdd->vc.ar->type, curve_draw_stroke_3d, op, REGION_DRAW_POST_VIEW);
1073         WM_cursor_modal_set(cdd->vc.win, BC_PAINTBRUSHCURSOR);
1074
1075         {
1076                 View3D *v3d = cdd->vc.v3d;
1077                 RegionView3D *rv3d = cdd->vc.rv3d;
1078                 Object *obedit = cdd->vc.obedit;
1079                 Curve *cu = obedit->data;
1080
1081                 const float *plane_no = NULL;
1082                 const float *plane_co = NULL;
1083
1084                 if ((cu->flag & CU_3D) == 0) {
1085                         /* 2D overrides other options */
1086                         plane_co = obedit->obmat[3];
1087                         plane_no = obedit->obmat[2];
1088                         cdd->project.use_plane = true;
1089                 }
1090                 else {
1091                         if ((cps->depth_mode == CURVE_PAINT_PROJECT_SURFACE) &&
1092                             (v3d->shading.type > OB_WIRE))
1093                         {
1094                                 /* needed or else the draw matrix can be incorrect */
1095                                 view3d_operator_needs_opengl(C);
1096
1097                                 ED_view3d_autodist_init(cdd->vc.depsgraph, cdd->vc.ar, cdd->vc.v3d, 0);
1098
1099                                 if (cdd->vc.rv3d->depths) {
1100                                         cdd->vc.rv3d->depths->damaged = true;
1101                                 }
1102
1103                                 ED_view3d_depth_update(cdd->vc.ar);
1104
1105                                 if (cdd->vc.rv3d->depths != NULL) {
1106                                         cdd->project.use_depth = true;
1107                                 }
1108                                 else {
1109                                         BKE_report(op->reports, RPT_WARNING, "Unable to access depth buffer, using view plane");
1110                                         cdd->project.use_depth = false;
1111                                 }
1112                         }
1113
1114                         /* use view plane (when set or as fallback when surface can't be found) */
1115                         if (cdd->project.use_depth == false) {
1116                                 plane_co = ED_view3d_cursor3d_get(cdd->vc.scene, v3d)->location;
1117                                 plane_no = rv3d->viewinv[2];
1118                                 cdd->project.use_plane = true;
1119                         }
1120
1121                         if (cdd->project.use_depth && (cdd->curve_type != CU_POLY)) {
1122                                 cdd->sample.use_substeps = true;
1123                         }
1124                 }
1125
1126                 if (cdd->project.use_plane) {
1127                         normalize_v3_v3(cdd->project.plane, plane_no);
1128                         cdd->project.plane[3] = -dot_v3v3(cdd->project.plane, plane_co);
1129                 }
1130         }
1131
1132         if (is_modal == false) {
1133                 curve_draw_event_add_first(op, event);
1134         }
1135
1136         /* add temp handler */
1137         WM_event_add_modal_handler(C, op);
1138
1139         return OPERATOR_RUNNING_MODAL;
1140 }
1141
1142 static void curve_draw_cancel(bContext *UNUSED(C), wmOperator *op)
1143 {
1144         curve_draw_exit(op);
1145 }
1146
1147
1148 /* Modal event handling of frame changing */
1149 static int curve_draw_modal(bContext *C, wmOperator *op, const wmEvent *event)
1150 {
1151         int ret = OPERATOR_RUNNING_MODAL;
1152         struct CurveDrawData *cdd = op->customdata;
1153
1154         UNUSED_VARS(C, op);
1155
1156         if (event->type == cdd->init_event_type) {
1157                 if (event->val == KM_RELEASE) {
1158                         ED_region_tag_redraw(cdd->vc.ar);
1159
1160                         curve_draw_exec_precalc(op);
1161
1162                         curve_draw_stroke_to_operator(op);
1163
1164                         curve_draw_exec(C, op);
1165
1166                         return OPERATOR_FINISHED;
1167                 }
1168         }
1169         else if (ELEM(event->type, ESCKEY, RIGHTMOUSE)) {
1170                 ED_region_tag_redraw(cdd->vc.ar);
1171                 curve_draw_cancel(C, op);
1172                 return OPERATOR_CANCELLED;
1173         }
1174         else if (ELEM(event->type, LEFTMOUSE)) {
1175                 if (event->val == KM_PRESS) {
1176                         curve_draw_event_add_first(op, event);
1177                 }
1178         }
1179         else if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
1180                 if (cdd->state == CURVE_DRAW_PAINTING) {
1181                         const float mval_fl[2] = {UNPACK2(event->mval)};
1182                         if (len_squared_v2v2(mval_fl, cdd->prev.mouse) > SQUARE(STROKE_SAMPLE_DIST_MIN_PX)) {
1183                                 curve_draw_event_add(op, event);
1184                         }
1185                 }
1186         }
1187
1188         return ret;
1189 }
1190
1191 void CURVE_OT_draw(wmOperatorType *ot)
1192 {
1193         /* identifiers */
1194         ot->name = "Draw Curve";
1195         ot->idname = "CURVE_OT_draw";
1196         ot->description = "Draw a freehand spline";
1197
1198         /* api callbacks */
1199         ot->exec = curve_draw_exec;
1200         ot->invoke = curve_draw_invoke;
1201         ot->cancel = curve_draw_cancel;
1202         ot->modal = curve_draw_modal;
1203         ot->poll = ED_operator_editcurve;
1204
1205         /* flags */
1206         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1207
1208         /* properties */
1209         PropertyRNA *prop;
1210
1211         prop = RNA_def_float_distance(
1212                 ot->srna, "error_threshold", 0.0f, 0.0f, 10.0f, "Error",
1213                 "Error distance threshold (in object units)",
1214                 0.0001f, 10.0f);
1215         RNA_def_property_ui_range(prop, 0.0, 10, 1, 4);
1216
1217         RNA_def_enum(ot->srna, "fit_method", rna_enum_curve_fit_method_items, CURVE_PAINT_FIT_METHOD_REFIT,
1218                      "Fit Method", "");
1219
1220         prop = RNA_def_float_distance(
1221                 ot->srna, "corner_angle", DEG2RADF(70.0f), 0.0f, M_PI, "Corner Angle", "", 0.0f, M_PI);
1222         RNA_def_property_subtype(prop, PROP_ANGLE);
1223
1224         prop = RNA_def_boolean(ot->srna, "use_cyclic", true, "Cyclic", "");
1225         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1226
1227         prop = RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
1228         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1229
1230         prop = RNA_def_boolean(ot->srna, "wait_for_input", true, "Wait for Input", "");
1231         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1232 }
1233
1234 /** \} */