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