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