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