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