Cleanup: comment line length (editors)
[blender.git] / source / blender / editors / sculpt_paint / sculpt.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) 2006 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  * Implements the Sculpt Mode tools
28  *
29  */
30
31 /** \file blender/editors/sculpt_paint/sculpt.c
32  *  \ingroup edsculpt
33  */
34
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_math.h"
39 #include "BLI_blenlib.h"
40 #include "BLI_dial_2d.h"
41 #include "BLI_task.h"
42 #include "BLI_utildefines.h"
43 #include "BLI_ghash.h"
44
45 #include "BLT_translation.h"
46
47 #include "DNA_customdata_types.h"
48 #include "DNA_mesh_types.h"
49 #include "DNA_meshdata_types.h"
50 #include "DNA_node_types.h"
51 #include "DNA_object_types.h"
52 #include "DNA_scene_types.h"
53 #include "DNA_brush_types.h"
54
55 #include "BKE_pbvh.h"
56 #include "BKE_brush.h"
57 #include "BKE_ccg.h"
58 #include "BKE_context.h"
59 #include "BKE_depsgraph.h"
60 #include "BKE_global.h"
61 #include "BKE_image.h"
62 #include "BKE_key.h"
63 #include "BKE_library.h"
64 #include "BKE_main.h"
65 #include "BKE_mesh.h"
66 #include "BKE_mesh_mapping.h"
67 #include "BKE_modifier.h"
68 #include "BKE_multires.h"
69 #include "BKE_paint.h"
70 #include "BKE_report.h"
71 #include "BKE_node.h"
72 #include "BKE_object.h"
73 #include "BKE_subsurf.h"
74 #include "BKE_colortools.h"
75
76 #include "WM_api.h"
77 #include "WM_types.h"
78
79 #include "ED_sculpt.h"
80 #include "ED_object.h"
81 #include "ED_screen.h"
82 #include "ED_view3d.h"
83 #include "paint_intern.h"
84 #include "sculpt_intern.h"
85
86 #include "RNA_access.h"
87 #include "RNA_define.h"
88
89 #include "GPU_buffers.h"
90 #include "GPU_extensions.h"
91
92 #include "UI_interface.h"
93 #include "UI_resources.h"
94
95 #include "bmesh.h"
96 #include "bmesh_tools.h"
97
98 #include <math.h>
99 #include <stdlib.h>
100 #include <string.h>
101
102 /** \name Tool Capabilities
103  *
104  * Avoid duplicate checks, internal logic only,
105  * share logic with #rna_def_sculpt_capabilities where possible.
106  *
107  * \{ */
108
109 /* Check if there are any active modifiers in stack
110  * (used for flushing updates at enter/exit sculpt mode) */
111 static bool sculpt_has_active_modifiers(Scene *scene, Object *ob)
112 {
113         ModifierData *md;
114         VirtualModifierData virtualModifierData;
115
116         md = modifiers_getVirtualModifierList(ob, &virtualModifierData);
117
118         /* exception for shape keys because we can edit those */
119         for (; md; md = md->next) {
120                 if (modifier_isEnabled(scene, md, eModifierMode_Realtime))
121                         return 1;
122         }
123
124         return 0;
125 }
126
127 static bool sculpt_tool_needs_original(const char sculpt_tool)
128 {
129         return ELEM(sculpt_tool,
130                     SCULPT_TOOL_GRAB,
131                     SCULPT_TOOL_ROTATE,
132                     SCULPT_TOOL_THUMB,
133                     SCULPT_TOOL_LAYER);
134 }
135
136 static bool sculpt_tool_is_proxy_used(const char sculpt_tool)
137 {
138         return ELEM(sculpt_tool,
139                     SCULPT_TOOL_SMOOTH,
140                     SCULPT_TOOL_LAYER);
141 }
142
143 /**
144  * Test whether the #StrokeCache.sculpt_normal needs update in #do_brush_action
145  */
146 static int sculpt_brush_needs_normal(const Brush *brush, float normal_weight)
147 {
148         return ((SCULPT_TOOL_HAS_NORMAL_WEIGHT(brush->sculpt_tool) &&
149                  (normal_weight > 0.0f)) ||
150
151                 ELEM(brush->sculpt_tool,
152                      SCULPT_TOOL_BLOB,
153                      SCULPT_TOOL_CREASE,
154                      SCULPT_TOOL_DRAW,
155                      SCULPT_TOOL_LAYER,
156                      SCULPT_TOOL_NUDGE,
157                      SCULPT_TOOL_ROTATE,
158                      SCULPT_TOOL_THUMB) ||
159
160                 (brush->mtex.brush_map_mode == MTEX_MAP_MODE_AREA));
161 }
162 /** \} */
163
164 static bool sculpt_brush_needs_rake_rotation(const Brush *brush)
165 {
166         return SCULPT_TOOL_HAS_RAKE(brush->sculpt_tool) && (brush->rake_factor != 0.0f);
167 }
168
169 typedef enum StrokeFlags {
170         CLIP_X = 1,
171         CLIP_Y = 2,
172         CLIP_Z = 4
173 } StrokeFlags;
174
175 /************** Access to original unmodified vertex data *************/
176
177 typedef struct {
178         BMLog *bm_log;
179
180         SculptUndoNode *unode;
181         float (*coords)[3];
182         short (*normals)[3];
183         const float *vmasks;
184
185         /* Original coordinate, normal, and mask */
186         const float *co;
187         const short *no;
188         float mask;
189 } SculptOrigVertData;
190
191
192 /* Initialize a SculptOrigVertData for accessing original vertex data;
193  * handles BMesh, mesh, and multires */
194 static void sculpt_orig_vert_data_unode_init(SculptOrigVertData *data,
195                                              Object *ob,
196                                              SculptUndoNode *unode)
197 {
198         SculptSession *ss = ob->sculpt;
199         BMesh *bm = ss->bm;
200
201         memset(data, 0, sizeof(*data));
202         data->unode = unode;
203
204         if (bm) {
205                 data->bm_log = ss->bm_log;
206         }
207         else {
208                 data->coords = data->unode->co;
209                 data->normals = data->unode->no;
210                 data->vmasks = data->unode->mask;
211         }
212 }
213
214 /* Initialize a SculptOrigVertData for accessing original vertex data;
215  * handles BMesh, mesh, and multires */
216 static void sculpt_orig_vert_data_init(SculptOrigVertData *data,
217                                        Object *ob,
218                                        PBVHNode *node)
219 {
220         SculptUndoNode *unode;
221         unode = sculpt_undo_push_node(ob, node, SCULPT_UNDO_COORDS);
222         sculpt_orig_vert_data_unode_init(data, ob, unode);
223 }
224
225 /* Update a SculptOrigVertData for a particular vertex from the PBVH
226  * iterator */
227 static void sculpt_orig_vert_data_update(SculptOrigVertData *orig_data,
228                                          PBVHVertexIter *iter)
229 {
230         if (orig_data->unode->type == SCULPT_UNDO_COORDS) {
231                 if (orig_data->bm_log) {
232                         BM_log_original_vert_data(
233                                 orig_data->bm_log, iter->bm_vert,
234                                 &orig_data->co, &orig_data->no);
235                 }
236                 else {
237                         orig_data->co = orig_data->coords[iter->i];
238                         orig_data->no = orig_data->normals[iter->i];
239                 }
240         }
241         else if (orig_data->unode->type == SCULPT_UNDO_MASK) {
242                 if (orig_data->bm_log) {
243                         orig_data->mask = BM_log_original_mask(orig_data->bm_log, iter->bm_vert);
244                 }
245                 else {
246                         orig_data->mask = orig_data->vmasks[iter->i];
247                 }
248         }
249 }
250
251 static void sculpt_rake_data_update(struct SculptRakeData *srd, const float co[3])
252 {
253         float rake_dist = len_v3v3(srd->follow_co, co);
254         if (rake_dist > srd->follow_dist) {
255                 interp_v3_v3v3(srd->follow_co, srd->follow_co, co, rake_dist - srd->follow_dist);
256         }
257 }
258
259
260 static void sculpt_rake_rotate(
261         const SculptSession *ss, const float sculpt_co[3], const float v_co[3], float factor, float r_delta[3])
262 {
263         float vec_rot[3];
264
265 #if 0
266         /* lerp */
267         sub_v3_v3v3(vec_rot, v_co, sculpt_co);
268         mul_qt_v3(ss->cache->rake_rotation_symmetry, vec_rot);
269         add_v3_v3(vec_rot, sculpt_co);
270         sub_v3_v3v3(r_delta, vec_rot, v_co);
271         mul_v3_fl(r_delta, factor);
272 #else
273         /* slerp */
274         float q_interp[4];
275         sub_v3_v3v3(vec_rot, v_co, sculpt_co);
276
277         copy_qt_qt(q_interp, ss->cache->rake_rotation_symmetry);
278         mul_fac_qt_fl(q_interp, factor);
279         mul_qt_v3(q_interp, vec_rot);
280
281         add_v3_v3(vec_rot, sculpt_co);
282         sub_v3_v3v3(r_delta, vec_rot, v_co);
283 #endif
284
285 }
286
287 /**
288  * Align the grab delta to the brush normal.
289  *
290  * \param grab_delta: Typically from `ss->cache->grab_delta_symmetry`.
291  */
292 static void sculpt_project_v3_normal_align(SculptSession *ss, const float normal_weight, float grab_delta[3])
293 {
294         /* signed to support grabbing in (to make a hole) as well as out. */
295         const float len_signed = dot_v3v3(ss->cache->sculpt_normal_symm, grab_delta);
296
297         /* this scale effectively projects the offset so dragging follows the cursor,
298          * as the normal points towards the view, the scale increases. */
299         float len_view_scale;
300         {
301                 float view_aligned_normal[3];
302                 project_plane_v3_v3v3(view_aligned_normal, ss->cache->sculpt_normal_symm, ss->cache->view_normal);
303                 len_view_scale = fabsf(dot_v3v3(view_aligned_normal, ss->cache->sculpt_normal_symm));
304                 len_view_scale = (len_view_scale > FLT_EPSILON) ? 1.0f / len_view_scale : 1.0f;
305         }
306
307         mul_v3_fl(grab_delta, 1.0f - normal_weight);
308         madd_v3_v3fl(grab_delta, ss->cache->sculpt_normal_symm, (len_signed * normal_weight) * len_view_scale);
309 }
310
311
312 /** \name SculptProjectVector
313  *
314  * Fast-path for #project_plane_v3_v3v3
315  *
316  * \{ */
317
318 typedef struct SculptProjectVector {
319         float plane[3];
320         float len_sq;
321         float len_sq_inv_neg;
322         bool  is_valid;
323
324 } SculptProjectVector;
325
326 /**
327  * \param plane: Direction, can be any length.
328  */
329 static void sculpt_project_v3_cache_init(
330         SculptProjectVector *spvc, const float plane[3])
331 {
332         copy_v3_v3(spvc->plane, plane);
333         spvc->len_sq = len_squared_v3(spvc->plane);
334         spvc->is_valid = (spvc->len_sq > FLT_EPSILON);
335         spvc->len_sq_inv_neg = (spvc->is_valid) ? -1.0f / spvc->len_sq : 0.0f;
336 }
337
338 /**
339  * Calculate the projection.
340  */
341 static void sculpt_project_v3(
342         const SculptProjectVector *spvc, const float vec[3],
343         float r_vec[3])
344 {
345 #if 0
346         project_plane_v3_v3v3(r_vec, vec, spvc->plane);
347 #else
348         /* inline the projection, cache `-1.0 / dot_v3_v3(v_proj, v_proj)` */
349         madd_v3_v3fl(r_vec, spvc->plane, dot_v3v3(vec, spvc->plane) * spvc->len_sq_inv_neg);
350 #endif
351 }
352
353 /** \} */
354
355
356 /**********************************************************************/
357
358 /* Returns true if the stroke will use dynamic topology, false
359  * otherwise.
360  *
361  * Factors: some brushes like grab cannot do dynamic topology.
362  * Others, like smooth, are better without. Same goes for alt-
363  * key smoothing. */
364 static bool sculpt_stroke_is_dynamic_topology(
365         const SculptSession *ss, const Brush *brush)
366 {
367         return ((BKE_pbvh_type(ss->pbvh) == PBVH_BMESH) &&
368
369                 (!ss->cache || (!ss->cache->alt_smooth)) &&
370
371                 /* Requires mesh restore, which doesn't work with
372                  * dynamic-topology */
373                 !(brush->flag & BRUSH_ANCHORED) &&
374                 !(brush->flag & BRUSH_DRAG_DOT) &&
375
376                 SCULPT_TOOL_HAS_DYNTOPO(brush->sculpt_tool));
377 }
378
379 /*** paint mesh ***/
380
381 static void paint_mesh_restore_co_task_cb(
382         void *__restrict userdata,
383         const int n,
384         const ParallelRangeTLS *__restrict UNUSED(tls))
385 {
386         SculptThreadedTaskData *data = userdata;
387         SculptSession *ss = data->ob->sculpt;
388
389         SculptUndoNode *unode;
390         SculptUndoType type = (data->brush->sculpt_tool == SCULPT_TOOL_MASK ? SCULPT_UNDO_MASK : SCULPT_UNDO_COORDS);
391
392         if (ss->bm) {
393                 unode = sculpt_undo_push_node(data->ob, data->nodes[n], type);
394         }
395         else {
396                 unode = sculpt_undo_get_node(data->nodes[n]);
397         }
398
399         if (unode) {
400                 PBVHVertexIter vd;
401                 SculptOrigVertData orig_data;
402
403                 sculpt_orig_vert_data_unode_init(&orig_data, data->ob, unode);
404
405                 BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
406                 {
407                         sculpt_orig_vert_data_update(&orig_data, &vd);
408
409                         if (orig_data.unode->type == SCULPT_UNDO_COORDS) {
410                                 copy_v3_v3(vd.co, orig_data.co);
411                                 if (vd.no)
412                                         copy_v3_v3_short(vd.no, orig_data.no);
413                                 else
414                                         normal_short_to_float_v3(vd.fno, orig_data.no);
415                         }
416                         else if (orig_data.unode->type == SCULPT_UNDO_MASK) {
417                                 *vd.mask = orig_data.mask;
418                         }
419
420                         if (vd.mvert)
421                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
422                 }
423                 BKE_pbvh_vertex_iter_end;
424
425                 BKE_pbvh_node_mark_update(data->nodes[n]);
426         }
427 }
428
429 static void paint_mesh_restore_co(Sculpt *sd, Object *ob)
430 {
431         SculptSession *ss = ob->sculpt;
432         Brush *brush = BKE_paint_brush(&sd->paint);
433
434         PBVHNode **nodes;
435         int totnode;
436
437         BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
438
439         /* Disable OpenMP when dynamic-topology is enabled. Otherwise, new entries might be inserted by
440          * sculpt_undo_push_node() into the GHash used internally by BM_log_original_vert_co() by a different thread.
441          * See T33787. */
442         SculptThreadedTaskData data = {
443                 .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
444         };
445
446         ParallelRangeSettings settings;
447         BLI_parallel_range_settings_defaults(&settings);
448         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && !ss->bm && totnode > SCULPT_THREADED_LIMIT);
449         BLI_task_parallel_range(
450                     0, totnode,
451                     &data,
452                     paint_mesh_restore_co_task_cb,
453                     &settings);
454
455         if (nodes)
456                 MEM_freeN(nodes);
457 }
458
459 /*** BVH Tree ***/
460
461 static void sculpt_extend_redraw_rect_previous(Object *ob, rcti *rect)
462 {
463         /* expand redraw rect with redraw rect from previous step to
464          * prevent partial-redraw issues caused by fast strokes. This is
465          * needed here (not in sculpt_flush_update) as it was before
466          * because redraw rectangle should be the same in both of
467          * optimized PBVH draw function and 3d view redraw (if not -- some
468          * mesh parts could disappear from screen (sergey) */
469         SculptSession *ss = ob->sculpt;
470
471         if (ss->cache) {
472                 if (!BLI_rcti_is_empty(&ss->cache->previous_r))
473                         BLI_rcti_union(rect, &ss->cache->previous_r);
474         }
475 }
476
477 /* Get a screen-space rectangle of the modified area */
478 bool sculpt_get_redraw_rect(ARegion *ar, RegionView3D *rv3d,
479                                    Object *ob, rcti *rect)
480 {
481         PBVH *pbvh = ob->sculpt->pbvh;
482         float bb_min[3], bb_max[3];
483
484         if (!pbvh)
485                 return 0;
486
487         BKE_pbvh_redraw_BB(pbvh, bb_min, bb_max);
488
489         /* convert 3D bounding box to screen space */
490         if (!paint_convert_bb_to_rect(rect,
491                                       bb_min,
492                                       bb_max,
493                                       ar,
494                                       rv3d,
495                                       ob))
496         {
497                 return 0;
498         }
499
500
501         return 1;
502 }
503
504 void ED_sculpt_redraw_planes_get(float planes[4][4], ARegion *ar,
505                                  RegionView3D *rv3d, Object *ob)
506 {
507         PBVH *pbvh = ob->sculpt->pbvh;
508         /* copy here, original will be used below */
509         rcti rect = ob->sculpt->cache->current_r;
510
511         sculpt_extend_redraw_rect_previous(ob, &rect);
512
513         paint_calc_redraw_planes(planes, ar, rv3d, ob, &rect);
514
515         /* we will draw this rect, so now we can set it as the previous partial rect.
516          * Note that we don't update with the union of previous/current (rect), only with
517          * the current. Thus we avoid the rectangle needlessly growing to include
518          * all the stroke area */
519         ob->sculpt->cache->previous_r = ob->sculpt->cache->current_r;
520
521         /* clear redraw flag from nodes */
522         if (pbvh)
523                 BKE_pbvh_update(pbvh, PBVH_UpdateRedraw, NULL);
524 }
525
526 /************************ Brush Testing *******************/
527
528 void sculpt_brush_test_init(SculptSession *ss, SculptBrushTest *test)
529 {
530         RegionView3D *rv3d = ss->cache->vc->rv3d;
531
532         test->radius_squared = ss->cache->radius_squared;
533         copy_v3_v3(test->location, ss->cache->location);
534         test->dist = 0.0f;   /* just for initialize */
535
536         /* Only for 2D projection. */
537         zero_v4(test->plane_view);
538         zero_v4(test->plane_tool);
539
540         test->mirror_symmetry_pass = ss->cache->mirror_symmetry_pass;
541
542         if (rv3d->rflag & RV3D_CLIPPING) {
543                 test->clip_rv3d = rv3d;
544         }
545         else {
546                 test->clip_rv3d = NULL;
547         }
548 }
549
550 BLI_INLINE bool sculpt_brush_test_clipping(const SculptBrushTest *test, const float co[3])
551 {
552         RegionView3D *rv3d = test->clip_rv3d;
553         if (!rv3d) {
554                 return false;
555         }
556         float symm_co[3];
557         flip_v3_v3(symm_co, co, test->mirror_symmetry_pass);
558         return ED_view3d_clipping_test(rv3d, symm_co, true);
559 }
560
561 bool sculpt_brush_test_sphere(SculptBrushTest *test, const float co[3])
562 {
563         float distsq = len_squared_v3v3(co, test->location);
564
565         if (distsq <= test->radius_squared) {
566                 if (sculpt_brush_test_clipping(test, co)) {
567                         return 0;
568                 }
569                 test->dist = sqrtf(distsq);
570                 return 1;
571         }
572         else {
573                 return 0;
574         }
575 }
576
577 bool sculpt_brush_test_sphere_sq(SculptBrushTest *test, const float co[3])
578 {
579         float distsq = len_squared_v3v3(co, test->location);
580
581         if (distsq <= test->radius_squared) {
582                 if (sculpt_brush_test_clipping(test, co)) {
583                         return 0;
584                 }
585                 test->dist = distsq;
586                 return 1;
587         }
588         else {
589                 return 0;
590         }
591 }
592
593 bool sculpt_brush_test_sphere_fast(const SculptBrushTest *test, const float co[3])
594 {
595         if (sculpt_brush_test_clipping(test, co)) {
596                 return 0;
597         }
598         return len_squared_v3v3(co, test->location) <= test->radius_squared;
599 }
600
601 bool sculpt_brush_test_circle_sq(SculptBrushTest *test, const float co[3])
602 {
603         float co_proj[3];
604         closest_to_plane_normalized_v3(co_proj, test->plane_view, co);
605         float distsq = len_squared_v3v3(co_proj, test->location);
606
607         if (distsq <= test->radius_squared) {
608                 if (sculpt_brush_test_clipping(test, co)) {
609                         return 0;
610                 }
611                 test->dist = distsq;
612                 return 1;
613         }
614         else {
615                 return 0;
616         }
617 }
618
619 bool sculpt_brush_test_cube(SculptBrushTest *test, const float co[3], float local[4][4])
620 {
621         float side = M_SQRT1_2;
622         float local_co[3];
623
624         if (sculpt_brush_test_clipping(test, co)) {
625                 return 0;
626         }
627
628         mul_v3_m4v3(local_co, local, co);
629
630         local_co[0] = fabsf(local_co[0]);
631         local_co[1] = fabsf(local_co[1]);
632         local_co[2] = fabsf(local_co[2]);
633
634         if (local_co[0] <= side && local_co[1] <= side && local_co[2] <= side) {
635                 float p = 4.0f;
636
637                 test->dist = ((powf(local_co[0], p) +
638                                powf(local_co[1], p) +
639                                powf(local_co[2], p)) / powf(side, p));
640
641                 return 1;
642         }
643         else {
644                 return 0;
645         }
646 }
647
648 SculptBrushTestFn sculpt_brush_test_init_with_falloff_shape(
649         SculptSession *ss, SculptBrushTest *test, char falloff_shape)
650 {
651         sculpt_brush_test_init(ss, test);
652         SculptBrushTestFn sculpt_brush_test_sq_fn;
653         if (falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE) {
654                 sculpt_brush_test_sq_fn = sculpt_brush_test_sphere_sq;
655         }
656         else {
657                 /* PAINT_FALLOFF_SHAPE_TUBE */
658                 plane_from_point_normal_v3(test->plane_view, test->location, ss->cache->view_normal);
659                 sculpt_brush_test_sq_fn = sculpt_brush_test_circle_sq;
660         }
661         return sculpt_brush_test_sq_fn;
662 }
663
664 const float *sculpt_brush_frontface_normal_from_falloff_shape(
665         SculptSession *ss, char falloff_shape)
666 {
667         if (falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE) {
668                 return ss->cache->sculpt_normal_symm;
669         }
670         else {
671                 /* PAINT_FALLOFF_SHAPE_TUBE */
672                 return ss->cache->view_normal;
673         }
674 }
675
676
677 static float frontface(const Brush *br, const float sculpt_normal[3],
678                        const short no[3], const float fno[3])
679 {
680         if (br->flag & BRUSH_FRONTFACE) {
681                 float dot;
682
683                 if (no) {
684                         float tmp[3];
685
686                         normal_short_to_float_v3(tmp, no);
687                         dot = dot_v3v3(tmp, sculpt_normal);
688                 }
689                 else {
690                         dot = dot_v3v3(fno, sculpt_normal);
691                 }
692                 return dot > 0 ? dot : 0;
693         }
694         else {
695                 return 1;
696         }
697 }
698
699 #if 0
700
701 static bool sculpt_brush_test_cyl(SculptBrushTest *test, float co[3], float location[3], const float area_no[3])
702 {
703         if (sculpt_brush_test_sphere_fast(test, co)) {
704                 float t1[3], t2[3], t3[3], dist;
705
706                 sub_v3_v3v3(t1, location, co);
707                 sub_v3_v3v3(t2, x2, location);
708
709                 cross_v3_v3v3(t3, area_no, t1);
710
711                 dist = len_v3(t3) / len_v3(t2);
712
713                 test->dist = dist;
714
715                 return 1;
716         }
717
718         return 0;
719 }
720
721 #endif
722
723 /* ===== Sculpting =====
724  *
725  */
726 static void flip_v3(float v[3], const char symm)
727 {
728         flip_v3_v3(v, v, symm);
729 }
730
731 static float calc_overlap(StrokeCache *cache, const char symm, const char axis, const float angle)
732 {
733         float mirror[3];
734         float distsq;
735
736         /* flip_v3_v3(mirror, cache->traced_location, symm); */
737         flip_v3_v3(mirror, cache->true_location, symm);
738
739         if (axis != 0) {
740                 float mat[3][3];
741                 axis_angle_to_mat3_single(mat, axis, angle);
742                 mul_m3_v3(mat, mirror);
743         }
744
745         /* distsq = len_squared_v3v3(mirror, cache->traced_location); */
746         distsq = len_squared_v3v3(mirror, cache->true_location);
747
748         if (distsq <= 4.0f * (cache->radius_squared))
749                 return (2.0f * (cache->radius) - sqrtf(distsq)) / (2.0f * (cache->radius));
750         else
751                 return 0;
752 }
753
754 static float calc_radial_symmetry_feather(Sculpt *sd, StrokeCache *cache, const char symm, const char axis)
755 {
756         int i;
757         float overlap;
758
759         overlap = 0;
760         for (i = 1; i < sd->radial_symm[axis - 'X']; ++i) {
761                 const float angle = 2 * M_PI * i / sd->radial_symm[axis - 'X'];
762                 overlap += calc_overlap(cache, symm, axis, angle);
763         }
764
765         return overlap;
766 }
767
768 static float calc_symmetry_feather(Sculpt *sd, StrokeCache *cache)
769 {
770         if (sd->paint.symmetry_flags & PAINT_SYMMETRY_FEATHER) {
771                 float overlap;
772                 int symm = cache->symmetry;
773                 int i;
774
775                 overlap = 0;
776                 for (i = 0; i <= symm; i++) {
777                         if (i == 0 || (symm & i && (symm != 5 || i != 3) && (symm != 6 || (i != 3 && i != 5)))) {
778
779                                 overlap += calc_overlap(cache, i, 0, 0);
780
781                                 overlap += calc_radial_symmetry_feather(sd, cache, i, 'X');
782                                 overlap += calc_radial_symmetry_feather(sd, cache, i, 'Y');
783                                 overlap += calc_radial_symmetry_feather(sd, cache, i, 'Z');
784                         }
785                 }
786
787                 return 1 / overlap;
788         }
789         else {
790                 return 1;
791         }
792 }
793
794 /** \name Calculate Normal and Center
795  *
796  * Calculate geometry surrounding the brush center.
797  * (optionally using original coordinates).
798  *
799  * Functions are:
800  * - #calc_area_center
801  * - #calc_area_normal
802  * - #calc_area_normal_and_center
803  *
804  * \note These are all _very_ similar, when changing one, check others.
805  * \{ */
806
807 static void calc_area_normal_and_center_task_cb(
808         void *__restrict userdata,
809         const int n,
810         const ParallelRangeTLS *__restrict UNUSED(tls))
811 {
812         SculptThreadedTaskData *data = userdata;
813         SculptSession *ss = data->ob->sculpt;
814         float (*area_nos)[3] = data->area_nos;
815         float (*area_cos)[3] = data->area_cos;
816
817         PBVHVertexIter vd;
818         SculptUndoNode *unode = NULL;
819
820         float private_co[2][3] = {{0.0f}};
821         float private_no[2][3] = {{0.0f}};
822         int   private_count[2] = {0};
823         bool use_original = false;
824
825         if (ss->cache->original) {
826                 unode = sculpt_undo_push_node(data->ob, data->nodes[n], SCULPT_UNDO_COORDS);
827                 use_original = (unode->co || unode->bm_entry);
828         }
829
830         SculptBrushTest test;
831         SculptBrushTestFn sculpt_brush_test_sq_fn =
832                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
833
834
835         /* when the mesh is edited we can't rely on original coords
836          * (original mesh may not even have verts in brush radius) */
837         if (use_original && data->has_bm_orco) {
838                 float (*orco_coords)[3];
839                 int   (*orco_tris)[3];
840                 int     orco_tris_num;
841                 int i;
842
843                 BKE_pbvh_node_get_bm_orco_data(data->nodes[n], &orco_tris, &orco_tris_num, &orco_coords);
844
845                 for (i = 0; i < orco_tris_num; i++) {
846                         const float *co_tri[3] = {
847                             orco_coords[orco_tris[i][0]],
848                             orco_coords[orco_tris[i][1]],
849                             orco_coords[orco_tris[i][2]],
850                         };
851                         float co[3];
852
853                         closest_on_tri_to_point_v3(co, test.location, UNPACK3(co_tri));
854
855                         if (sculpt_brush_test_sq_fn(&test, co)) {
856                                 float no[3];
857                                 int flip_index;
858
859                                 normal_tri_v3(no, UNPACK3(co_tri));
860
861                                 flip_index = (dot_v3v3(ss->cache->view_normal, no) <= 0.0f);
862                                 if (area_cos)
863                                         add_v3_v3(private_co[flip_index], co);
864                                 if (area_nos)
865                                         add_v3_v3(private_no[flip_index], no);
866                                 private_count[flip_index] += 1;
867                         }
868                 }
869         }
870         else {
871                 BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
872                 {
873                         const float *co;
874                         const short *no_s;  /* bm_vert only */
875
876                         if (use_original) {
877                                 if (unode->bm_entry) {
878                                         BM_log_original_vert_data(ss->bm_log, vd.bm_vert, &co, &no_s);
879                                 }
880                                 else {
881                                         co = unode->co[vd.i];
882                                         no_s = unode->no[vd.i];
883                                 }
884                         }
885                         else {
886                                 co = vd.co;
887                         }
888
889                         if (sculpt_brush_test_sq_fn(&test, co)) {
890                                 float no_buf[3];
891                                 const float *no;
892                                 int flip_index;
893
894                                 if (use_original) {
895                                         normal_short_to_float_v3(no_buf, no_s);
896                                         no = no_buf;
897                                 }
898                                 else {
899                                         if (vd.no) {
900                                                 normal_short_to_float_v3(no_buf, vd.no);
901                                                 no = no_buf;
902                                         }
903                                         else {
904                                                 no = vd.fno;
905                                         }
906                                 }
907
908                                 flip_index = (dot_v3v3(ss->cache->view_normal, no) <= 0.0f);
909                                 if (area_cos)
910                                         add_v3_v3(private_co[flip_index], co);
911                                 if (area_nos)
912                                         add_v3_v3(private_no[flip_index], no);
913                                 private_count[flip_index] += 1;
914                         }
915                 }
916                 BKE_pbvh_vertex_iter_end;
917         }
918
919         BLI_mutex_lock(&data->mutex);
920
921         /* for flatten center */
922         if (area_cos) {
923                 add_v3_v3(area_cos[0], private_co[0]);
924                 add_v3_v3(area_cos[1], private_co[1]);
925         }
926
927         /* for area normal */
928         if (area_nos) {
929                 add_v3_v3(area_nos[0], private_no[0]);
930                 add_v3_v3(area_nos[1], private_no[1]);
931         }
932
933         /* weights */
934         data->count[0] += private_count[0];
935         data->count[1] += private_count[1];
936
937         BLI_mutex_unlock(&data->mutex);
938 }
939
940 static void calc_area_center(
941         Sculpt *sd, Object *ob,
942         PBVHNode **nodes, int totnode,
943         float r_area_co[3])
944 {
945         const Brush *brush = BKE_paint_brush(&sd->paint);
946         SculptSession *ss = ob->sculpt;
947         const bool has_bm_orco = ss->bm && sculpt_stroke_is_dynamic_topology(ss, brush);
948         int n;
949
950         /* 0=towards view, 1=flipped */
951         float area_cos[2][3] = {{0.0f}};
952
953         int count[2] = {0};
954
955         /* Intentionally set 'sd' to NULL since we share logic with vertex paint. */
956         SculptThreadedTaskData data = {
957                 .sd = NULL, .ob = ob, .brush = brush, .nodes = nodes, .totnode = totnode,
958                 .has_bm_orco = has_bm_orco, .area_cos = area_cos, .area_nos = NULL, .count = count,
959         };
960         BLI_mutex_init(&data.mutex);
961
962         ParallelRangeSettings settings;
963         BLI_parallel_range_settings_defaults(&settings);
964         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
965         BLI_task_parallel_range(
966                     0, totnode,
967                     &data,
968                     calc_area_normal_and_center_task_cb,
969                     &settings);
970
971         BLI_mutex_end(&data.mutex);
972
973         /* for flatten center */
974         for (n = 0; n < ARRAY_SIZE(area_cos); n++) {
975                 if (count[n] != 0) {
976                         mul_v3_v3fl(r_area_co, area_cos[n], 1.0f / count[n]);
977                         break;
978                 }
979         }
980         if (n == 2) {
981                 zero_v3(r_area_co);
982         }
983 }
984
985 static void calc_area_normal(
986         Sculpt *sd, Object *ob,
987         PBVHNode **nodes, int totnode,
988         float r_area_no[3])
989 {
990         const Brush *brush = BKE_paint_brush(&sd->paint);
991         bool use_threading = (sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT;
992         sculpt_pbvh_calc_area_normal(brush, ob, nodes, totnode, use_threading, r_area_no);
993 }
994
995 /* expose 'calc_area_normal' externally. */
996 void sculpt_pbvh_calc_area_normal(
997         const Brush *brush, Object *ob,
998         PBVHNode **nodes, int totnode,
999         bool use_threading,
1000         float r_area_no[3])
1001 {
1002         SculptSession *ss = ob->sculpt;
1003         const bool has_bm_orco = ss->bm && sculpt_stroke_is_dynamic_topology(ss, brush);
1004
1005         /* 0=towards view, 1=flipped */
1006         float area_nos[2][3] = {{0.0f}};
1007
1008         int count[2] = {0};
1009
1010         /* Intentionally set 'sd' to NULL since this is used for vertex paint too. */
1011         SculptThreadedTaskData data = {
1012                 .sd = NULL, .ob = ob, .brush = brush, .nodes = nodes, .totnode = totnode,
1013                 .has_bm_orco = has_bm_orco, .area_cos = NULL, .area_nos = area_nos, .count = count,
1014         };
1015         BLI_mutex_init(&data.mutex);
1016
1017         ParallelRangeSettings settings;
1018         BLI_parallel_range_settings_defaults(&settings);
1019         settings.use_threading = use_threading;
1020         BLI_task_parallel_range(
1021                     0, totnode,
1022                     &data,
1023                     calc_area_normal_and_center_task_cb,
1024                     &settings);
1025
1026         BLI_mutex_end(&data.mutex);
1027
1028         /* for area normal */
1029         for (int i = 0; i < ARRAY_SIZE(area_nos); i++) {
1030                 if (normalize_v3_v3(r_area_no, area_nos[i]) != 0.0f) {
1031                         break;
1032                 }
1033         }
1034 }
1035
1036
1037 /* this calculates flatten center and area normal together,
1038  * amortizing the memory bandwidth and loop overhead to calculate both at the same time */
1039 static void calc_area_normal_and_center(
1040         Sculpt *sd, Object *ob,
1041         PBVHNode **nodes, int totnode,
1042         float r_area_no[3], float r_area_co[3])
1043 {
1044         const Brush *brush = BKE_paint_brush(&sd->paint);
1045         SculptSession *ss = ob->sculpt;
1046         const bool has_bm_orco = ss->bm && sculpt_stroke_is_dynamic_topology(ss, brush);
1047         int n;
1048
1049         /* 0=towards view, 1=flipped */
1050         float area_cos[2][3] = {{0.0f}};
1051         float area_nos[2][3] = {{0.0f}};
1052
1053         int count[2] = {0};
1054
1055         /* Intentionally set 'sd' to NULL since this is used for vertex paint too. */
1056         SculptThreadedTaskData data = {
1057                 .sd = NULL, .ob = ob, .brush = brush, .nodes = nodes, .totnode = totnode,
1058                 .has_bm_orco = has_bm_orco, .area_cos = area_cos, .area_nos = area_nos, .count = count,
1059         };
1060         BLI_mutex_init(&data.mutex);
1061
1062         ParallelRangeSettings settings;
1063         BLI_parallel_range_settings_defaults(&settings);
1064         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
1065         BLI_task_parallel_range(
1066                     0, totnode,
1067                     &data,
1068                     calc_area_normal_and_center_task_cb,
1069                     &settings);
1070
1071         BLI_mutex_end(&data.mutex);
1072
1073         /* for flatten center */
1074         for (n = 0; n < ARRAY_SIZE(area_cos); n++) {
1075                 if (count[n] != 0) {
1076                         mul_v3_v3fl(r_area_co, area_cos[n], 1.0f / count[n]);
1077                         break;
1078                 }
1079         }
1080         if (n == 2) {
1081                 zero_v3(r_area_co);
1082         }
1083
1084         /* for area normal */
1085         for (n = 0; n < ARRAY_SIZE(area_nos); n++) {
1086                 if (normalize_v3_v3(r_area_no, area_nos[n]) != 0.0f) {
1087                         break;
1088                 }
1089         }
1090 }
1091
1092 /** \} */
1093
1094
1095 /* Return modified brush strength. Includes the direction of the brush, positive
1096  * values pull vertices, negative values push. Uses tablet pressure and a
1097  * special multiplier found experimentally to scale the strength factor. */
1098 static float brush_strength(
1099         const Sculpt *sd, const StrokeCache *cache,
1100         const float feather, const UnifiedPaintSettings *ups)
1101 {
1102         const Scene *scene = cache->vc->scene;
1103         const Brush *brush = BKE_paint_brush((Paint *)&sd->paint);
1104
1105         /* Primary strength input; square it to make lower values more sensitive */
1106         const float root_alpha = BKE_brush_alpha_get(scene, brush);
1107         float alpha        = root_alpha * root_alpha;
1108         float dir          = (brush->flag & BRUSH_DIR_IN) ? -1 : 1;
1109         float pressure     = BKE_brush_use_alpha_pressure(scene, brush) ? cache->pressure : 1;
1110         float pen_flip     = cache->pen_flip ? -1 : 1;
1111         float invert       = cache->invert ? -1 : 1;
1112         float overlap       = ups->overlap_factor;
1113         /* spacing is integer percentage of radius, divide by 50 to get
1114          * normalized diameter */
1115
1116         float flip         = dir * invert * pen_flip;
1117
1118         switch (brush->sculpt_tool) {
1119                 case SCULPT_TOOL_CLAY:
1120                 case SCULPT_TOOL_CLAY_STRIPS:
1121                 case SCULPT_TOOL_DRAW:
1122                 case SCULPT_TOOL_LAYER:
1123                         return alpha * flip * pressure * overlap * feather;
1124
1125                 case SCULPT_TOOL_MASK:
1126                         overlap = (1 + overlap) / 2;
1127                         switch ((BrushMaskTool)brush->mask_tool) {
1128                                 case BRUSH_MASK_DRAW:
1129                                         return alpha * flip * pressure * overlap * feather;
1130                                 case BRUSH_MASK_SMOOTH:
1131                                         return alpha * pressure * feather;
1132                         }
1133                         BLI_assert(!"Not supposed to happen");
1134                         return 0.0f;
1135
1136                 case SCULPT_TOOL_CREASE:
1137                 case SCULPT_TOOL_BLOB:
1138                         return alpha * flip * pressure * overlap * feather;
1139
1140                 case SCULPT_TOOL_INFLATE:
1141                         if (flip > 0) {
1142                                 return 0.250f * alpha * flip * pressure * overlap * feather;
1143                         }
1144                         else {
1145                                 return 0.125f * alpha * flip * pressure * overlap * feather;
1146                         }
1147
1148                 case SCULPT_TOOL_FILL:
1149                 case SCULPT_TOOL_SCRAPE:
1150                 case SCULPT_TOOL_FLATTEN:
1151                         if (flip > 0) {
1152                                 overlap = (1 + overlap) / 2;
1153                                 return alpha * flip * pressure * overlap * feather;
1154                         }
1155                         else {
1156                                 /* reduce strength for DEEPEN, PEAKS, and CONTRAST */
1157                                 return 0.5f * alpha * flip * pressure * overlap * feather;
1158                         }
1159
1160                 case SCULPT_TOOL_SMOOTH:
1161                         return alpha * pressure * feather;
1162
1163                 case SCULPT_TOOL_PINCH:
1164                         if (flip > 0) {
1165                                 return alpha * flip * pressure * overlap * feather;
1166                         }
1167                         else {
1168                                 return 0.25f * alpha * flip * pressure * overlap * feather;
1169                         }
1170
1171                 case SCULPT_TOOL_NUDGE:
1172                         overlap = (1 + overlap) / 2;
1173                         return alpha * pressure * overlap * feather;
1174
1175                 case SCULPT_TOOL_THUMB:
1176                         return alpha * pressure * feather;
1177
1178                 case SCULPT_TOOL_SNAKE_HOOK:
1179                         return root_alpha * feather;
1180
1181                 case SCULPT_TOOL_GRAB:
1182                         return root_alpha * feather;
1183
1184                 case SCULPT_TOOL_ROTATE:
1185                         return alpha * pressure * feather;
1186
1187                 default:
1188                         return 0;
1189         }
1190 }
1191
1192 /* Return a multiplier for brush strength on a particular vertex. */
1193 float tex_strength(SculptSession *ss, const Brush *br,
1194                    const float brush_point[3],
1195                    const float len,
1196                    const short vno[3],
1197                    const float fno[3],
1198                    const float mask,
1199                    const int thread_id)
1200 {
1201         StrokeCache *cache = ss->cache;
1202         const Scene *scene = cache->vc->scene;
1203         const MTex *mtex = &br->mtex;
1204         float avg = 1;
1205         float rgba[4];
1206         float point[3];
1207
1208         sub_v3_v3v3(point, brush_point, cache->plane_offset);
1209
1210         if (!mtex->tex) {
1211                 avg = 1;
1212         }
1213         else if (mtex->brush_map_mode == MTEX_MAP_MODE_3D) {
1214                 /* Get strength by feeding the vertex
1215                  * location directly into a texture */
1216                 avg = BKE_brush_sample_tex_3d(scene, br, point, rgba, 0, ss->tex_pool);
1217         }
1218         else if (ss->texcache) {
1219                 float symm_point[3], point_2d[2];
1220                 float x = 0.0f, y = 0.0f; /* Quite warnings */
1221
1222                 /* if the active area is being applied for symmetry, flip it
1223                  * across the symmetry axis and rotate it back to the original
1224                  * position in order to project it. This insures that the
1225                  * brush texture will be oriented correctly. */
1226
1227                 flip_v3_v3(symm_point, point, cache->mirror_symmetry_pass);
1228
1229                 if (cache->radial_symmetry_pass)
1230                         mul_m4_v3(cache->symm_rot_mat_inv, symm_point);
1231
1232                 ED_view3d_project_float_v2_m4(cache->vc->ar, symm_point, point_2d, cache->projection_mat);
1233
1234                 /* still no symmetry supported for other paint modes.
1235                  * Sculpt does it DIY */
1236                 if (mtex->brush_map_mode == MTEX_MAP_MODE_AREA) {
1237                         /* Similar to fixed mode, but projects from brush angle
1238                          * rather than view direction */
1239
1240                         mul_m4_v3(cache->brush_local_mat, symm_point);
1241
1242                         x = symm_point[0];
1243                         y = symm_point[1];
1244
1245                         x *= br->mtex.size[0];
1246                         y *= br->mtex.size[1];
1247
1248                         x += br->mtex.ofs[0];
1249                         y += br->mtex.ofs[1];
1250
1251                         avg = paint_get_tex_pixel(&br->mtex, x, y, ss->tex_pool, thread_id);
1252
1253                         avg += br->texture_sample_bias;
1254                 }
1255                 else {
1256                         const float point_3d[3] = {point_2d[0], point_2d[1], 0.0f};
1257                         avg = BKE_brush_sample_tex_3d(scene, br, point_3d, rgba, 0, ss->tex_pool);
1258                 }
1259         }
1260
1261         /* Falloff curve */
1262         avg *= BKE_brush_curve_strength(br, len, cache->radius);
1263
1264         avg *= frontface(br, cache->view_normal, vno, fno);
1265
1266         /* Paint mask */
1267         avg *= 1.0f - mask;
1268
1269         return avg;
1270 }
1271
1272 /* Test AABB against sphere */
1273 bool sculpt_search_sphere_cb(PBVHNode *node, void *data_v)
1274 {
1275         SculptSearchSphereData *data = data_v;
1276         float *center = data->ss->cache->location, nearest[3];
1277         float t[3], bb_min[3], bb_max[3];
1278         int i;
1279
1280         if (data->original)
1281                 BKE_pbvh_node_get_original_BB(node, bb_min, bb_max);
1282         else
1283                 BKE_pbvh_node_get_BB(node, bb_min, bb_max);
1284
1285         for (i = 0; i < 3; ++i) {
1286                 if (bb_min[i] > center[i])
1287                         nearest[i] = bb_min[i];
1288                 else if (bb_max[i] < center[i])
1289                         nearest[i] = bb_max[i];
1290                 else
1291                         nearest[i] = center[i];
1292         }
1293
1294         sub_v3_v3v3(t, center, nearest);
1295
1296         return len_squared_v3(t) < data->radius_squared;
1297 }
1298
1299 /* 2D projection (distance to line). */
1300 bool sculpt_search_circle_cb(PBVHNode *node, void *data_v)
1301 {
1302         SculptSearchCircleData *data = data_v;
1303         float bb_min[3], bb_max[3];
1304
1305         if (data->original)
1306                 BKE_pbvh_node_get_original_BB(node, bb_min, bb_max);
1307         else
1308                 BKE_pbvh_node_get_BB(node, bb_min, bb_min);
1309
1310         float dummy_co[3], dummy_depth;
1311         const float dist_sq = dist_squared_ray_to_aabb_v3(
1312                 data->dist_ray_to_aabb_precalc, bb_min, bb_max, dummy_co, &dummy_depth);
1313
1314         return dist_sq < data->radius_squared || 1;
1315 }
1316
1317 /* Handles clipping against a mirror modifier and SCULPT_LOCK axis flags */
1318 static void sculpt_clip(Sculpt *sd, SculptSession *ss, float co[3], const float val[3])
1319 {
1320         int i;
1321
1322         for (i = 0; i < 3; ++i) {
1323                 if (sd->flags & (SCULPT_LOCK_X << i))
1324                         continue;
1325
1326                 if ((ss->cache->flag & (CLIP_X << i)) && (fabsf(co[i]) <= ss->cache->clip_tolerance[i]))
1327                         co[i] = 0.0f;
1328                 else
1329                         co[i] = val[i];
1330         }
1331 }
1332
1333 static PBVHNode **sculpt_pbvh_gather_generic(
1334         Object *ob, Sculpt *sd, const Brush *brush, bool use_original, float radius_scale, int *r_totnode)
1335 {
1336         SculptSession *ss = ob->sculpt;
1337         PBVHNode **nodes = NULL;
1338
1339         /* Build a list of all nodes that are potentially within the brush's area of influence */
1340         if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE) {
1341                 SculptSearchSphereData data = {
1342                         .ss = ss,
1343                         .sd = sd,
1344                         .radius_squared = SQUARE(ss->cache->radius * radius_scale),
1345                         .original = use_original,
1346                 };
1347                 BKE_pbvh_search_gather(ss->pbvh, sculpt_search_sphere_cb, &data, &nodes, r_totnode);
1348         }
1349         else {
1350                 struct DistRayAABB_Precalc dist_ray_to_aabb_precalc;
1351                 dist_squared_ray_to_aabb_v3_precalc(&dist_ray_to_aabb_precalc, ss->cache->location, ss->cache->view_normal);
1352                 SculptSearchCircleData data = {
1353                         .ss = ss,
1354                         .sd = sd,
1355                         .radius_squared = SQUARE(ss->cache->radius * radius_scale),
1356                         .original = use_original,
1357                         .dist_ray_to_aabb_precalc = &dist_ray_to_aabb_precalc,
1358                 };
1359                 BKE_pbvh_search_gather(ss->pbvh, sculpt_search_circle_cb, &data, &nodes, r_totnode);
1360         }
1361         return nodes;
1362 }
1363
1364 /* Calculate primary direction of movement for many brushes */
1365 static void calc_sculpt_normal(
1366         Sculpt *sd, Object *ob,
1367         PBVHNode **nodes, int totnode,
1368         float r_area_no[3])
1369 {
1370         const Brush *brush = BKE_paint_brush(&sd->paint);
1371         const SculptSession *ss = ob->sculpt;
1372
1373         switch (brush->sculpt_plane) {
1374                 case SCULPT_DISP_DIR_VIEW:
1375                         copy_v3_v3(r_area_no, ss->cache->true_view_normal);
1376                         break;
1377
1378                 case SCULPT_DISP_DIR_X:
1379                         ARRAY_SET_ITEMS(r_area_no, 1, 0, 0);
1380                         break;
1381
1382                 case SCULPT_DISP_DIR_Y:
1383                         ARRAY_SET_ITEMS(r_area_no, 0, 1, 0);
1384                         break;
1385
1386                 case SCULPT_DISP_DIR_Z:
1387                         ARRAY_SET_ITEMS(r_area_no, 0, 0, 1);
1388                         break;
1389
1390                 case SCULPT_DISP_DIR_AREA:
1391                         calc_area_normal(sd, ob, nodes, totnode, r_area_no);
1392                         break;
1393
1394                 default:
1395                         break;
1396         }
1397 }
1398
1399 static void update_sculpt_normal(Sculpt *sd, Object *ob,
1400                                  PBVHNode **nodes, int totnode)
1401 {
1402         const Brush *brush = BKE_paint_brush(&sd->paint);
1403         StrokeCache *cache = ob->sculpt->cache;
1404
1405         if (cache->mirror_symmetry_pass == 0 &&
1406             cache->radial_symmetry_pass == 0 &&
1407             (cache->first_time || !(brush->flag & BRUSH_ORIGINAL_NORMAL)))
1408         {
1409                 calc_sculpt_normal(sd, ob, nodes, totnode, cache->sculpt_normal);
1410                 if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
1411                         project_plane_v3_v3v3(cache->sculpt_normal, cache->sculpt_normal, cache->view_normal);
1412                         normalize_v3(cache->sculpt_normal);
1413                 }
1414                 copy_v3_v3(cache->sculpt_normal_symm, cache->sculpt_normal);
1415         }
1416         else {
1417                 copy_v3_v3(cache->sculpt_normal_symm, cache->sculpt_normal);
1418                 flip_v3(cache->sculpt_normal_symm, cache->mirror_symmetry_pass);
1419                 mul_m4_v3(cache->symm_rot_mat, cache->sculpt_normal_symm);
1420         }
1421 }
1422
1423 static void calc_local_y(ViewContext *vc, const float center[3], float y[3])
1424 {
1425         Object *ob = vc->obact;
1426         float loc[3], mval_f[2] = {0.0f, 1.0f};
1427         float zfac;
1428
1429         mul_v3_m4v3(loc, ob->imat, center);
1430         zfac = ED_view3d_calc_zfac(vc->rv3d, loc, NULL);
1431
1432         ED_view3d_win_to_delta(vc->ar, mval_f, y, zfac);
1433         normalize_v3(y);
1434
1435         add_v3_v3(y, ob->loc);
1436         mul_m4_v3(ob->imat, y);
1437 }
1438
1439 static void calc_brush_local_mat(const Brush *brush, Object *ob,
1440                                  float local_mat[4][4])
1441 {
1442         const StrokeCache *cache = ob->sculpt->cache;
1443         float tmat[4][4];
1444         float mat[4][4];
1445         float scale[4][4];
1446         float angle, v[3];
1447         float up[3];
1448
1449         /* Ensure ob->imat is up to date */
1450         invert_m4_m4(ob->imat, ob->obmat);
1451
1452         /* Initialize last column of matrix */
1453         mat[0][3] = 0;
1454         mat[1][3] = 0;
1455         mat[2][3] = 0;
1456         mat[3][3] = 1;
1457
1458         /* Get view's up vector in object-space */
1459         calc_local_y(cache->vc, cache->location, up);
1460
1461         /* Calculate the X axis of the local matrix */
1462         cross_v3_v3v3(v, up, cache->sculpt_normal);
1463         /* Apply rotation (user angle, rake, etc.) to X axis */
1464         angle = brush->mtex.rot - cache->special_rotation;
1465         rotate_v3_v3v3fl(mat[0], v, cache->sculpt_normal, angle);
1466
1467         /* Get other axes */
1468         cross_v3_v3v3(mat[1], cache->sculpt_normal, mat[0]);
1469         copy_v3_v3(mat[2], cache->sculpt_normal);
1470
1471         /* Set location */
1472         copy_v3_v3(mat[3], cache->location);
1473
1474         /* Scale by brush radius */
1475         normalize_m4(mat);
1476         scale_m4_fl(scale, cache->radius);
1477         mul_m4_m4m4(tmat, mat, scale);
1478
1479         /* Return inverse (for converting from modelspace coords to local
1480          * area coords) */
1481         invert_m4_m4(local_mat, tmat);
1482 }
1483
1484 static void update_brush_local_mat(Sculpt *sd, Object *ob)
1485 {
1486         StrokeCache *cache = ob->sculpt->cache;
1487
1488         if (cache->mirror_symmetry_pass == 0 &&
1489             cache->radial_symmetry_pass == 0)
1490         {
1491                 calc_brush_local_mat(BKE_paint_brush(&sd->paint), ob,
1492                                      cache->brush_local_mat);
1493         }
1494 }
1495
1496 /* For the smooth brush, uses the neighboring vertices around vert to calculate
1497  * a smoothed location for vert. Skips corner vertices (used by only one
1498  * polygon.) */
1499 static void neighbor_average(SculptSession *ss, float avg[3], unsigned vert)
1500 {
1501         const MeshElemMap *vert_map = &ss->pmap[vert];
1502         const MVert *mvert = ss->mvert;
1503         float (*deform_co)[3] = ss->deform_cos;
1504
1505         /* Don't modify corner vertices */
1506         if (vert_map->count > 1) {
1507                 int i, total = 0;
1508
1509                 zero_v3(avg);
1510
1511                 for (i = 0; i < vert_map->count; i++) {
1512                         const MPoly *p = &ss->mpoly[vert_map->indices[i]];
1513                         unsigned f_adj_v[2];
1514
1515                         if (poly_get_adj_loops_from_vert(p, ss->mloop, vert, f_adj_v) != -1) {
1516                                 int j;
1517                                 for (j = 0; j < ARRAY_SIZE(f_adj_v); j += 1) {
1518                                         if (vert_map->count != 2 || ss->pmap[f_adj_v[j]].count <= 2) {
1519                                                 add_v3_v3(avg, deform_co ? deform_co[f_adj_v[j]] :
1520                                                           mvert[f_adj_v[j]].co);
1521
1522                                                 total++;
1523                                         }
1524                                 }
1525                         }
1526                 }
1527
1528                 if (total > 0) {
1529                         mul_v3_fl(avg, 1.0f / total);
1530                         return;
1531                 }
1532         }
1533
1534         copy_v3_v3(avg, deform_co ? deform_co[vert] : mvert[vert].co);
1535 }
1536
1537 /* Similar to neighbor_average(), but returns an averaged mask value
1538  * instead of coordinate. Also does not restrict based on border or
1539  * corner vertices. */
1540 static float neighbor_average_mask(SculptSession *ss, unsigned vert)
1541 {
1542         const float *vmask = ss->vmask;
1543         float avg = 0;
1544         int i, total = 0;
1545
1546         for (i = 0; i < ss->pmap[vert].count; i++) {
1547                 const MPoly *p = &ss->mpoly[ss->pmap[vert].indices[i]];
1548                 unsigned f_adj_v[2];
1549
1550                 if (poly_get_adj_loops_from_vert(p, ss->mloop, vert, f_adj_v) != -1) {
1551                         int j;
1552                         for (j = 0; j < ARRAY_SIZE(f_adj_v); j += 1) {
1553                                 avg += vmask[f_adj_v[j]];
1554                                 total++;
1555                         }
1556                 }
1557         }
1558
1559         if (total > 0)
1560                 return avg / (float)total;
1561         else
1562                 return vmask[vert];
1563 }
1564
1565 /* Same logic as neighbor_average(), but for bmesh rather than mesh */
1566 static void bmesh_neighbor_average(float avg[3], BMVert *v)
1567 {
1568         /* logic for 3 or more is identical */
1569         const int vfcount = BM_vert_face_count_at_most(v, 3);
1570
1571         /* Don't modify corner vertices */
1572         if (vfcount > 1) {
1573                 BMIter liter;
1574                 BMLoop *l;
1575                 int i, total = 0;
1576
1577                 zero_v3(avg);
1578
1579                 BM_ITER_ELEM (l, &liter, v, BM_LOOPS_OF_VERT) {
1580                         const BMVert *adj_v[2] = {l->prev->v, l->next->v};
1581
1582                         for (i = 0; i < ARRAY_SIZE(adj_v); i++) {
1583                                 const BMVert *v_other = adj_v[i];
1584                                 if (vfcount != 2 || BM_vert_face_count_at_most(v_other, 2) <= 2) {
1585                                         add_v3_v3(avg, v_other->co);
1586                                         total++;
1587                                 }
1588                         }
1589                 }
1590
1591                 if (total > 0) {
1592                         mul_v3_fl(avg, 1.0f / total);
1593                         return;
1594                 }
1595         }
1596
1597         copy_v3_v3(avg, v->co);
1598 }
1599
1600 /* Same logic as neighbor_average_mask(), but for bmesh rather than mesh */
1601 static float bmesh_neighbor_average_mask(BMVert *v, const int cd_vert_mask_offset)
1602 {
1603         BMIter liter;
1604         BMLoop *l;
1605         float avg = 0;
1606         int i, total = 0;
1607
1608         BM_ITER_ELEM (l, &liter, v, BM_LOOPS_OF_VERT) {
1609                 /* skip this vertex */
1610                 const BMVert *adj_v[2] = {l->prev->v, l->next->v};
1611
1612                 for (i = 0; i < ARRAY_SIZE(adj_v); i++) {
1613                         const BMVert *v_other = adj_v[i];
1614                         const float *vmask = BM_ELEM_CD_GET_VOID_P(v_other, cd_vert_mask_offset);
1615                         avg += (*vmask);
1616                         total++;
1617                 }
1618         }
1619
1620         if (total > 0) {
1621                 return avg / (float)total;
1622         }
1623         else {
1624                 const float *vmask = BM_ELEM_CD_GET_VOID_P(v, cd_vert_mask_offset);
1625                 return (*vmask);
1626         }
1627 }
1628
1629 /* Note: uses after-struct allocated mem to store actual cache... */
1630 typedef struct SculptDoBrushSmoothGridDataChunk {
1631         size_t tmpgrid_size;
1632 } SculptDoBrushSmoothGridDataChunk;
1633
1634 typedef struct {
1635         SculptSession *ss;
1636         const float *ray_start, *ray_normal;
1637         bool hit;
1638         float depth;
1639         bool original;
1640 } SculptRaycastData;
1641
1642 typedef struct {
1643         const float *ray_start, *ray_normal;
1644         bool hit;
1645         float depth;
1646         float detail;
1647 } SculptDetailRaycastData;
1648
1649 typedef struct {
1650         SculptSession *ss;
1651         const float *ray_start, *ray_normal;
1652         bool hit;
1653         float depth;
1654         float dist_sq_to_ray;
1655         bool original;
1656 } SculptFindNearestToRayData;
1657
1658 static void do_smooth_brush_mesh_task_cb_ex(
1659         void *__restrict userdata,
1660         const int n,
1661         const ParallelRangeTLS *__restrict tls)
1662 {
1663         SculptThreadedTaskData *data = userdata;
1664         SculptSession *ss = data->ob->sculpt;
1665         Sculpt *sd = data->sd;
1666         const Brush *brush = data->brush;
1667         const bool smooth_mask = data->smooth_mask;
1668         float bstrength = data->strength;
1669
1670         PBVHVertexIter vd;
1671
1672         CLAMP(bstrength, 0.0f, 1.0f);
1673
1674         SculptBrushTest test;
1675         SculptBrushTestFn sculpt_brush_test_sq_fn =
1676                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
1677
1678         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1679         {
1680                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
1681                         const float fade = bstrength * tex_strength(
1682                                 ss, brush, vd.co, sqrtf(test.dist),
1683                                 vd.no, vd.fno, smooth_mask ? 0.0f : (vd.mask ? *vd.mask : 0.0f), tls->thread_id);
1684                         if (smooth_mask) {
1685                                 float val = neighbor_average_mask(ss, vd.vert_indices[vd.i]) - *vd.mask;
1686                                 val *= fade * bstrength;
1687                                 *vd.mask += val;
1688                                 CLAMP(*vd.mask, 0.0f, 1.0f);
1689                         }
1690                         else {
1691                                 float avg[3], val[3];
1692
1693                                 neighbor_average(ss, avg, vd.vert_indices[vd.i]);
1694                                 sub_v3_v3v3(val, avg, vd.co);
1695
1696                                 madd_v3_v3v3fl(val, vd.co, val, fade);
1697
1698                                 sculpt_clip(sd, ss, vd.co, val);
1699                         }
1700
1701                         if (vd.mvert)
1702                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
1703                 }
1704         }
1705         BKE_pbvh_vertex_iter_end;
1706 }
1707
1708 static void do_smooth_brush_bmesh_task_cb_ex(
1709         void *__restrict userdata,
1710         const int n,
1711         const ParallelRangeTLS *__restrict tls)
1712 {
1713         SculptThreadedTaskData *data = userdata;
1714         SculptSession *ss = data->ob->sculpt;
1715         Sculpt *sd = data->sd;
1716         const Brush *brush = data->brush;
1717         const bool smooth_mask = data->smooth_mask;
1718         float bstrength = data->strength;
1719
1720         PBVHVertexIter vd;
1721
1722         CLAMP(bstrength, 0.0f, 1.0f);
1723
1724         SculptBrushTest test;
1725         SculptBrushTestFn sculpt_brush_test_sq_fn =
1726                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
1727
1728         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1729         {
1730                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
1731                         const float fade = bstrength * tex_strength(
1732                                 ss, brush, vd.co, sqrtf(test.dist),
1733                                 vd.no, vd.fno, smooth_mask ? 0.0f : *vd.mask, tls->thread_id);
1734                         if (smooth_mask) {
1735                                 float val = bmesh_neighbor_average_mask(vd.bm_vert, vd.cd_vert_mask_offset) - *vd.mask;
1736                                 val *= fade * bstrength;
1737                                 *vd.mask += val;
1738                                 CLAMP(*vd.mask, 0.0f, 1.0f);
1739                         }
1740                         else {
1741                                 float avg[3], val[3];
1742
1743                                 bmesh_neighbor_average(avg, vd.bm_vert);
1744                                 sub_v3_v3v3(val, avg, vd.co);
1745
1746                                 madd_v3_v3v3fl(val, vd.co, val, fade);
1747
1748                                 sculpt_clip(sd, ss, vd.co, val);
1749                         }
1750
1751                         if (vd.mvert)
1752                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
1753                 }
1754         }
1755         BKE_pbvh_vertex_iter_end;
1756 }
1757
1758 static void do_smooth_brush_multires_task_cb_ex(
1759         void *__restrict userdata,
1760         const int n,
1761         const ParallelRangeTLS *__restrict tls)
1762 {
1763         SculptThreadedTaskData *data = userdata;
1764         SculptDoBrushSmoothGridDataChunk *data_chunk = tls->userdata_chunk;
1765         SculptSession *ss = data->ob->sculpt;
1766         Sculpt *sd = data->sd;
1767         const Brush *brush = data->brush;
1768         const bool smooth_mask = data->smooth_mask;
1769         float bstrength = data->strength;
1770
1771         CCGElem **griddata, *gddata;
1772         CCGKey key;
1773
1774         float (*tmpgrid_co)[3] = NULL;
1775         float tmprow_co[2][3];
1776         float *tmpgrid_mask = NULL;
1777         float tmprow_mask[2];
1778
1779         BLI_bitmap * const *grid_hidden;
1780         int *grid_indices, totgrid, gridsize;
1781         int i, x, y;
1782
1783         SculptBrushTest test;
1784         SculptBrushTestFn sculpt_brush_test_sq_fn =
1785                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
1786
1787         CLAMP(bstrength, 0.0f, 1.0f);
1788
1789         BKE_pbvh_node_get_grids(ss->pbvh, data->nodes[n], &grid_indices, &totgrid, NULL, &gridsize, &griddata);
1790         BKE_pbvh_get_grid_key(ss->pbvh, &key);
1791
1792         grid_hidden = BKE_pbvh_grid_hidden(ss->pbvh);
1793
1794         if (smooth_mask)
1795                 tmpgrid_mask = (void *)(data_chunk + 1);
1796         else
1797                 tmpgrid_co = (void *)(data_chunk + 1);
1798
1799         for (i = 0; i < totgrid; i++) {
1800                 int gi = grid_indices[i];
1801                 const BLI_bitmap *gh = grid_hidden[gi];
1802                 gddata = griddata[gi];
1803
1804                 if (smooth_mask)
1805                         memset(tmpgrid_mask, 0, data_chunk->tmpgrid_size);
1806                 else
1807                         memset(tmpgrid_co, 0, data_chunk->tmpgrid_size);
1808
1809                 for (y = 0; y < gridsize - 1; y++) {
1810                         const int v = y * gridsize;
1811                         if (smooth_mask) {
1812                                 tmprow_mask[0] = (*CCG_elem_offset_mask(&key, gddata, v) +
1813                                                   *CCG_elem_offset_mask(&key, gddata, v + gridsize));
1814                         }
1815                         else {
1816                                 add_v3_v3v3(tmprow_co[0],
1817                                             CCG_elem_offset_co(&key, gddata, v),
1818                                             CCG_elem_offset_co(&key, gddata, v + gridsize));
1819                         }
1820
1821                         for (x = 0; x < gridsize - 1; x++) {
1822                                 const int v1 = x + y * gridsize;
1823                                 const int v2 = v1 + 1;
1824                                 const int v3 = v1 + gridsize;
1825                                 const int v4 = v3 + 1;
1826
1827                                 if (smooth_mask) {
1828                                         float tmp;
1829
1830                                         tmprow_mask[(x + 1) % 2] = (*CCG_elem_offset_mask(&key, gddata, v2) +
1831                                                                     *CCG_elem_offset_mask(&key, gddata, v4));
1832                                         tmp = tmprow_mask[(x + 1) % 2] + tmprow_mask[x % 2];
1833
1834                                         tmpgrid_mask[v1] += tmp;
1835                                         tmpgrid_mask[v2] += tmp;
1836                                         tmpgrid_mask[v3] += tmp;
1837                                         tmpgrid_mask[v4] += tmp;
1838                                 }
1839                                 else {
1840                                         float tmp[3];
1841
1842                                         add_v3_v3v3(tmprow_co[(x + 1) % 2],
1843                                                     CCG_elem_offset_co(&key, gddata, v2),
1844                                                     CCG_elem_offset_co(&key, gddata, v4));
1845                                         add_v3_v3v3(tmp, tmprow_co[(x + 1) % 2], tmprow_co[x % 2]);
1846
1847                                         add_v3_v3(tmpgrid_co[v1], tmp);
1848                                         add_v3_v3(tmpgrid_co[v2], tmp);
1849                                         add_v3_v3(tmpgrid_co[v3], tmp);
1850                                         add_v3_v3(tmpgrid_co[v4], tmp);
1851                                 }
1852                         }
1853                 }
1854
1855                 /* blend with existing coordinates */
1856                 for (y = 0; y < gridsize; y++) {
1857                         for (x = 0; x < gridsize; x++) {
1858                                 float *co;
1859                                 const float *fno;
1860                                 float *mask;
1861                                 const int index = y * gridsize + x;
1862
1863                                 if (gh) {
1864                                         if (BLI_BITMAP_TEST(gh, index))
1865                                                 continue;
1866                                 }
1867
1868                                 co = CCG_elem_offset_co(&key, gddata, index);
1869                                 fno = CCG_elem_offset_no(&key, gddata, index);
1870                                 mask = CCG_elem_offset_mask(&key, gddata, index);
1871
1872                                 if (sculpt_brush_test_sq_fn(&test, co)) {
1873                                         const float strength_mask = (smooth_mask ? 0.0f : *mask);
1874                                         const float fade = bstrength * tex_strength(
1875                                                 ss, brush, co, sqrtf(test.dist),
1876                                                 NULL, fno, strength_mask, tls->thread_id);
1877                                         float f = 1.0f / 16.0f;
1878
1879                                         if (x == 0 || x == gridsize - 1)
1880                                                 f *= 2.0f;
1881
1882                                         if (y == 0 || y == gridsize - 1)
1883                                                 f *= 2.0f;
1884
1885                                         if (smooth_mask) {
1886                                                 *mask += ((tmpgrid_mask[index] * f) - *mask) * fade;
1887                                         }
1888                                         else {
1889                                                 float *avg = tmpgrid_co[index];
1890                                                 float val[3];
1891
1892                                                 mul_v3_fl(avg, f);
1893                                                 sub_v3_v3v3(val, avg, co);
1894                                                 madd_v3_v3v3fl(val, co, val, fade);
1895
1896                                                 sculpt_clip(sd, ss, co, val);
1897                                         }
1898                                 }
1899                         }
1900                 }
1901         }
1902 }
1903
1904 static void smooth(
1905         Sculpt *sd, Object *ob, PBVHNode **nodes, const int totnode, float bstrength, const bool smooth_mask)
1906 {
1907         SculptSession *ss = ob->sculpt;
1908         Brush *brush = BKE_paint_brush(&sd->paint);
1909
1910         const int max_iterations = 4;
1911         const float fract = 1.0f / max_iterations;
1912         PBVHType type = BKE_pbvh_type(ss->pbvh);
1913         int iteration, count;
1914         float last;
1915
1916         CLAMP(bstrength, 0.0f, 1.0f);
1917
1918         count = (int)(bstrength * max_iterations);
1919         last  = max_iterations * (bstrength - count * fract);
1920
1921         if (type == PBVH_FACES && !ss->pmap) {
1922                 BLI_assert(!"sculpt smooth: pmap missing");
1923                 return;
1924         }
1925
1926         for (iteration = 0; iteration <= count; ++iteration) {
1927                 const float strength = (iteration != count) ? 1.0f : last;
1928
1929                 SculptThreadedTaskData data = {
1930                     .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
1931                     .smooth_mask = smooth_mask, .strength = strength,
1932                 };
1933
1934                 ParallelRangeSettings settings;
1935                 BLI_parallel_range_settings_defaults(&settings);
1936                 settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
1937
1938                 switch (type) {
1939                         case PBVH_GRIDS:
1940                         {
1941                                 int gridsize;
1942                                 size_t size;
1943                                 SculptDoBrushSmoothGridDataChunk *data_chunk;
1944
1945                                 BKE_pbvh_node_get_grids(ss->pbvh, NULL, NULL, NULL, NULL, &gridsize, NULL);
1946                                 size = (size_t)gridsize;
1947                                 size = sizeof(float) * size * size * (smooth_mask ? 1 : 3);
1948                                 data_chunk = MEM_mallocN(sizeof(*data_chunk) + size, __func__);
1949                                 data_chunk->tmpgrid_size = size;
1950                                 size += sizeof(*data_chunk);
1951
1952                                 settings.userdata_chunk = data_chunk;
1953                                 settings.userdata_chunk_size = size;
1954                                 BLI_task_parallel_range(
1955                                             0, totnode,
1956                                             &data,
1957                                             do_smooth_brush_multires_task_cb_ex,
1958                                             &settings);
1959
1960                                 MEM_freeN(data_chunk);
1961                                 break;
1962                         }
1963                         case PBVH_FACES:
1964                                 BLI_task_parallel_range(
1965                                             0, totnode,
1966                                             &data,
1967                                             do_smooth_brush_mesh_task_cb_ex,
1968                                             &settings);
1969                                 break;
1970                         case PBVH_BMESH:
1971                                 BLI_task_parallel_range(
1972                                             0, totnode,
1973                                             &data,
1974                                             do_smooth_brush_bmesh_task_cb_ex,
1975                                             &settings);
1976                                 break;
1977                 }
1978
1979                 if (ss->multires)
1980                         multires_stitch_grids(ob);
1981         }
1982 }
1983
1984 static void do_smooth_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
1985 {
1986         SculptSession *ss = ob->sculpt;
1987         smooth(sd, ob, nodes, totnode, ss->cache->bstrength, false);
1988 }
1989
1990 static void do_mask_brush_draw_task_cb_ex(
1991         void *__restrict userdata,
1992         const int n,
1993         const ParallelRangeTLS *__restrict tls)
1994 {
1995         SculptThreadedTaskData *data = userdata;
1996         SculptSession *ss = data->ob->sculpt;
1997         const Brush *brush = data->brush;
1998         const float bstrength = ss->cache->bstrength;
1999
2000         PBVHVertexIter vd;
2001
2002         SculptBrushTest test;
2003         SculptBrushTestFn sculpt_brush_test_sq_fn =
2004                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2005
2006         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2007         {
2008                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2009                         const float fade = tex_strength(
2010                                 ss, brush, vd.co, sqrtf(test.dist),
2011                                 vd.no, vd.fno, 0.0f, tls->thread_id);
2012
2013                         (*vd.mask) += fade * bstrength;
2014                         CLAMP(*vd.mask, 0, 1);
2015
2016                         if (vd.mvert)
2017                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2018                 }
2019                 BKE_pbvh_vertex_iter_end;
2020         }
2021 }
2022
2023 static void do_mask_brush_draw(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2024 {
2025         Brush *brush = BKE_paint_brush(&sd->paint);
2026
2027         /* threaded loop over nodes */
2028         SculptThreadedTaskData data = {
2029             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2030         };
2031
2032         ParallelRangeSettings settings;
2033         BLI_parallel_range_settings_defaults(&settings);
2034         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
2035         BLI_task_parallel_range(
2036                     0, totnode,
2037                     &data,
2038                     do_mask_brush_draw_task_cb_ex,
2039                     &settings);
2040 }
2041
2042 static void do_mask_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2043 {
2044         SculptSession *ss = ob->sculpt;
2045         Brush *brush = BKE_paint_brush(&sd->paint);
2046
2047         switch ((BrushMaskTool)brush->mask_tool) {
2048                 case BRUSH_MASK_DRAW:
2049                         do_mask_brush_draw(sd, ob, nodes, totnode);
2050                         break;
2051                 case BRUSH_MASK_SMOOTH:
2052                         smooth(sd, ob, nodes, totnode, ss->cache->bstrength, true);
2053                         break;
2054         }
2055 }
2056
2057 static void do_draw_brush_task_cb_ex(
2058         void *__restrict userdata,
2059         const int n,
2060         const ParallelRangeTLS *__restrict tls)
2061 {
2062         SculptThreadedTaskData *data = userdata;
2063         SculptSession *ss = data->ob->sculpt;
2064         const Brush *brush = data->brush;
2065         const float *offset = data->offset;
2066
2067         PBVHVertexIter vd;
2068         float (*proxy)[3];
2069
2070         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2071
2072         SculptBrushTest test;
2073         SculptBrushTestFn sculpt_brush_test_sq_fn =
2074                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2075
2076         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2077         {
2078                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2079                         /* offset vertex */
2080                         const float fade = tex_strength(
2081                                 ss, brush, vd.co, sqrtf(test.dist),
2082                                 vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
2083
2084                         mul_v3_v3fl(proxy[vd.i], offset, fade);
2085
2086                         if (vd.mvert)
2087                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2088                 }
2089         }
2090         BKE_pbvh_vertex_iter_end;
2091 }
2092
2093 static void do_draw_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2094 {
2095         SculptSession *ss = ob->sculpt;
2096         Brush *brush = BKE_paint_brush(&sd->paint);
2097         float offset[3];
2098         const float bstrength = ss->cache->bstrength;
2099
2100         /* offset with as much as possible factored in already */
2101         mul_v3_v3fl(offset, ss->cache->sculpt_normal_symm, ss->cache->radius);
2102         mul_v3_v3(offset, ss->cache->scale);
2103         mul_v3_fl(offset, bstrength);
2104
2105         /* threaded loop over nodes */
2106         SculptThreadedTaskData data = {
2107             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2108             .offset = offset,
2109         };
2110
2111         ParallelRangeSettings settings;
2112         BLI_parallel_range_settings_defaults(&settings);
2113         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
2114         BLI_task_parallel_range(
2115                     0, totnode,
2116                     &data,
2117                     do_draw_brush_task_cb_ex,
2118                     &settings);
2119 }
2120
2121 /**
2122  * Used for 'SCULPT_TOOL_CREASE' and 'SCULPT_TOOL_BLOB'
2123  */
2124 static void do_crease_brush_task_cb_ex(
2125         void *__restrict userdata,
2126         const int n,
2127         const ParallelRangeTLS *__restrict tls)
2128 {
2129         SculptThreadedTaskData *data = userdata;
2130         SculptSession *ss = data->ob->sculpt;
2131         const Brush *brush = data->brush;
2132         SculptProjectVector *spvc = data->spvc;
2133         const float flippedbstrength = data->flippedbstrength;
2134         const float *offset = data->offset;
2135
2136         PBVHVertexIter vd;
2137         float (*proxy)[3];
2138
2139         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2140
2141         SculptBrushTest test;
2142         SculptBrushTestFn sculpt_brush_test_sq_fn =
2143                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2144
2145         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2146         {
2147                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2148                         /* offset vertex */
2149                         const float fade = tex_strength(
2150                                 ss, brush, vd.co, sqrtf(test.dist),
2151                                 vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
2152                         float val1[3];
2153                         float val2[3];
2154
2155                         /* first we pinch */
2156                         sub_v3_v3v3(val1, test.location, vd.co);
2157                         if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
2158                                 project_plane_v3_v3v3(val1, val1, ss->cache->view_normal);
2159                         }
2160
2161                         mul_v3_fl(val1, fade * flippedbstrength);
2162
2163                         sculpt_project_v3(spvc, val1, val1);
2164
2165                         /* then we draw */
2166                         mul_v3_v3fl(val2, offset, fade);
2167
2168                         add_v3_v3v3(proxy[vd.i], val1, val2);
2169
2170                         if (vd.mvert)
2171                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2172                 }
2173         }
2174         BKE_pbvh_vertex_iter_end;
2175 }
2176
2177 static void do_crease_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2178 {
2179         SculptSession *ss = ob->sculpt;
2180         const Scene *scene = ss->cache->vc->scene;
2181         Brush *brush = BKE_paint_brush(&sd->paint);
2182         float offset[3];
2183         float bstrength = ss->cache->bstrength;
2184         float flippedbstrength, crease_correction;
2185         float brush_alpha;
2186
2187         SculptProjectVector spvc;
2188
2189         /* offset with as much as possible factored in already */
2190         mul_v3_v3fl(offset, ss->cache->sculpt_normal_symm, ss->cache->radius);
2191         mul_v3_v3(offset, ss->cache->scale);
2192         mul_v3_fl(offset, bstrength);
2193
2194         /* we divide out the squared alpha and multiply by the squared crease to give us the pinch strength */
2195         crease_correction = brush->crease_pinch_factor * brush->crease_pinch_factor;
2196         brush_alpha = BKE_brush_alpha_get(scene, brush);
2197         if (brush_alpha > 0.0f)
2198                 crease_correction /= brush_alpha * brush_alpha;
2199
2200         /* we always want crease to pinch or blob to relax even when draw is negative */
2201         flippedbstrength = (bstrength < 0) ? -crease_correction * bstrength : crease_correction * bstrength;
2202
2203         if (brush->sculpt_tool == SCULPT_TOOL_BLOB) flippedbstrength *= -1.0f;
2204
2205         /* Use surface normal for 'spvc', so the vertices are pinched towards a line instead of a single point.
2206          * Without this we get a 'flat' surface surrounding the pinch */
2207         sculpt_project_v3_cache_init(&spvc, ss->cache->sculpt_normal_symm);
2208
2209         /* threaded loop over nodes */
2210         SculptThreadedTaskData data = {
2211             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2212             .spvc = &spvc, .offset = offset, .flippedbstrength = flippedbstrength,
2213         };
2214
2215         ParallelRangeSettings settings;
2216         BLI_parallel_range_settings_defaults(&settings);
2217         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
2218         BLI_task_parallel_range(
2219                     0, totnode,
2220                     &data,
2221                     do_crease_brush_task_cb_ex,
2222                     &settings);
2223 }
2224
2225 static void do_pinch_brush_task_cb_ex(
2226         void *__restrict userdata,
2227         const int n,
2228         const ParallelRangeTLS *__restrict tls)
2229 {
2230         SculptThreadedTaskData *data = userdata;
2231         SculptSession *ss = data->ob->sculpt;
2232         const Brush *brush = data->brush;
2233
2234         PBVHVertexIter vd;
2235         float (*proxy)[3];
2236         const float bstrength = ss->cache->bstrength;
2237
2238         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2239
2240         SculptBrushTest test;
2241         SculptBrushTestFn sculpt_brush_test_sq_fn =
2242                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2243
2244         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2245         {
2246                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2247                         const float fade = bstrength * tex_strength(
2248                                 ss, brush, vd.co, sqrtf(test.dist),
2249                                 vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
2250                         float val[3];
2251
2252                         sub_v3_v3v3(val, test.location, vd.co);
2253                         if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
2254                                 project_plane_v3_v3v3(val, val, ss->cache->view_normal);
2255                         }
2256                         mul_v3_v3fl(proxy[vd.i], val, fade);
2257
2258                         if (vd.mvert)
2259                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2260                 }
2261         }
2262         BKE_pbvh_vertex_iter_end;
2263 }
2264
2265 static void do_pinch_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2266 {
2267         Brush *brush = BKE_paint_brush(&sd->paint);
2268
2269         SculptThreadedTaskData data = {
2270             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2271         };
2272
2273         ParallelRangeSettings settings;
2274         BLI_parallel_range_settings_defaults(&settings);
2275         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
2276         BLI_task_parallel_range(
2277                     0, totnode,
2278                     &data,
2279                     do_pinch_brush_task_cb_ex,
2280                     &settings);
2281 }
2282
2283 static void do_grab_brush_task_cb_ex(
2284         void *__restrict userdata,
2285         const int n,
2286         const ParallelRangeTLS *__restrict tls)
2287 {
2288         SculptThreadedTaskData *data = userdata;
2289         SculptSession *ss = data->ob->sculpt;
2290         const Brush *brush = data->brush;
2291         const float *grab_delta = data->grab_delta;
2292
2293         PBVHVertexIter vd;
2294         SculptOrigVertData orig_data;
2295         float (*proxy)[3];
2296         const float bstrength = ss->cache->bstrength;
2297
2298         sculpt_orig_vert_data_init(&orig_data, data->ob, data->nodes[n]);
2299
2300         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2301
2302         SculptBrushTest test;
2303         SculptBrushTestFn sculpt_brush_test_sq_fn =
2304                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2305
2306         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2307         {
2308                 sculpt_orig_vert_data_update(&orig_data, &vd);
2309
2310                 if (sculpt_brush_test_sq_fn(&test, orig_data.co)) {
2311                         const float fade = bstrength * tex_strength(
2312                                 ss, brush, orig_data.co, sqrtf(test.dist),
2313                                 orig_data.no, NULL, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
2314
2315                         mul_v3_v3fl(proxy[vd.i], grab_delta, fade);
2316
2317                         if (vd.mvert)
2318                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2319                 }
2320         }
2321         BKE_pbvh_vertex_iter_end;
2322 }
2323
2324 static void do_grab_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2325 {
2326         SculptSession *ss = ob->sculpt;
2327         Brush *brush = BKE_paint_brush(&sd->paint);
2328         float grab_delta[3];
2329
2330         copy_v3_v3(grab_delta, ss->cache->grab_delta_symmetry);
2331
2332         if (ss->cache->normal_weight > 0.0f) {
2333                 sculpt_project_v3_normal_align(ss, ss->cache->normal_weight, grab_delta);
2334         }
2335
2336         SculptThreadedTaskData data = {
2337             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2338             .grab_delta = grab_delta,
2339         };
2340
2341         ParallelRangeSettings settings;
2342         BLI_parallel_range_settings_defaults(&settings);
2343         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
2344         BLI_task_parallel_range(
2345                     0, totnode,
2346                     &data,
2347                     do_grab_brush_task_cb_ex,
2348                     &settings);
2349 }
2350
2351 static void do_nudge_brush_task_cb_ex(
2352         void *__restrict userdata,
2353         const int n,
2354         const ParallelRangeTLS *__restrict tls)
2355 {
2356         SculptThreadedTaskData *data = userdata;
2357         SculptSession *ss = data->ob->sculpt;
2358         const Brush *brush = data->brush;
2359         const float *cono = data->cono;
2360
2361         PBVHVertexIter vd;
2362         float (*proxy)[3];
2363         const float bstrength = ss->cache->bstrength;
2364
2365         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2366
2367         SculptBrushTest test;
2368         SculptBrushTestFn sculpt_brush_test_sq_fn =
2369                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2370
2371         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2372         {
2373                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2374                         const float fade = bstrength * tex_strength(
2375                                 ss, brush, vd.co, sqrtf(test.dist),
2376                                 vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
2377
2378                         mul_v3_v3fl(proxy[vd.i], cono, fade);
2379
2380                         if (vd.mvert)
2381                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2382                 }
2383         }
2384         BKE_pbvh_vertex_iter_end;
2385 }
2386
2387 static void do_nudge_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2388 {
2389         SculptSession *ss = ob->sculpt;
2390         Brush *brush = BKE_paint_brush(&sd->paint);
2391         float grab_delta[3];
2392         float tmp[3], cono[3];
2393
2394         copy_v3_v3(grab_delta, ss->cache->grab_delta_symmetry);
2395
2396         cross_v3_v3v3(tmp, ss->cache->sculpt_normal_symm, grab_delta);
2397         cross_v3_v3v3(cono, tmp, ss->cache->sculpt_normal_symm);
2398
2399         SculptThreadedTaskData data = {
2400             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2401             .cono = cono,
2402         };
2403
2404         ParallelRangeSettings settings;
2405         BLI_parallel_range_settings_defaults(&settings);
2406         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
2407         BLI_task_parallel_range(
2408                     0, totnode,
2409                     &data,
2410                     do_nudge_brush_task_cb_ex,
2411                     &settings);
2412 }
2413
2414 static void do_snake_hook_brush_task_cb_ex(
2415         void *__restrict userdata,
2416         const int n,
2417         const ParallelRangeTLS *__restrict tls)
2418 {
2419         SculptThreadedTaskData *data = userdata;
2420         SculptSession *ss = data->ob->sculpt;
2421         const Brush *brush = data->brush;
2422         SculptProjectVector *spvc = data->spvc;
2423         const float *grab_delta = data->grab_delta;
2424
2425         PBVHVertexIter vd;
2426         float (*proxy)[3];
2427         const float bstrength = ss->cache->bstrength;
2428         const bool do_rake_rotation = ss->cache->is_rake_rotation_valid;
2429         const bool do_pinch = (brush->crease_pinch_factor != 0.5f);
2430         const float pinch = do_pinch ?
2431                 (2.0f * (0.5f - brush->crease_pinch_factor) * (len_v3(grab_delta) / ss->cache->radius)) : 0.0f;
2432
2433         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2434
2435         SculptBrushTest test;
2436         SculptBrushTestFn sculpt_brush_test_sq_fn =
2437                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2438
2439         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2440         {
2441                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2442                         const float fade = bstrength * tex_strength(
2443                                 ss, brush, vd.co, sqrtf(test.dist),
2444                                 vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
2445
2446                         mul_v3_v3fl(proxy[vd.i], grab_delta, fade);
2447
2448                         /* negative pinch will inflate, helps maintain volume */
2449                         if (do_pinch) {
2450                                 float delta_pinch_init[3], delta_pinch[3];
2451
2452                                 sub_v3_v3v3(delta_pinch, vd.co, test.location);
2453                                 if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
2454                                         project_plane_v3_v3v3(delta_pinch, delta_pinch, ss->cache->true_view_normal);
2455                                 }
2456
2457                                 /* important to calculate based on the grabbed location
2458                                  * (intentionally ignore fade here). */
2459                                 add_v3_v3(delta_pinch, grab_delta);
2460
2461                                 sculpt_project_v3(spvc, delta_pinch, delta_pinch);
2462
2463                                 copy_v3_v3(delta_pinch_init, delta_pinch);
2464
2465                                 float pinch_fade = pinch * fade;
2466                                 /* when reducing, scale reduction back by how close to the center we are,
2467                                  * so we don't pinch into nothingness */
2468                                 if (pinch > 0.0f) {
2469                                         /* square to have even less impact for close vertices */
2470                                         pinch_fade *= pow2f(min_ff(1.0f, len_v3(delta_pinch) / ss->cache->radius));
2471                                 }
2472                                 mul_v3_fl(delta_pinch, 1.0f + pinch_fade);
2473                                 sub_v3_v3v3(delta_pinch, delta_pinch_init, delta_pinch);
2474                                 add_v3_v3(proxy[vd.i], delta_pinch);
2475                         }
2476
2477                         if (do_rake_rotation) {
2478                                 float delta_rotate[3];
2479                                 sculpt_rake_rotate(ss, test.location, vd.co, fade, delta_rotate);
2480                                 add_v3_v3(proxy[vd.i], delta_rotate);
2481                         }
2482
2483                         if (vd.mvert)
2484                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2485                 }
2486         }
2487         BKE_pbvh_vertex_iter_end;
2488 }
2489
2490 static void do_snake_hook_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2491 {
2492         SculptSession *ss = ob->sculpt;
2493         Brush *brush = BKE_paint_brush(&sd->paint);
2494         const float bstrength = ss->cache->bstrength;
2495         float grab_delta[3];
2496
2497         SculptProjectVector spvc;
2498
2499         copy_v3_v3(grab_delta, ss->cache->grab_delta_symmetry);
2500
2501         if (bstrength < 0)
2502                 negate_v3(grab_delta);
2503
2504         if (ss->cache->normal_weight > 0.0f) {
2505                 sculpt_project_v3_normal_align(ss, ss->cache->normal_weight, grab_delta);
2506         }
2507
2508         /* optionally pinch while painting */
2509         if (brush->crease_pinch_factor != 0.5f) {
2510                 sculpt_project_v3_cache_init(&spvc, grab_delta);
2511         }
2512
2513         SculptThreadedTaskData data = {
2514             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2515             .spvc = &spvc, .grab_delta = grab_delta,
2516         };
2517
2518         ParallelRangeSettings settings;
2519         BLI_parallel_range_settings_defaults(&settings);
2520         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
2521         BLI_task_parallel_range(
2522                     0, totnode,
2523                     &data,
2524                     do_snake_hook_brush_task_cb_ex,
2525                     &settings);
2526 }
2527
2528 static void do_thumb_brush_task_cb_ex(
2529         void *__restrict userdata,
2530         const int n,
2531         const ParallelRangeTLS *__restrict tls)
2532 {
2533         SculptThreadedTaskData *data = userdata;
2534         SculptSession *ss = data->ob->sculpt;
2535         const Brush *brush = data->brush;
2536         const float *cono = data->cono;
2537
2538         PBVHVertexIter vd;
2539         SculptOrigVertData orig_data;
2540         float (*proxy)[3];
2541         const float bstrength = ss->cache->bstrength;
2542
2543         sculpt_orig_vert_data_init(&orig_data, data->ob, data->nodes[n]);
2544
2545         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2546
2547         SculptBrushTest test;
2548         SculptBrushTestFn sculpt_brush_test_sq_fn =
2549                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2550
2551         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2552         {
2553                 sculpt_orig_vert_data_update(&orig_data, &vd);
2554
2555                 if (sculpt_brush_test_sq_fn(&test, orig_data.co)) {
2556                         const float fade = bstrength * tex_strength(
2557                                 ss, brush, orig_data.co, sqrtf(test.dist),
2558                                 orig_data.no, NULL, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
2559
2560                         mul_v3_v3fl(proxy[vd.i], cono, fade);
2561
2562                         if (vd.mvert)
2563                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2564                 }
2565         }
2566         BKE_pbvh_vertex_iter_end;
2567 }
2568
2569 static void do_thumb_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2570 {
2571         SculptSession *ss = ob->sculpt;
2572         Brush *brush = BKE_paint_brush(&sd->paint);
2573         float grab_delta[3];
2574         float tmp[3], cono[3];
2575
2576         copy_v3_v3(grab_delta, ss->cache->grab_delta_symmetry);
2577
2578         cross_v3_v3v3(tmp, ss->cache->sculpt_normal_symm, grab_delta);
2579         cross_v3_v3v3(cono, tmp, ss->cache->sculpt_normal_symm);
2580
2581         SculptThreadedTaskData data = {
2582             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2583             .cono = cono,
2584         };
2585
2586         ParallelRangeSettings settings;
2587         BLI_parallel_range_settings_defaults(&settings);
2588         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
2589         BLI_task_parallel_range(
2590                     0, totnode,
2591                     &data,
2592                     do_thumb_brush_task_cb_ex,
2593                     &settings);
2594 }
2595
2596 static void do_rotate_brush_task_cb_ex(
2597         void *__restrict userdata,
2598         const int n,
2599         const ParallelRangeTLS *__restrict tls)
2600 {
2601         SculptThreadedTaskData *data = userdata;
2602         SculptSession *ss = data->ob->sculpt;
2603         const Brush *brush = data->brush;
2604         const float angle = data->angle;
2605
2606         PBVHVertexIter vd;
2607         SculptOrigVertData orig_data;
2608         float (*proxy)[3];
2609         const float bstrength = ss->cache->bstrength;
2610
2611         sculpt_orig_vert_data_init(&orig_data, data->ob, data->nodes[n]);
2612
2613         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2614
2615         SculptBrushTest test;
2616         SculptBrushTestFn sculpt_brush_test_sq_fn =
2617                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2618
2619         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2620         {
2621                 sculpt_orig_vert_data_update(&orig_data, &vd);
2622
2623                 if (sculpt_brush_test_sq_fn(&test, orig_data.co)) {
2624                         float vec[3], rot[3][3];
2625                         const float fade = bstrength * tex_strength(
2626                                 ss, brush, orig_data.co, sqrtf(test.dist),
2627                                 orig_data.no, NULL, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
2628
2629                         sub_v3_v3v3(vec, orig_data.co, ss->cache->location);
2630                         axis_angle_normalized_to_mat3(rot, ss->cache->sculpt_normal_symm, angle * fade);
2631                         mul_v3_m3v3(proxy[vd.i], rot, vec);
2632                         add_v3_v3(proxy[vd.i], ss->cache->location);
2633                         sub_v3_v3(proxy[vd.i], orig_data.co);
2634
2635                         if (vd.mvert)
2636                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2637                 }
2638         }
2639         BKE_pbvh_vertex_iter_end;
2640 }
2641
2642 static void do_rotate_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2643 {
2644         SculptSession *ss = ob->sculpt;
2645         Brush *brush = BKE_paint_brush(&sd->paint);
2646
2647         static const int flip[8] = { 1, -1, -1, 1, -1, 1, 1, -1 };
2648         const float angle = ss->cache->vertex_rotation * flip[ss->cache->mirror_symmetry_pass];
2649
2650         SculptThreadedTaskData data = {
2651             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2652             .angle = angle,
2653         };
2654
2655         ParallelRangeSettings settings;
2656         BLI_parallel_range_settings_defaults(&settings);
2657         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
2658         BLI_task_parallel_range(
2659                     0, totnode,
2660                     &data,
2661                     do_rotate_brush_task_cb_ex,
2662                     &settings);
2663 }
2664
2665 static void do_layer_brush_task_cb_ex(
2666         void *__restrict userdata,
2667         const int n,
2668         const ParallelRangeTLS *__restrict tls)
2669 {
2670         SculptThreadedTaskData *data = userdata;
2671         SculptSession *ss = data->ob->sculpt;
2672         Sculpt *sd = data->sd;
2673         const Brush *brush = data->brush;
2674         const float *offset = data->offset;
2675
2676         PBVHVertexIter vd;
2677         SculptOrigVertData orig_data;
2678         float *layer_disp;
2679         const float bstrength = ss->cache->bstrength;
2680         const float lim = (bstrength < 0) ? -data->brush->height : data->brush->height;
2681         /* XXX: layer brush needs conversion to proxy but its more complicated */
2682         /* proxy = BKE_pbvh_node_add_proxy(ss->pbvh, nodes[n])->co; */
2683
2684         sculpt_orig_vert_data_init(&orig_data, data->ob, data->nodes[n]);
2685
2686         /* Why does this have to be thread-protected? */
2687         BLI_mutex_lock(&data->mutex);
2688         layer_disp = BKE_pbvh_node_layer_disp_get(ss->pbvh, data->nodes[n]);
2689         BLI_mutex_unlock(&data->mutex);
2690
2691         SculptBrushTest test;
2692         SculptBrushTestFn sculpt_brush_test_sq_fn =
2693                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2694
2695         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2696         {
2697                 sculpt_orig_vert_data_update(&orig_data, &vd);
2698
2699                 if (sculpt_brush_test_sq_fn(&test, orig_data.co)) {
2700                         const float fade = bstrength * tex_strength(
2701                                 ss, brush, vd.co, sqrtf(test.dist),
2702                                 vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
2703                         float *disp = &layer_disp[vd.i];
2704                         float val[3];
2705
2706                         *disp += fade;
2707
2708                         /* Don't let the displacement go past the limit */
2709                         if ((lim < 0.0f && *disp < lim) || (lim >= 0.0f && *disp > lim))
2710                                 *disp = lim;
2711
2712                         mul_v3_v3fl(val, offset, *disp);
2713
2714                         if (!ss->multires && !ss->bm && ss->layer_co && (brush->flag & BRUSH_PERSISTENT)) {
2715                                 int index = vd.vert_indices[vd.i];
2716
2717                                 /* persistent base */
2718                                 add_v3_v3(val, ss->layer_co[index]);
2719                         }
2720                         else {
2721                                 add_v3_v3(val, orig_data.co);
2722                         }
2723
2724                         sculpt_clip(sd, ss, vd.co, val);
2725
2726                         if (vd.mvert)
2727                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2728                 }
2729         }
2730         BKE_pbvh_vertex_iter_end;
2731 }
2732
2733 static void do_layer_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2734 {
2735         SculptSession *ss = ob->sculpt;
2736         Brush *brush = BKE_paint_brush(&sd->paint);
2737         float offset[3];
2738
2739         mul_v3_v3v3(offset, ss->cache->scale, ss->cache->sculpt_normal_symm);
2740
2741         SculptThreadedTaskData data = {
2742             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2743             .offset = offset,
2744         };
2745         BLI_mutex_init(&data.mutex);
2746
2747         ParallelRangeSettings settings;
2748         BLI_parallel_range_settings_defaults(&settings);
2749         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
2750         BLI_task_parallel_range(
2751                     0, totnode,
2752                     &data,
2753                     do_layer_brush_task_cb_ex,
2754                     &settings);
2755
2756         BLI_mutex_end(&data.mutex);
2757 }
2758
2759 static void do_inflate_brush_task_cb_ex(
2760         void *__restrict userdata,
2761         const int n,
2762         const ParallelRangeTLS *__restrict tls)
2763 {
2764         SculptThreadedTaskData *data = userdata;
2765         SculptSession *ss = data->ob->sculpt;
2766         const Brush *brush = data->brush;
2767
2768         PBVHVertexIter vd;
2769         float (*proxy)[3];
2770         const float bstrength = ss->cache->bstrength;
2771
2772         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2773
2774         SculptBrushTest test;
2775         SculptBrushTestFn sculpt_brush_test_sq_fn =
2776                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2777
2778         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2779         {
2780                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2781                         const float fade = bstrength * tex_strength(
2782                                 ss, brush, vd.co, sqrtf(test.dist),
2783                                 vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
2784                         float val[3];
2785
2786                         if (vd.fno)
2787                                 copy_v3_v3(val, vd.fno);
2788                         else
2789                                 normal_short_to_float_v3(val, vd.no);
2790
2791                         mul_v3_fl(val, fade * ss->cache->radius);
2792                         mul_v3_v3v3(proxy[vd.i], val, ss->cache->scale);
2793
2794                         if (vd.mvert)
2795                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2796                 }
2797         }
2798         BKE_pbvh_vertex_iter_end;
2799 }
2800
2801 static void do_inflate_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2802 {
2803         Brush *brush = BKE_paint_brush(&sd->paint);
2804
2805         SculptThreadedTaskData data = {
2806             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2807         };
2808
2809         ParallelRangeSettings settings;
2810         BLI_parallel_range_settings_defaults(&settings);
2811         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
2812         BLI_task_parallel_range(
2813                     0, totnode,
2814                     &data,
2815                     do_inflate_brush_task_cb_ex,
2816                     &settings);
2817 }
2818
2819 static void calc_sculpt_plane(
2820         Sculpt *sd, Object *ob,
2821         PBVHNode **nodes, int totnode,
2822         float r_area_no[3], float r_area_co[3])
2823 {
2824         SculptSession *ss = ob->sculpt;
2825         Brush *brush = BKE_paint_brush(&sd->paint);
2826
2827         if (ss->cache->mirror_symmetry_pass == 0 &&
2828             ss->cache->radial_symmetry_pass == 0 &&
2829             ss->cache->tile_pass == 0 &&
2830             (ss->cache->first_time || !(brush->flag & BRUSH_ORIGINAL_NORMAL)))
2831         {
2832                 switch (brush->sculpt_plane) {
2833                         case SCULPT_DISP_DIR_VIEW:
2834                                 copy_v3_v3(r_area_no, ss->cache->true_view_normal);
2835                                 break;
2836
2837                         case SCULPT_DISP_DIR_X:
2838                                 ARRAY_SET_ITEMS(r_area_no, 1, 0, 0);
2839                                 break;
2840
2841                         case SCULPT_DISP_DIR_Y:
2842                                 ARRAY_SET_ITEMS(r_area_no, 0, 1, 0);
2843                                 break;
2844
2845                         case SCULPT_DISP_DIR_Z:
2846                                 ARRAY_SET_ITEMS(r_area_no, 0, 0, 1);
2847                                 break;
2848
2849                         case SCULPT_DISP_DIR_AREA:
2850                                 calc_area_normal_and_center(sd, ob, nodes, totnode, r_area_no, r_area_co);
2851                                 if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
2852                                         project_plane_v3_v3v3(r_area_no, r_area_no, ss->cache->view_normal);
2853                                         normalize_v3(r_area_no);
2854                                 }
2855                                 break;
2856
2857                         default:
2858                                 break;
2859                 }
2860
2861                 /* for flatten center */
2862                 /* flatten center has not been calculated yet if we are not using the area normal */
2863                 if (brush->sculpt_plane != SCULPT_DISP_DIR_AREA)
2864                         calc_area_center(sd, ob, nodes, totnode, r_area_co);
2865
2866                 /* for area normal */
2867                 copy_v3_v3(ss->cache->sculpt_normal, r_area_no);
2868
2869                 /* for flatten center */
2870                 copy_v3_v3(ss->cache->last_center, r_area_co);
2871         }
2872         else {
2873                 /* for area normal */
2874                 copy_v3_v3(r_area_no, ss->cache->sculpt_normal);
2875
2876                 /* for flatten center */
2877                 copy_v3_v3(r_area_co, ss->cache->last_center);
2878
2879                 /* for area normal */
2880                 flip_v3(r_area_no, ss->cache->mirror_symmetry_pass);
2881
2882                 /* for flatten center */
2883                 flip_v3(r_area_co, ss->cache->mirror_symmetry_pass);
2884
2885                 /* for area normal */
2886                 mul_m4_v3(ss->cache->symm_rot_mat, r_area_no);
2887
2888                 /* for flatten center */
2889                 mul_m4_v3(ss->cache->symm_rot_mat, r_area_co);
2890
2891                 /* shift the plane for the current tile */
2892                 add_v3_v3(r_area_co, ss->cache->plane_offset);
2893         }
2894 }
2895
2896 static int plane_trim(const StrokeCache *cache, const Brush *brush, const float val[3])
2897 {
2898         return (!(brush->flag & BRUSH_PLANE_TRIM) ||
2899                 ((dot_v3v3(val, val) <= cache->radius_squared * cache->plane_trim_squared)));
2900 }
2901
2902 static bool plane_point_side_flip(
2903         const float co[3], const float plane[4],
2904         const bool flip)
2905 {
2906         float d = plane_point_side_v3(plane, co);
2907         if (flip) d = -d;
2908         return d <= 0.0f;
2909 }
2910
2911 static int plane_point_side(const float co[3], const float plane[4])
2912 {
2913         float d = plane_point_side_v3(plane, co);
2914         return d <= 0.0f;
2915 }
2916
2917 static float get_offset(Sculpt *sd, SculptSession *ss)
2918 {
2919         Brush *brush = BKE_paint_brush(&sd->paint);
2920
2921         float rv = brush->plane_offset;
2922
2923         if (brush->flag & BRUSH_OFFSET_PRESSURE) {
2924                 rv *= ss->cache->pressure;
2925         }
2926
2927         return rv;
2928 }
2929
2930 static void do_flatten_brush_task_cb_ex(
2931         void *__restrict userdata,
2932         const int n,
2933         const ParallelRangeTLS *__restrict tls)
2934 {
2935         SculptThreadedTaskData *data = userdata;
2936         SculptSession *ss = data->ob->sculpt;
2937         const Brush *brush = data->brush;
2938         const float *area_no = data->area_no;
2939         const float *area_co = data->area_co;
2940
2941         PBVHVertexIter vd;
2942         float (*proxy)[3];
2943         const float bstrength = ss->cache->bstrength;
2944
2945         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2946
2947         SculptBrushTest test;
2948         SculptBrushTestFn sculpt_brush_test_sq_fn =
2949                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2950
2951         plane_from_point_normal_v3(test.plane_tool, area_co, area_no);
2952
2953         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2954         {
2955                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2956                         float intr[3];
2957                         float val[3];
2958
2959                         closest_to_plane_normalized_v3(intr, test.plane_tool, vd.co);
2960
2961                         sub_v3_v3v3(val, intr, vd.co);
2962
2963                         if (plane_trim(ss->cache, brush, val)) {
2964                                 const float fade = bstrength * tex_strength(
2965                                         ss, brush, vd.co, sqrtf(test.dist),
2966                                         vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
2967
2968                                 mul_v3_v3fl(proxy[vd.i], val, fade);
2969
2970                                 if (vd.mvert)
2971                                         vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2972                         }
2973                 }
2974         }
2975         BKE_pbvh_vertex_iter_end;
2976 }
2977
2978 static void do_flatten_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2979 {
2980         SculptSession *ss = ob->sculpt;
2981         Brush *brush = BKE_paint_brush(&sd->paint);
2982
2983         const float radius = ss->cache->radius;
2984
2985         float area_no[3];
2986         float area_co[3];
2987
2988         float offset = get_offset(sd, ss);
2989         float displace;
2990         float temp[3];
2991
2992         calc_sculpt_plane(sd, ob, nodes, totnode, area_no, area_co);
2993
2994         displace = radius * offset;
2995
2996         mul_v3_v3v3(temp, area_no, ss->cache->scale);
2997         mul_v3_fl(temp, displace);
2998         add_v3_v3(area_co, temp);
2999
3000         SculptThreadedTaskData data = {
3001             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
3002             .area_no = area_no, .area_co = area_co,
3003         };
3004
3005         ParallelRangeSettings settings;
3006         BLI_parallel_range_settings_defaults(&settings);
3007         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
3008         BLI_task_parallel_range(
3009                     0, totnode,
3010                     &data,
3011                     do_flatten_brush_task_cb_ex,
3012                     &settings);
3013 }
3014
3015 static void do_clay_brush_task_cb_ex(
3016         void *__restrict userdata,
3017         const int n,
3018         const ParallelRangeTLS *__restrict tls)
3019 {
3020         SculptThreadedTaskData *data = userdata;
3021         SculptSession *ss = data->ob->sculpt;
3022         const Brush *brush = data->brush;
3023         const float *area_no = data->area_no;
3024         const float *area_co = data->area_co;
3025
3026         PBVHVertexIter vd;
3027         float (*proxy)[3];
3028         const bool flip = (ss->cache->bstrength < 0);
3029         const float bstrength = flip ? -ss->cache->bstrength : ss->cache->bstrength;
3030
3031         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
3032
3033         SculptBrushTest test;
3034         SculptBrushTestFn sculpt_brush_test_sq_fn =
3035                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
3036
3037         plane_from_point_normal_v3(test.plane_tool, area_co, area_no);
3038
3039         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
3040         {
3041                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
3042                         if (plane_point_side_flip(vd.co, test.plane_tool, flip)) {
3043                                 float intr[3];
3044                                 float val[3];
3045
3046                                 closest_to_plane_normalized_v3(intr, test.plane_tool, vd.co);
3047
3048                                 sub_v3_v3v3(val, intr, vd.co);
3049
3050                                 if (plane_trim(ss->cache, brush, val)) {
3051                                         /* note, the normal from the vertices is ignored,
3052                                          * causes glitch with planes, see: T44390 */
3053                                         const float fade = bstrength * tex_strength(
3054                                                 ss, brush, vd.co, sqrtf(test.dist),
3055                                                 vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
3056
3057                                         mul_v3_v3fl(proxy[vd.i], val, fade);
3058
3059                                         if (vd.mvert)
3060                                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
3061                                 }
3062                         }
3063                 }
3064         }
3065         BKE_pbvh_vertex_iter_end;
3066 }
3067
3068 static void do_clay_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
3069 {
3070         SculptSession *ss = ob->sculpt;
3071         Brush *brush = BKE_paint_brush(&sd->paint);
3072
3073         const bool flip = (ss->cache->bstrength < 0);
3074         const float radius = flip ? -ss->cache->radius : ss->cache->radius;
3075
3076         float offset = get_offset(sd, ss);
3077         float displace;
3078
3079         float area_no[3];
3080         float area_co[3];
3081         float temp[3];
3082
3083         calc_sculpt_plane(sd, ob, nodes, totnode, area_no, area_co);
3084
3085         displace = radius * (0.25f + offset);
3086
3087         mul_v3_v3v3(temp, area_no, ss->cache->scale);
3088         mul_v3_fl(temp, displace);
3089         add_v3_v3(area_co, temp);
3090
3091         /* add_v3_v3v3(p, ss->cache->location, area_no); */
3092
3093         SculptThreadedTaskData data = {
3094             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
3095             .area_no = area_no, .area_co = area_co,
3096         };
3097
3098         ParallelRangeSettings settings;
3099         BLI_parallel_range_settings_defaults(&settings);
3100         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
3101         BLI_task_parallel_range(
3102                     0, totnode,
3103                     &data,
3104                     do_clay_brush_task_cb_ex,
3105                     &settings);
3106 }
3107
3108 static void do_clay_strips_brush_task_cb_ex(
3109         void *__restrict userdata,
3110         const int n,
3111         const ParallelRangeTLS *__restrict tls)
3112 {
3113         SculptThreadedTaskData *data = userdata;
3114         SculptSession *ss = data->ob->sculpt;
3115         const Brush *brush = data->brush;
3116         float (*mat)[4] = data->mat;
3117         const float *area_no_sp = data->area_no_sp;
3118         const float *area_co = data->area_co;
3119
3120         PBVHVertexIter vd;
3121         SculptBrushTest test;
3122         float (*proxy)[3];
3123         const bool flip = (ss->cache->bstrength < 0);
3124         const float bstrength = flip ? -ss->cache->bstrength : ss->cache->bstrength;
3125
3126         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
3127
3128         sculpt_brush_test_init(ss, &test);
3129         plane_from_point_normal_v3(test.plane_tool, area_co, area_no_sp);
3130
3131         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
3132         {
3133                 if (sculpt_brush_test_cube(&test, vd.co, mat)) {
3134                         if (plane_point_side_flip(vd.co, test.plane_tool, flip)) {
3135                                 float intr[3];
3136                                 float val[3];
3137
3138                                 closest_to_plane_normalized_v3(intr, test.plane_tool, vd.co);
3139
3140                                 sub_v3_v3v3(val, intr, vd.co);
3141
3142                                 if (plane_trim(ss->cache, brush, val)) {
3143                                         /* note, the normal from the vertices is ignored,
3144                                          * causes glitch with planes, see: T44390 */
3145                                         const float fade = bstrength * tex_strength(
3146                                                 ss, brush, vd.co, ss->cache->radius * test.dist,
3147                                                 vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
3148
3149                                         mul_v3_v3fl(proxy[vd.i], val, fade);
3150
3151                                         if (vd.mvert)
3152                                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
3153                                 }
3154                         }
3155                 }
3156         }
3157         BKE_pbvh_vertex_iter_end;
3158 }
3159
3160 static void do_clay_strips_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
3161 {
3162         SculptSession *ss = ob->sculpt;
3163         Brush *brush = BKE_paint_brush(&sd->paint);
3164
3165         const bool flip = (ss->cache->bstrength < 0);
3166         const float radius    = flip ? -ss->cache->radius : ss->cache->radius;
3167         const float offset    = get_offset(sd, ss);
3168         const float displace  = radius * (0.25f + offset);
3169
3170         float area_no_sp[3];  /* the sculpt-plane normal (whatever its set to) */
3171         float area_no[3];     /* geometry normal */
3172         float area_co[3];
3173
3174         float temp[3];
3175         float mat[4][4];
3176         float scale[4][4];
3177         float tmat[4][4];
3178
3179         calc_sculpt_plane(sd, ob, nodes, totnode, area_no_sp, area_co);
3180
3181         if (brush->sculpt_plane != SCULPT_DISP_DIR_AREA || (brush->flag & BRUSH_ORIGINAL_NORMAL))
3182                 calc_area_normal(sd, ob, nodes, totnode, area_no);
3183         else
3184                 copy_v3_v3(area_no, area_no_sp);
3185
3186         /* delay the first daub because grab delta is not setup */
3187         if (ss->cache->first_time)
3188                 return;
3189
3190         mul_v3_v3v3(temp, area_no_sp, ss->cache->scale);
3191         mul_v3_fl(temp, displace);
3192         add_v3_v3(area_co, temp);
3193
3194         /* init mat */
3195         cross_v3_v3v3(mat[0], area_no, ss->cache->grab_delta_symmetry);
3196         mat[0][3] = 0;
3197         cross_v3_v3v3(mat[1], area_no, mat[0]);
3198         mat[1][3] = 0;
3199         copy_v3_v3(mat[2], area_no);
3200         mat[2][3] = 0;
3201         copy_v3_v3(mat[3], ss->cache->location);
3202         mat[3][3] = 1;
3203         normalize_m4(mat);
3204
3205         /* scale mat */
3206         scale_m4_fl(scale, ss->cache->radius);
3207         mul_m4_m4m4(tmat, mat, scale);
3208         invert_m4_m4(mat, tmat);
3209
3210         SculptThreadedTaskData data = {
3211             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
3212             .area_no_sp = area_no_sp, .area_co = area_co, .mat = mat,
3213         };
3214
3215         ParallelRangeSettings settings;
3216         BLI_parallel_range_settings_defaults(&settings);
3217         settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
3218         BLI_task_parallel_range(
3219                     0, totnode,
3220                     &data,
3221                     do_clay_strips_brush_task_cb_ex,
3222                     &settings);
3223 }
3224
3225 static void do_fill_brush_task_cb_ex(
3226         void *__restrict userdata,
3227         const int n,
3228         const ParallelRangeTLS *__restrict tls)
3229 {
3230         SculptThreadedTaskData *data = userdata;
3231         SculptSession *ss = data->ob->sculpt;
3232         const Brush *brush = data->brush;
3233         const float *area_no = data->area_no;
3234         const float *area_co = data->area_co;
3235
3236         PBVHVertexIter vd;
3237         float (*proxy)[3];
3238         const float bstrength = ss->cache->bstrength;
3239
3240         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
3241
3242         SculptBrushTest test;
3243         SculptBrushTestFn sculpt_brush_test_sq_fn =
3244                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
3245
3246         plane_from_point_normal_v3(test.plane_tool, area_co, area_no);
3247
3248         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
3249         {
3250                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {