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