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