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