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