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