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