490343ab1f2cb9b8050db0bc2b580b0d09453bbb
[blender-staging.git] / source / blender / editors / sculpt_paint / paint_vertex.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) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/sculpt_paint/paint_vertex.c
29  *  \ingroup edsculpt
30  *
31  * Used for vertex color & weight paint and mode switching.
32  *
33  * \note This file is already big,
34  * use `paint_vertex_color_ops.c` & `paint_vertex_weight_ops.c` for general purpose operators.
35  */
36
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_listbase.h"
40 #include "BLI_rect.h"
41 #include "BLI_math.h"
42 #include "BLI_array_utils.h"
43 #include "BLI_task.h"
44
45 #include "DNA_armature_types.h"
46 #include "DNA_mesh_types.h"
47 #include "DNA_particle_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_brush_types.h"
50 #include "DNA_object_types.h"
51
52 #include "RNA_access.h"
53 #include "RNA_define.h"
54
55 #include "BKE_brush.h"
56 #include "BKE_context.h"
57 #include "BKE_depsgraph.h"
58 #include "BKE_deform.h"
59 #include "BKE_mesh.h"
60 #include "BKE_mesh_mapping.h"
61 #include "BKE_object_deform.h"
62 #include "BKE_paint.h"
63 #include "BKE_report.h"
64 #include "BKE_subsurf.h"
65
66 #include "WM_api.h"
67 #include "WM_types.h"
68
69 #include "ED_object.h"
70 #include "ED_mesh.h"
71 #include "ED_screen.h"
72 #include "ED_view3d.h"
73
74 #include "bmesh.h"
75 #include "BKE_ccg.h"
76
77 #include "sculpt_intern.h"
78 #include "paint_intern.h"  /* own include */
79
80 /* Use for 'blur' brush, align with PBVH nodes, created and freed on each update. */
81 struct VPaintAverageAccum {
82         uint len;
83         uint value[3];
84 };
85
86 struct WPaintAverageAccum {
87         uint len;
88         double value;
89 };
90
91 struct NormalAnglePrecalc {
92         bool do_mask_normal;
93         /* what angle to mask at */
94         float angle;
95         /* cos(angle), faster to compare */
96         float angle__cos;
97         float angle_inner;
98         float angle_inner__cos;
99         /* difference between angle and angle_inner, for easy access */
100         float angle_range;
101 };
102
103
104 static void view_angle_limits_init(
105         struct NormalAnglePrecalc *a, float angle, bool do_mask_normal)
106 {
107         angle = RAD2DEGF(angle);
108         a->do_mask_normal = do_mask_normal;
109         if (do_mask_normal) {
110                 a->angle_inner = angle;
111                 a->angle = (a->angle_inner + 90.0f) * 0.5f;
112         }
113         else {
114                 a->angle_inner = a->angle = angle;
115         }
116
117         a->angle_inner *=   (float)(M_PI_2 / 90);
118         a->angle *=         (float)(M_PI_2 / 90);
119         a->angle_range = a->angle - a->angle_inner;
120
121         if (a->angle_range <= 0.0f) {
122                 a->do_mask_normal = false;  /* no need to do blending */
123         }
124
125         a->angle__cos       = cosf(a->angle);
126         a->angle_inner__cos = cosf(a->angle_inner);
127 }
128
129 static float view_angle_limits_apply_falloff(
130         const struct NormalAnglePrecalc *a, float angle_cos, float *mask_p)
131 {
132         if (angle_cos <= a->angle__cos) {
133                 /* outsize the normal limit */
134                 return false;
135         }
136         else if (angle_cos < a->angle_inner__cos) {
137                 *mask_p *= (a->angle - acosf(angle_cos)) / a->angle_range;
138                 return true;
139         }
140         else {
141                 return true;
142         }
143 }
144
145 static bool vwpaint_use_normal(const VPaint *vp)
146 {
147         return ((vp->paint.brush->flag & BRUSH_FRONTFACE) != 0) ||
148                ((vp->paint.brush->flag & BRUSH_FRONTFACE_FALLOFF) != 0);
149 }
150
151 static bool brush_use_accumulate(const Brush *brush)
152 {
153         return (brush->flag & BRUSH_ACCUMULATE) != 0 || brush->vertexpaint_tool == PAINT_BLEND_SMEAR;
154 }
155
156 static MDeformVert *defweight_prev_init(MDeformVert *dvert_prev, MDeformVert *dvert_curr, int index)
157 {
158         MDeformVert *dv_curr = &dvert_curr[index];
159         MDeformVert *dv_prev = &dvert_prev[index];
160         if (dv_prev->flag == 1) {
161                 dv_prev->flag = 0;
162                 defvert_copy(dv_prev, dv_curr);
163         }
164         return dv_prev;
165 }
166
167 /* check if we can do partial updates and have them draw realtime
168  * (without rebuilding the 'derivedFinal') */
169 static bool vertex_paint_use_fast_update_check(Object *ob)
170 {
171         DerivedMesh *dm = ob->derivedFinal;
172
173         if (dm) {
174                 Mesh *me = BKE_mesh_from_object(ob);
175                 if (me && me->mloopcol) {
176                         return (me->mloopcol == CustomData_get_layer(&dm->loopData, CD_MLOOPCOL));
177                 }
178         }
179
180         return false;
181 }
182
183 static void paint_last_stroke_update(Scene *scene, ARegion *ar, const float mval[2])
184 {
185         const int mval_i[2] = {mval[0], mval[1]};
186         float world[3];
187
188         if (ED_view3d_autodist_simple(ar, mval_i, world, 0, NULL)) {
189                 UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
190                 ups->average_stroke_counter++;
191                 add_v3_v3(ups->average_stroke_accum, world);
192                 ups->last_stroke_valid = true;
193         }
194 }
195
196 /* polling - retrieve whether cursor should be set or operator should be done */
197
198 /* Returns true if vertex paint mode is active */
199 int vertex_paint_mode_poll(bContext *C)
200 {
201         Object *ob = CTX_data_active_object(C);
202
203         return ob && ob->mode == OB_MODE_VERTEX_PAINT && ((Mesh *)ob->data)->totpoly;
204 }
205
206 int vertex_paint_poll(bContext *C)
207 {
208         if (vertex_paint_mode_poll(C) &&
209             BKE_paint_brush(&CTX_data_tool_settings(C)->vpaint->paint))
210         {
211                 ScrArea *sa = CTX_wm_area(C);
212                 if (sa && sa->spacetype == SPACE_VIEW3D) {
213                         ARegion *ar = CTX_wm_region(C);
214                         if (ar->regiontype == RGN_TYPE_WINDOW)
215                                 return 1;
216                 }
217         }
218         return 0;
219 }
220
221 int weight_paint_mode_poll(bContext *C)
222 {
223         Object *ob = CTX_data_active_object(C);
224
225         return ob && ob->mode == OB_MODE_WEIGHT_PAINT && ((Mesh *)ob->data)->totpoly;
226 }
227
228 int weight_paint_poll(bContext *C)
229 {
230         Object *ob = CTX_data_active_object(C);
231         ScrArea *sa;
232
233         if ((ob != NULL) &&
234             (ob->mode & OB_MODE_WEIGHT_PAINT) &&
235             (BKE_paint_brush(&CTX_data_tool_settings(C)->wpaint->paint) != NULL) &&
236             (sa = CTX_wm_area(C)) &&
237             (sa->spacetype == SPACE_VIEW3D))
238         {
239                 ARegion *ar = CTX_wm_region(C);
240                 if (ar->regiontype == RGN_TYPE_WINDOW) {
241                         return 1;
242                 }
243         }
244         return 0;
245 }
246
247 static VPaint *new_vpaint(void)
248 {
249         VPaint *vp = MEM_callocN(sizeof(VPaint), "VPaint");
250
251         vp->paint.flags |= PAINT_SHOW_BRUSH;
252
253         return vp;
254 }
255
256 uint vpaint_get_current_col(Scene *scene, VPaint *vp)
257 {
258         Brush *brush = BKE_paint_brush(&vp->paint);
259         uchar col[4];
260         rgb_float_to_uchar(col, BKE_brush_color_get(scene, brush));
261         col[3] = 255; /* alpha isn't used, could even be removed to speedup paint a little */
262         return *(uint *)col;
263 }
264
265 /* wpaint has 'wpaint_blend' */
266 static uint vpaint_blend(
267         const VPaint *vp, uint color_curr, uint color_orig,
268         uint color_paint, const int alpha_i,
269         /* pre scaled from [0-1] --> [0-255] */
270         const int brush_alpha_value_i)
271 {
272         const Brush *brush = vp->paint.brush;
273         const int tool = brush->vertexpaint_tool;
274
275         uint color_blend = ED_vpaint_blend_tool(tool, color_curr, color_paint, alpha_i);
276
277         /* if no accumulate, clip color adding with colorig & orig alpha */
278         if (!brush_use_accumulate(brush)) {
279                 uint color_test, a;
280                 char *cp, *ct, *co;
281
282                 color_test = ED_vpaint_blend_tool(tool, color_orig, color_paint, brush_alpha_value_i);
283
284                 cp = (char *)&color_blend;
285                 ct = (char *)&color_test;
286                 co = (char *)&color_orig;
287
288                 for (a = 0; a < 4; a++) {
289                         if (ct[a] < co[a]) {
290                                 if (cp[a] < ct[a]) cp[a] = ct[a];
291                                 else if (cp[a] > co[a]) cp[a] = co[a];
292                         }
293                         else {
294                                 if (cp[a] < co[a]) cp[a] = co[a];
295                                 else if (cp[a] > ct[a]) cp[a] = ct[a];
296                         }
297                 }
298         }
299
300         if ((brush->flag & BRUSH_LOCK_ALPHA) &&
301             !ELEM(tool, PAINT_BLEND_ALPHA_SUB, PAINT_BLEND_ALPHA_ADD))
302         {
303                 char *cp, *cc;
304                 cp = (char *)&color_blend;
305                 cc = (char *)&color_curr;
306                 cp[3] = cc[3];
307         }
308
309         return color_blend;
310 }
311
312 static void tex_color_alpha(
313         VPaint *vp, const ViewContext *vc, const float co[3],
314         float r_rgba[4])
315 {
316         const Brush *brush = BKE_paint_brush(&vp->paint);
317         BLI_assert(brush->mtex.tex != NULL);
318         if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_3D) {
319                 BKE_brush_sample_tex_3D(vc->scene, brush, co, r_rgba, 0, NULL);
320         }
321         else {
322                 float co_ss[2];  /* screenspace */
323                 if (ED_view3d_project_float_object(
324                         vc->ar,
325                         co, co_ss,
326                         V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
327                 {
328                         const float co_ss_3d[3] = {co_ss[0], co_ss[1], 0.0f};  /* we need a 3rd empty value */
329                         BKE_brush_sample_tex_3D(vc->scene, brush, co_ss_3d, r_rgba, 0, NULL);
330                 }
331                 else {
332                         zero_v4(r_rgba);
333                 }
334         }
335 }
336
337 /* vpaint has 'vpaint_blend' */
338 static float wpaint_blend(
339         const VPaint *wp, float weight,
340         const float alpha, float paintval,
341         const float UNUSED(brush_alpha_value),
342         const short do_flip)
343 {
344         const Brush *brush = wp->paint.brush;
345         int tool = brush->vertexpaint_tool;
346
347         if (do_flip) {
348                 switch (tool) {
349                         case PAINT_BLEND_MIX:
350                                 paintval = 1.f - paintval; break;
351                         case PAINT_BLEND_ADD:
352                                 tool = PAINT_BLEND_SUB; break;
353                         case PAINT_BLEND_SUB:
354                                 tool = PAINT_BLEND_ADD; break;
355                         case PAINT_BLEND_LIGHTEN:
356                                 tool = PAINT_BLEND_DARKEN; break;
357                         case PAINT_BLEND_DARKEN:
358                                 tool = PAINT_BLEND_LIGHTEN; break;
359                 }
360         }
361
362         weight = ED_wpaint_blend_tool(tool, weight, paintval, alpha);
363
364         CLAMP(weight, 0.0f, 1.0f);
365
366         return weight;
367 }
368
369 static float wpaint_clamp_monotonic(float oldval, float curval, float newval)
370 {
371         if (newval < oldval)
372                 return MIN2(newval, curval);
373         else if (newval > oldval)
374                 return MAX2(newval, curval);
375         else
376                 return newval;
377 }
378
379 /* ----------------------------------------------------- */
380
381 static void do_weight_paint_normalize_all(MDeformVert *dvert, const int defbase_tot, const bool *vgroup_validmap)
382 {
383         float sum = 0.0f, fac;
384         uint i, tot = 0;
385         MDeformWeight *dw;
386
387         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
388                 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
389                         tot++;
390                         sum += dw->weight;
391                 }
392         }
393
394         if ((tot == 0) || (sum == 1.0f)) {
395                 return;
396         }
397
398         if (sum != 0.0f) {
399                 fac = 1.0f / sum;
400
401                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
402                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
403                                 dw->weight *= fac;
404                         }
405                 }
406         }
407         else {
408                 /* hrmf, not a factor in this case */
409                 fac = 1.0f / tot;
410
411                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
412                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
413                                 dw->weight = fac;
414                         }
415                 }
416         }
417 }
418
419 /**
420  * A version of #do_weight_paint_normalize_all that includes locked weights
421  * but only changes unlocked weights.
422  */
423 static bool do_weight_paint_normalize_all_locked(
424         MDeformVert *dvert, const int defbase_tot, const bool *vgroup_validmap,
425         const bool *lock_flags)
426 {
427         float sum = 0.0f, fac;
428         float sum_unlock = 0.0f;
429         float lock_weight = 0.0f;
430         uint i, tot = 0;
431         MDeformWeight *dw;
432
433         if (lock_flags == NULL) {
434                 do_weight_paint_normalize_all(dvert, defbase_tot, vgroup_validmap);
435                 return true;
436         }
437
438         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
439                 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
440                         sum += dw->weight;
441
442                         if (lock_flags[dw->def_nr]) {
443                                 lock_weight += dw->weight;
444                         }
445                         else {
446                                 tot++;
447                                 sum_unlock += dw->weight;
448                         }
449                 }
450         }
451
452         if (sum == 1.0f) {
453                 return true;
454         }
455
456         if (tot == 0) {
457                 return false;
458         }
459
460         if (lock_weight >= 1.0f) {
461                 /* locked groups make it impossible to fully normalize,
462                  * zero out what we can and return false */
463                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
464                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
465                                 if (lock_flags[dw->def_nr] == false) {
466                                         dw->weight = 0.0f;
467                                 }
468                         }
469                 }
470
471                 return (lock_weight == 1.0f);
472         }
473         else if (sum_unlock != 0.0f) {
474                 fac = (1.0f - lock_weight) / sum_unlock;
475
476                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
477                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
478                                 if (lock_flags[dw->def_nr] == false) {
479                                         dw->weight *= fac;
480                                         /* paranoid but possibly with float error */
481                                         CLAMP(dw->weight, 0.0f, 1.0f);
482                                 }
483                         }
484                 }
485         }
486         else {
487                 /* hrmf, not a factor in this case */
488                 fac = (1.0f - lock_weight) / tot;
489                 /* paranoid but possibly with float error */
490                 CLAMP(fac, 0.0f, 1.0f);
491
492                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
493                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
494                                 if (lock_flags[dw->def_nr] == false) {
495                                         dw->weight = fac;
496                                 }
497                         }
498                 }
499         }
500
501         return true;
502 }
503
504 /**
505  * \note same as function above except it does a second pass without active group
506  * if normalize fails with it.
507  */
508 static void do_weight_paint_normalize_all_locked_try_active(
509         MDeformVert *dvert, const int defbase_tot, const bool *vgroup_validmap,
510         const bool *lock_flags, const bool *lock_with_active)
511 {
512         /* first pass with both active and explicitly locked groups restricted from change */
513
514         bool success = do_weight_paint_normalize_all_locked(dvert, defbase_tot, vgroup_validmap, lock_with_active);
515
516         if (!success) {
517                 /**
518                  * Locks prevented the first pass from full completion, so remove restriction on active group; e.g:
519                  *
520                  * - With 1.0 weight painted into active:
521                  *   nonzero locked weight; first pass zeroed out unlocked weight; scale 1 down to fit.
522                  * - With 0.0 weight painted into active:
523                  *   no unlocked groups; first pass did nothing; increase 0 to fit.
524                  */
525                 do_weight_paint_normalize_all_locked(dvert, defbase_tot, vgroup_validmap, lock_flags);
526         }
527 }
528
529 #if 0 /* UNUSED */
530 static bool has_unselected_unlocked_bone_group(
531         int defbase_tot, bool *defbase_sel, int selected,
532         const bool *lock_flags, const bool *vgroup_validmap)
533 {
534         int i;
535         if (defbase_tot == selected) {
536                 return false;
537         }
538         for (i = 0; i < defbase_tot; i++) {
539                 if (vgroup_validmap[i] && !defbase_sel[i] && !lock_flags[i]) {
540                         return true;
541                 }
542         }
543         return false;
544 }
545 #endif
546
547 static void multipaint_clamp_change(
548         MDeformVert *dvert, const int defbase_tot, const bool *defbase_sel,
549         float *change_p)
550 {
551         int i;
552         MDeformWeight *dw;
553         float val;
554         float change = *change_p;
555
556         /* verify that the change does not cause values exceeding 1 and clamp it */
557         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
558                 if (dw->def_nr < defbase_tot && defbase_sel[dw->def_nr]) {
559                         if (dw->weight) {
560                                 val = dw->weight * change;
561                                 if (val > 1) {
562                                         change = 1.0f / dw->weight;
563                                 }
564                         }
565                 }
566         }
567
568         *change_p = change;
569 }
570
571 static bool multipaint_verify_change(MDeformVert *dvert, const int defbase_tot, float change, const bool *defbase_sel)
572 {
573         int i;
574         MDeformWeight *dw;
575         float val;
576
577         /* in case the change is reduced, you need to recheck
578          * the earlier values to make sure they are not 0
579          * (precision error) */
580         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
581                 if (dw->def_nr < defbase_tot && defbase_sel[dw->def_nr]) {
582                         if (dw->weight) {
583                                 val = dw->weight * change;
584                                 /* the value should never reach zero while multi-painting if it
585                                  * was nonzero beforehand */
586                                 if (val <= 0) {
587                                         return false;
588                                 }
589                         }
590                 }
591         }
592
593         return true;
594 }
595
596 static void multipaint_apply_change(MDeformVert *dvert, const int defbase_tot, float change, const bool *defbase_sel)
597 {
598         int i;
599         MDeformWeight *dw;
600
601         /* apply the valid change */
602         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
603                 if (dw->def_nr < defbase_tot && defbase_sel[dw->def_nr]) {
604                         if (dw->weight) {
605                                 dw->weight = dw->weight * change;
606                                 CLAMP(dw->weight, 0.0f, 1.0f);
607                         }
608                 }
609         }
610 }
611
612 /**
613  * Variables stored both for 'active' and 'mirror' sides.
614  */
615 struct WeightPaintGroupData {
616         /** index of active group or its mirror
617          *
618          * - 'active' is always `ob->actdef`.
619          * - 'mirror' is -1 when 'ME_EDIT_MIRROR_X' flag id disabled,
620          *   otherwise this will be set to the mirror or the active group (if the group isn't mirrored).
621          */
622         int index;
623         /** lock that includes the 'index' as locked too
624          *
625          * - 'active' is set of locked or active/selected groups
626          * - 'mirror' is set of locked or mirror groups
627          */
628         const bool *lock;
629 };
630
631 /* struct to avoid passing many args each call to do_weight_paint_vertex()
632  * this _could_ be made a part of the operators 'WPaintData' struct, or at
633  * least a member, but for now keep its own struct, initialized on every
634  * paint stroke update - campbell */
635 typedef struct WeightPaintInfo {
636
637         int defbase_tot;
638
639         /* both must add up to 'defbase_tot' */
640         int defbase_tot_sel;
641         int defbase_tot_unsel;
642
643         struct WeightPaintGroupData active, mirror;
644
645         /* boolean array for locked bones,
646          * length of defbase_tot */
647         const bool *lock_flags;
648         /* boolean array for selected bones,
649          * length of defbase_tot, cant be const because of how its passed */
650         const bool *defbase_sel;
651         /* same as WeightPaintData.vgroup_validmap,
652          * only added here for convenience */
653         const bool *vgroup_validmap;
654
655         bool do_flip;
656         bool do_multipaint;
657         bool do_auto_normalize;
658
659         float brush_alpha_value;  /* result of BKE_brush_alpha_get() */
660 } WeightPaintInfo;
661
662 static void do_weight_paint_vertex_single(
663         /* vars which remain the same for every vert */
664         const VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
665         /* vars which change on each stroke */
666         const uint index, float alpha, float paintweight)
667 {
668         Mesh *me = ob->data;
669         MDeformVert *dv = &me->dvert[index];
670         bool topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
671
672         MDeformWeight *dw;
673         float weight_prev;
674
675         /* mirror vars */
676         int index_mirr;
677         int vgroup_mirr;
678
679         MDeformVert *dv_mirr;
680         MDeformWeight *dw_mirr;
681
682         /* from now on we can check if mirrors enabled if this var is -1 and not bother with the flag */
683         if (me->editflag & ME_EDIT_MIRROR_X) {
684                 index_mirr = mesh_get_x_mirror_vert(ob, NULL, index, topology);
685                 vgroup_mirr = wpi->mirror.index;
686
687                 /* another possible error - mirror group _and_ active group are the same (which is fine),
688                  * but we also are painting onto a center vertex - this would paint the same weight twice */
689                 if (index_mirr == index && vgroup_mirr == wpi->active.index) {
690                         index_mirr = vgroup_mirr = -1;
691                 }
692         }
693         else {
694                 index_mirr = vgroup_mirr = -1;
695         }
696
697         if (wp->flag & VP_FLAG_VGROUP_RESTRICT) {
698                 dw = defvert_find_index(dv, wpi->active.index);
699         }
700         else {
701                 dw = defvert_verify_index(dv, wpi->active.index);
702         }
703
704         if (dw == NULL) {
705                 return;
706         }
707
708         /* get the mirror def vars */
709         if (index_mirr != -1) {
710                 dv_mirr = &me->dvert[index_mirr];
711                 if (wp->flag & VP_FLAG_VGROUP_RESTRICT) {
712                         dw_mirr = defvert_find_index(dv_mirr, vgroup_mirr);
713
714                         if (dw_mirr == NULL) {
715                                 index_mirr = vgroup_mirr = -1;
716                                 dv_mirr = NULL;
717                         }
718                 }
719                 else {
720                         if (index != index_mirr) {
721                                 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
722                         }
723                         else {
724                                 /* dv and dv_mirr are the same */
725                                 int totweight_prev = dv_mirr->totweight;
726                                 int dw_offset = (int)(dw - dv_mirr->dw);
727                                 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
728
729                                 /* if we added another, get our old one back */
730                                 if (totweight_prev != dv_mirr->totweight) {
731                                         dw = &dv_mirr->dw[dw_offset];
732                                 }
733                         }
734                 }
735         }
736         else {
737                 dv_mirr = NULL;
738                 dw_mirr = NULL;
739         }
740
741         if (!brush_use_accumulate(wp->paint.brush)) {
742                 MDeformVert *dvert_prev = ob->sculpt->mode.wpaint.dvert_prev;
743                 MDeformVert *dv_prev = defweight_prev_init(dvert_prev, me->dvert, index);
744                 if (index_mirr != -1) {
745                         defweight_prev_init(dvert_prev, me->dvert, index_mirr);
746                 }
747
748                 weight_prev = defvert_find_weight(dv_prev, wpi->active.index);
749         }
750         else {
751                 weight_prev = dw->weight;
752         }
753
754         /* If there are no normalize-locks or multipaint,
755          * then there is no need to run the more complicated checks */
756
757         {
758                 float new_weight = wpaint_blend(
759                         wp, weight_prev, alpha, paintweight,
760                         wpi->brush_alpha_value, wpi->do_flip);
761
762                 dw->weight = wpaint_clamp_monotonic(weight_prev, dw->weight, new_weight);
763
764                 /* WATCH IT: take care of the ordering of applying mirror -> normalize,
765                  * can give wrong results [#26193], least confusing if normalize is done last */
766
767                 /* apply mirror */
768                 if (index_mirr != -1) {
769                         /* copy, not paint again */
770                         dw_mirr->weight = dw->weight;
771                 }
772
773                 /* apply normalize */
774                 if (wpi->do_auto_normalize) {
775                         /* note on normalize - this used to be applied after painting and normalize all weights,
776                          * in some ways this is good because there is feedback where the more weights involved would
777                          * 'resist' so you couldn't instantly zero out other weights by painting 1.0 on the active.
778                          *
779                          * However this gave a problem since applying mirror, then normalize both verts
780                          * the resulting weight wont match on both sides.
781                          *
782                          * If this 'resisting', slower normalize is nicer, we could call
783                          * do_weight_paint_normalize_all() and only use...
784                          * do_weight_paint_normalize_all_active() when normalizing the mirror vertex.
785                          * - campbell
786                          */
787                         do_weight_paint_normalize_all_locked_try_active(
788                                 dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->active.lock);
789
790                         if (index_mirr != -1) {
791                                 /* only normalize if this is not a center vertex, else we get a conflict, normalizing twice */
792                                 if (index != index_mirr) {
793                                         do_weight_paint_normalize_all_locked_try_active(
794                                                 dv_mirr, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->mirror.lock);
795                                 }
796                                 else {
797                                         /* this case accounts for...
798                                          * - painting onto a center vertex of a mesh
799                                          * - x mirror is enabled
800                                          * - auto normalize is enabled
801                                          * - the group you are painting onto has a L / R version
802                                          *
803                                          * We want L/R vgroups to have the same weight but this cant be if both are over 0.5,
804                                          * We _could_ have special check for that, but this would need its own normalize function which
805                                          * holds 2 groups from changing at once.
806                                          *
807                                          * So! just balance out the 2 weights, it keeps them equal and everything normalized.
808                                          *
809                                          * While it wont hit the desired weight immediately as the user waggles their mouse,
810                                          * constant painting and re-normalizing will get there. this is also just simpler logic.
811                                          * - campbell */
812                                         dw_mirr->weight = dw->weight = (dw_mirr->weight + dw->weight) * 0.5f;
813                                 }
814                         }
815                 }
816         }
817 }
818
819 static void do_weight_paint_vertex_multi(
820         /* vars which remain the same for every vert */
821         const VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
822         /* vars which change on each stroke */
823         const uint index, float alpha, float paintweight)
824 {
825         Mesh *me = ob->data;
826         MDeformVert *dv = &me->dvert[index];
827         bool topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
828
829         /* mirror vars */
830         int index_mirr = -1;
831         MDeformVert *dv_mirr = NULL;
832
833         /* weights */
834         float curw, oldw, neww, change, curw_mirr, change_mirr;
835
836         /* from now on we can check if mirrors enabled if this var is -1 and not bother with the flag */
837         if (me->editflag & ME_EDIT_MIRROR_X) {
838                 index_mirr = mesh_get_x_mirror_vert(ob, NULL, index, topology);
839
840                 if (index_mirr != -1 && index_mirr != index) {
841                         dv_mirr = &me->dvert[index_mirr];
842                 }
843                 else {
844                         index_mirr = -1;
845                 }
846         }
847
848         /* compute weight change by applying the brush to average or sum of group weights */
849         curw = BKE_defvert_multipaint_collective_weight(
850                 dv, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
851
852         if (curw == 0.0f) {
853                 /* note: no weight to assign to this vertex, could add all groups? */
854                 return;
855         }
856
857         if (!brush_use_accumulate(wp->paint.brush)) {
858                 MDeformVert *dvert_prev = ob->sculpt->mode.wpaint.dvert_prev;
859                 MDeformVert *dv_prev = defweight_prev_init(dvert_prev, me->dvert, index);
860                 if (index_mirr != -1) {
861                         defweight_prev_init(dvert_prev, me->dvert, index_mirr);
862                 }
863
864                 oldw = BKE_defvert_multipaint_collective_weight(
865                         dv_prev, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
866         }
867         else {
868                 oldw = curw;
869         }
870
871         neww = wpaint_blend(wp, oldw, alpha, paintweight, wpi->brush_alpha_value, wpi->do_flip);
872         neww = wpaint_clamp_monotonic(oldw, curw, neww);
873
874         change = neww / curw;
875
876         /* verify for all groups that 0 < result <= 1 */
877         multipaint_clamp_change(dv, wpi->defbase_tot, wpi->defbase_sel, &change);
878
879         if (dv_mirr != NULL) {
880                 curw_mirr = BKE_defvert_multipaint_collective_weight(
881                         dv_mirr, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
882
883                 if (curw_mirr == 0.0f) {
884                         /* can't mirror into a zero weight vertex */
885                         dv_mirr = NULL;
886                 }
887                 else {
888                         /* mirror is changed to achieve the same collective weight value */
889                         float orig = change_mirr = curw * change / curw_mirr;
890
891                         multipaint_clamp_change(dv_mirr, wpi->defbase_tot, wpi->defbase_sel, &change_mirr);
892
893                         if (!multipaint_verify_change(dv_mirr, wpi->defbase_tot, change_mirr, wpi->defbase_sel)) {
894                                 return;
895                         }
896
897                         change *= change_mirr / orig;
898                 }
899         }
900
901         if (!multipaint_verify_change(dv, wpi->defbase_tot, change, wpi->defbase_sel)) {
902                 return;
903         }
904
905         /* apply validated change to vertex and mirror */
906         multipaint_apply_change(dv, wpi->defbase_tot, change, wpi->defbase_sel);
907
908         if (dv_mirr != NULL) {
909                 multipaint_apply_change(dv_mirr, wpi->defbase_tot, change_mirr, wpi->defbase_sel);
910         }
911
912         /* normalize */
913         if (wpi->do_auto_normalize) {
914                 do_weight_paint_normalize_all_locked_try_active(
915                         dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->active.lock);
916
917                 if (dv_mirr != NULL) {
918                         do_weight_paint_normalize_all_locked_try_active(
919                                 dv_mirr, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->active.lock);
920                 }
921         }
922 }
923
924 static void do_weight_paint_vertex(
925         /* vars which remain the same for every vert */
926         const VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
927         /* vars which change on each stroke */
928         const uint index, float alpha, float paintweight)
929 {
930         if (wpi->do_multipaint) {
931                 do_weight_paint_vertex_multi(wp, ob, wpi, index, alpha, paintweight);
932         }
933         else {
934                 do_weight_paint_vertex_single(wp, ob, wpi, index, alpha, paintweight);
935         }
936 }
937
938
939 /* Toggle operator for turning vertex paint mode on or off (copied from sculpt.c) */
940 static void vertex_paint_init_session(Scene *scene, Object *ob)
941 {
942         /* Create persistent sculpt mode data */
943         BKE_sculpt_toolsettings_data_ensure(scene);
944
945         if (ob->sculpt == NULL) {
946                 ob->sculpt = MEM_callocN(sizeof(SculptSession), "sculpt session");
947                 BKE_sculpt_update_mesh_elements(scene, scene->toolsettings->sculpt, ob, 0, false);
948         }
949 }
950
951 static void vertex_paint_init_session_data(const ToolSettings *ts, Object *ob)
952 {
953         /* Create maps */
954         struct SculptVertexPaintGeomMap *gmap = NULL;
955         const Brush *brush = NULL;
956         if (ob->mode == OB_MODE_VERTEX_PAINT) {
957                 gmap = &ob->sculpt->mode.vpaint.gmap;
958                 brush = BKE_paint_brush(&ts->vpaint->paint);
959                 ob->sculpt->mode_type = OB_MODE_VERTEX_PAINT;
960         }
961         else if (ob->mode == OB_MODE_WEIGHT_PAINT) {
962                 gmap = &ob->sculpt->mode.wpaint.gmap;
963                 brush = BKE_paint_brush(&ts->wpaint->paint);
964                 ob->sculpt->mode_type = OB_MODE_WEIGHT_PAINT;
965         }
966         else {
967                 ob->sculpt->mode_type = 0;
968                 BLI_assert(0);
969                 return;
970         }
971
972         Mesh *me = ob->data;
973
974         if (gmap->vert_to_loop == NULL) {
975                 gmap->vert_map_mem = NULL;
976                 gmap->vert_to_loop = NULL;
977                 gmap->poly_map_mem = NULL;
978                 gmap->vert_to_poly = NULL;
979                 BKE_mesh_vert_loop_map_create(
980                         &gmap->vert_to_loop,
981                         &gmap->vert_map_mem,
982                         me->mpoly, me->mloop, me->totvert, me->totpoly, me->totloop);
983                 BKE_mesh_vert_poly_map_create(
984                         &gmap->vert_to_poly,
985                         &gmap->poly_map_mem,
986                         me->mpoly, me->mloop, me->totvert, me->totpoly, me->totloop);
987         }
988
989         /* Create average brush arrays */
990         if (ob->mode == OB_MODE_VERTEX_PAINT) {
991                 if (!brush_use_accumulate(brush)) {
992                         if (ob->sculpt->mode.vpaint.previous_color == NULL) {
993                                 ob->sculpt->mode.vpaint.previous_color =
994                                         MEM_callocN(me->totloop * sizeof(uint), __func__);
995                         }
996                 }
997                 else {
998                         MEM_SAFE_FREE(ob->sculpt->mode.vpaint.previous_color);
999                 }
1000         }
1001         else if (ob->mode == OB_MODE_WEIGHT_PAINT) {
1002                 if (!brush_use_accumulate(brush)) {
1003                         if (ob->sculpt->mode.wpaint.alpha_weight == NULL) {
1004                                 ob->sculpt->mode.wpaint.alpha_weight =
1005                                         MEM_callocN(me->totvert * sizeof(float), __func__);
1006                         }
1007                         if (ob->sculpt->mode.wpaint.dvert_prev == NULL) {
1008                                 ob->sculpt->mode.wpaint.dvert_prev =
1009                                         MEM_callocN(me->totvert * sizeof(MDeformVert), __func__);
1010                                 MDeformVert *dv = ob->sculpt->mode.wpaint.dvert_prev;
1011                                 for (int i = 0; i < me->totvert; i++, dv++) {
1012                                         /* Use to show this isn't initialized, never apply to the mesh data. */
1013                                         dv->flag = 1;
1014                                 }
1015                         }
1016                 }
1017                 else {
1018                         MEM_SAFE_FREE(ob->sculpt->mode.wpaint.alpha_weight);
1019                         if (ob->sculpt->mode.wpaint.dvert_prev != NULL) {
1020                                 BKE_defvert_array_free_elems(ob->sculpt->mode.wpaint.dvert_prev, me->totvert);
1021                                 MEM_freeN(ob->sculpt->mode.wpaint.dvert_prev);
1022                                 ob->sculpt->mode.wpaint.dvert_prev = NULL;
1023                         }
1024                 }
1025         }
1026
1027 }
1028
1029 /* *************** set wpaint operator ****************** */
1030
1031 /**
1032  * \note Keep in sync with #vpaint_mode_toggle_exec
1033  */
1034 static int wpaint_mode_toggle_exec(bContext *C, wmOperator *op)
1035 {
1036         Object *ob = CTX_data_active_object(C);
1037         const int mode_flag = OB_MODE_WEIGHT_PAINT;
1038         const bool is_mode_set = (ob->mode & mode_flag) != 0;
1039         Scene *scene = CTX_data_scene(C);
1040         VPaint *wp = scene->toolsettings->wpaint;
1041         Mesh *me;
1042
1043         if (!is_mode_set) {
1044                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
1045                         return OPERATOR_CANCELLED;
1046                 }
1047         }
1048
1049         me = BKE_mesh_from_object(ob);
1050
1051         if (ob->mode & mode_flag) {
1052                 ob->mode &= ~mode_flag;
1053
1054                 if (me->editflag & ME_EDIT_PAINT_VERT_SEL) {
1055                         BKE_mesh_flush_select_from_verts(me);
1056                 }
1057                 else if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
1058                         BKE_mesh_flush_select_from_polys(me);
1059                 }
1060
1061                 /* weight paint specific */
1062                 ED_mesh_mirror_spatial_table(NULL, NULL, NULL, NULL, 'e');
1063                 ED_mesh_mirror_topo_table(NULL, NULL, 'e');
1064
1065                 /* If the cache is not released by a cancel or a done, free it now. */
1066                 if (ob->sculpt->cache) {
1067                         sculpt_cache_free(ob->sculpt->cache);
1068                         ob->sculpt->cache = NULL;
1069                 }
1070
1071                 BKE_sculptsession_free(ob);
1072
1073                 paint_cursor_delete_textures();
1074         }
1075         else {
1076                 ob->mode |= mode_flag;
1077
1078                 if (wp == NULL)
1079                         wp = scene->toolsettings->wpaint = new_vpaint();
1080
1081                 paint_cursor_start(C, weight_paint_poll);
1082
1083                 BKE_paint_init(scene, ePaintWeight, PAINT_CURSOR_WEIGHT_PAINT);
1084
1085                 /* weight paint specific */
1086                 ED_mesh_mirror_spatial_table(ob, NULL, NULL, NULL, 's');
1087                 ED_vgroup_sync_from_pose(ob);
1088
1089                 /* Create vertex/weight paint mode session data */
1090                 if (ob->sculpt) {
1091                         BKE_sculptsession_free(ob);
1092                 }
1093                 vertex_paint_init_session(scene, ob);
1094         }
1095
1096         /* Weightpaint works by overriding colors in mesh,
1097          * so need to make sure we recalc on enter and
1098          * exit (exit needs doing regardless because we
1099          * should redeform).
1100          */
1101         DAG_id_tag_update(&me->id, 0);
1102
1103         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
1104
1105         return OPERATOR_FINISHED;
1106 }
1107
1108 /* for switching to/from mode */
1109 static int paint_poll_test(bContext *C)
1110 {
1111         Object *ob = CTX_data_active_object(C);
1112         if (ob == NULL || ob->type != OB_MESH)
1113                 return 0;
1114         if (!ob->data || ID_IS_LINKED(ob->data))
1115                 return 0;
1116         if (CTX_data_edit_object(C))
1117                 return 0;
1118         return 1;
1119 }
1120
1121 void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
1122 {
1123
1124         /* identifiers */
1125         ot->name = "Weight Paint Mode";
1126         ot->idname = "PAINT_OT_weight_paint_toggle";
1127         ot->description = "Toggle weight paint mode in 3D view";
1128
1129         /* api callbacks */
1130         ot->exec = wpaint_mode_toggle_exec;
1131         ot->poll = paint_poll_test;
1132
1133         /* flags */
1134         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1135 }
1136
1137 /* ************ weight paint operator ********** */
1138
1139 struct WPaintData {
1140         ViewContext vc;
1141         struct NormalAnglePrecalc normal_angle_precalc;
1142
1143         struct WeightPaintGroupData active, mirror;
1144
1145         /* variables for auto normalize */
1146         const bool *vgroup_validmap; /* stores if vgroups tie to deforming bones or not */
1147         const bool *lock_flags;
1148
1149         /* variables for multipaint */
1150         const bool *defbase_sel;      /* set of selected groups */
1151         int defbase_tot_sel;          /* number of selected groups */
1152         bool do_multipaint;           /* true if multipaint enabled and multiple groups selected */
1153
1154         int defbase_tot;
1155
1156         /* original weight values for use in blur/smear */
1157         float *precomputed_weight;
1158         bool precomputed_weight_ready;
1159 };
1160
1161 /* Initialize the stroke cache invariants from operator properties */
1162 static void vwpaint_update_cache_invariants(
1163         bContext *C, const VPaint *vp, SculptSession *ss, wmOperator *op, const float mouse[2])
1164 {
1165         StrokeCache *cache;
1166         Scene *scene = CTX_data_scene(C);
1167         UnifiedPaintSettings *ups = &CTX_data_tool_settings(C)->unified_paint_settings;
1168         const Brush *brush = vp->paint.brush;
1169         ViewContext *vc = paint_stroke_view_context(op->customdata);
1170         Object *ob = CTX_data_active_object(C);
1171         float mat[3][3];
1172         float view_dir[3] = {0.0f, 0.0f, 1.0f};
1173         int mode;
1174
1175         /* VW paint needs to allocate stroke cache before update is called. */
1176         if (!ss->cache) {
1177                 cache = MEM_callocN(sizeof(StrokeCache), "stroke cache");
1178                 ss->cache = cache;
1179         }
1180         else {
1181                 cache = ss->cache;
1182         }
1183
1184         /* Initial mouse location */
1185         if (mouse)
1186                 copy_v2_v2(cache->initial_mouse, mouse);
1187         else
1188                 zero_v2(cache->initial_mouse);
1189
1190         mode = RNA_enum_get(op->ptr, "mode");
1191         cache->invert = mode == BRUSH_STROKE_INVERT;
1192         cache->alt_smooth = mode == BRUSH_STROKE_SMOOTH;
1193         /* not very nice, but with current events system implementation
1194          * we can't handle brush appearance inversion hotkey separately (sergey) */
1195         if (cache->invert) ups->draw_inverted = true;
1196         else ups->draw_inverted = false;
1197
1198         copy_v2_v2(cache->mouse, cache->initial_mouse);
1199         /* Truly temporary data that isn't stored in properties */
1200         cache->vc = vc;
1201         cache->brush = brush;
1202         cache->first_time = 1;
1203
1204         /* cache projection matrix */
1205         ED_view3d_ob_project_mat_get(cache->vc->rv3d, ob, cache->projection_mat);
1206
1207         invert_m4_m4(ob->imat, ob->obmat);
1208         copy_m3_m4(mat, cache->vc->rv3d->viewinv);
1209         mul_m3_v3(mat, view_dir);
1210         copy_m3_m4(mat, ob->imat);
1211         mul_m3_v3(mat, view_dir);
1212         normalize_v3_v3(cache->true_view_normal, view_dir);
1213
1214         copy_v3_v3(cache->view_normal, cache->true_view_normal);
1215         cache->bstrength = BKE_brush_alpha_get(scene, brush);
1216         cache->is_last_valid = false;
1217 }
1218
1219 /* Initialize the stroke cache variants from operator properties */
1220 static void vwpaint_update_cache_variants(bContext *C, VPaint *vp, Object *ob, PointerRNA *ptr)
1221 {
1222         Scene *scene = CTX_data_scene(C);
1223         SculptSession *ss = ob->sculpt;
1224         StrokeCache *cache = ss->cache;
1225         Brush *brush = BKE_paint_brush(&vp->paint);
1226
1227         /* This effects the actual brush radius, so things farther away
1228          * are compared with a larger radius and vise versa. */
1229         if (cache->first_time) {
1230                 RNA_float_get_array(ptr, "location", cache->true_location);
1231         }
1232
1233         RNA_float_get_array(ptr, "mouse", cache->mouse);
1234
1235         /* XXX: Use pressure value from first brush step for brushes which don't
1236          * support strokes (grab, thumb). They depends on initial state and
1237          * brush coord/pressure/etc.
1238          * It's more an events design issue, which doesn't split coordinate/pressure/angle
1239          * changing events. We should avoid this after events system re-design */
1240         if (paint_supports_dynamic_size(brush, ePaintSculpt) || cache->first_time) {
1241                 cache->pressure = RNA_float_get(ptr, "pressure");
1242         }
1243
1244         /* Truly temporary data that isn't stored in properties */
1245         if (cache->first_time) {
1246                 if (!BKE_brush_use_locked_size(scene, brush)) {
1247                         cache->initial_radius = paint_calc_object_space_radius(
1248                                 cache->vc, cache->true_location, BKE_brush_size_get(scene, brush));
1249                         BKE_brush_unprojected_radius_set(scene, brush, cache->initial_radius);
1250                 }
1251                 else {
1252                         cache->initial_radius = BKE_brush_unprojected_radius_get(scene, brush);
1253                 }
1254         }
1255
1256         if (BKE_brush_use_size_pressure(scene, brush) && paint_supports_dynamic_size(brush, ePaintSculpt)) {
1257                 cache->radius = cache->initial_radius * cache->pressure;
1258         }
1259         else {
1260                 cache->radius = cache->initial_radius;
1261         }
1262
1263         cache->radius_squared = cache->radius * cache->radius;
1264
1265         if (ss->pbvh) {
1266                 BKE_pbvh_update(ss->pbvh, PBVH_UpdateRedraw, NULL);
1267                 BKE_pbvh_update(ss->pbvh, PBVH_UpdateBB, NULL);
1268         }
1269 }
1270
1271 static bool wpaint_stroke_test_start(bContext *C, wmOperator *op, const float mouse[2])
1272 {
1273         Scene *scene = CTX_data_scene(C);
1274         struct PaintStroke *stroke = op->customdata;
1275         ToolSettings *ts = scene->toolsettings;
1276         Object *ob = CTX_data_active_object(C);
1277         Mesh *me = BKE_mesh_from_object(ob);
1278         struct WPaintData *wpd;
1279         struct WPaintVGroupIndex vgroup_index;
1280         int defbase_tot, defbase_tot_sel;
1281         bool *defbase_sel;
1282         SculptSession *ss = ob->sculpt;
1283         VPaint *vp = CTX_data_tool_settings(C)->wpaint;
1284
1285         if (ED_wpaint_ensure_data(C, op->reports, WPAINT_ENSURE_MIRROR, &vgroup_index) == false) {
1286                 return false;
1287         }
1288
1289         {
1290                 /* check if we are attempting to paint onto a locked vertex group,
1291                  * and other options disallow it from doing anything useful */
1292                 bDeformGroup *dg;
1293                 dg = BLI_findlink(&ob->defbase, vgroup_index.active);
1294                 if (dg->flag & DG_LOCK_WEIGHT) {
1295                         BKE_report(op->reports, RPT_WARNING, "Active group is locked, aborting");
1296                         return false;
1297                 }
1298                 if (vgroup_index.mirror != -1) {
1299                         dg = BLI_findlink(&ob->defbase, vgroup_index.mirror);
1300                         if (dg->flag & DG_LOCK_WEIGHT) {
1301                                 BKE_report(op->reports, RPT_WARNING, "Mirror group is locked, aborting");
1302                                 return false;
1303                         }
1304                 }
1305         }
1306
1307         /* check that multipaint groups are unlocked */
1308         defbase_tot = BLI_listbase_count(&ob->defbase);
1309         defbase_sel = BKE_object_defgroup_selected_get(ob, defbase_tot, &defbase_tot_sel);
1310
1311         if (ts->multipaint && defbase_tot_sel > 1) {
1312                 int i;
1313                 bDeformGroup *dg;
1314
1315                 if (me->editflag & ME_EDIT_MIRROR_X) {
1316                         BKE_object_defgroup_mirror_selection(ob, defbase_tot, defbase_sel, defbase_sel, &defbase_tot_sel);
1317                 }
1318
1319                 for (i = 0; i < defbase_tot; i++) {
1320                         if (defbase_sel[i]) {
1321                                 dg = BLI_findlink(&ob->defbase, i);
1322                                 if (dg->flag & DG_LOCK_WEIGHT) {
1323                                         BKE_report(op->reports, RPT_WARNING, "Multipaint group is locked, aborting");
1324                                         MEM_freeN(defbase_sel);
1325                                         return false;
1326                                 }
1327                         }
1328                 }
1329         }
1330
1331         /* ALLOCATIONS! no return after this line */
1332         /* make mode data storage */
1333         wpd = MEM_callocN(sizeof(struct WPaintData), "WPaintData");
1334         paint_stroke_set_mode_data(stroke, wpd);
1335         view3d_set_viewcontext(C, &wpd->vc);
1336         view_angle_limits_init(&wpd->normal_angle_precalc, vp->paint.brush->falloff_angle,
1337                                (vp->paint.brush->flag & BRUSH_FRONTFACE_FALLOFF) != 0);
1338
1339         wpd->active.index = vgroup_index.active;
1340         wpd->mirror.index = vgroup_index.mirror;
1341
1342         /* multipaint */
1343         wpd->defbase_tot = defbase_tot;
1344         wpd->defbase_sel = defbase_sel;
1345         wpd->defbase_tot_sel = defbase_tot_sel > 1 ? defbase_tot_sel : 1;
1346         wpd->do_multipaint = (ts->multipaint && defbase_tot_sel > 1);
1347
1348         /* set up auto-normalize, and generate map for detecting which
1349          * vgroups affect deform bones */
1350         wpd->lock_flags = BKE_object_defgroup_lock_flags_get(ob, wpd->defbase_tot);
1351         if (ts->auto_normalize || ts->multipaint || wpd->lock_flags) {
1352                 wpd->vgroup_validmap = BKE_object_defgroup_validmap_get(ob, wpd->defbase_tot);
1353         }
1354
1355         if (wpd->do_multipaint && ts->auto_normalize) {
1356                 bool *tmpflags;
1357                 tmpflags = MEM_mallocN(sizeof(bool) * defbase_tot, __func__);
1358                 if (wpd->lock_flags) {
1359                         BLI_array_binary_or(tmpflags, wpd->defbase_sel, wpd->lock_flags, wpd->defbase_tot);
1360                 }
1361                 else {
1362                         memcpy(tmpflags, wpd->defbase_sel, sizeof(*tmpflags) * wpd->defbase_tot);
1363                 }
1364                 wpd->active.lock = tmpflags;
1365         }
1366         else if (ts->auto_normalize) {
1367                 bool *tmpflags;
1368
1369                 tmpflags = wpd->lock_flags ?
1370                         MEM_dupallocN(wpd->lock_flags) :
1371                         MEM_callocN(sizeof(bool) * defbase_tot, __func__);
1372                 tmpflags[wpd->active.index] = true;
1373                 wpd->active.lock = tmpflags;
1374
1375                 tmpflags = wpd->lock_flags ?
1376                         MEM_dupallocN(wpd->lock_flags) :
1377                         MEM_callocN(sizeof(bool) * defbase_tot, __func__);
1378                 tmpflags[(wpd->mirror.index != -1) ? wpd->mirror.index : wpd->active.index] = true;
1379                 wpd->mirror.lock = tmpflags;
1380         }
1381
1382         if (ELEM(vp->paint.brush->vertexpaint_tool, PAINT_BLEND_SMEAR, PAINT_BLEND_BLUR)) {
1383                 wpd->precomputed_weight = MEM_mallocN(sizeof(float) * me->totvert, __func__);
1384         }
1385
1386         /* If not previously created, create vertex/weight paint mode session data */
1387         vertex_paint_init_session(scene, ob);
1388         vwpaint_update_cache_invariants(C, vp, ss, op, mouse);
1389         vertex_paint_init_session_data(ts, ob);
1390
1391         if (ob->sculpt->mode.wpaint.dvert_prev != NULL) {
1392                 MDeformVert *dv = ob->sculpt->mode.wpaint.dvert_prev;
1393                 for (int i = 0; i < me->totvert; i++, dv++) {
1394                         /* Use to show this isn't initialized, never apply to the mesh data. */
1395                         dv->flag = 1;
1396                 }
1397         }
1398
1399         return true;
1400 }
1401
1402 static float dot_vf3vs3(const float brushNormal[3], const short vertexNormal[3])
1403 {
1404         float normal[3];
1405         normal_short_to_float_v3(normal, vertexNormal);
1406         return dot_v3v3(brushNormal, normal);
1407 }
1408
1409 static void get_brush_alpha_data(
1410         const Scene *scene, const SculptSession *ss, const Brush *brush,
1411         float *r_brush_size_pressure, float *r_brush_alpha_value, float *r_brush_alpha_pressure)
1412 {
1413         *r_brush_size_pressure =
1414                 BKE_brush_size_get(scene, brush) *
1415                 (BKE_brush_use_size_pressure(scene, brush) ? ss->cache->pressure : 1.0f);
1416         *r_brush_alpha_value =
1417                 BKE_brush_alpha_get(scene, brush);
1418         *r_brush_alpha_pressure =
1419                 (BKE_brush_use_alpha_pressure(scene, brush) ? ss->cache->pressure : 1.0f);
1420 }
1421
1422 static float wpaint_get_active_weight(const MDeformVert *dv, const WeightPaintInfo *wpi)
1423 {
1424         if (wpi->do_multipaint) {
1425                 float weight = BKE_defvert_multipaint_collective_weight(
1426                      dv, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
1427
1428                 CLAMP(weight, 0.0f, 1.0f);
1429                 return weight;
1430         }
1431         else {
1432                 return defvert_find_weight(dv, wpi->active.index);
1433         }
1434 }
1435
1436 static void do_wpaint_precompute_weight_cb_ex(
1437         void *__restrict userdata,
1438         const int n,
1439         const ParallelRangeTLS *__restrict UNUSED(tls))
1440 {
1441         SculptThreadedTaskData *data = userdata;
1442         const MDeformVert *dv = &data->me->dvert[n];
1443
1444         data->wpd->precomputed_weight[n] = wpaint_get_active_weight(dv, data->wpi);
1445 }
1446
1447 static void precompute_weight_values(
1448         bContext *C, Object *ob, Brush *brush, struct WPaintData *wpd, WeightPaintInfo *wpi, Mesh *me)
1449 {
1450         if (wpd->precomputed_weight_ready && !brush_use_accumulate(brush))
1451                 return;
1452
1453         /* threaded loop over vertices */
1454         SculptThreadedTaskData data = {
1455                 .C = C, .ob = ob, .wpd = wpd, .wpi = wpi, .me = me,
1456         };
1457
1458         ParallelRangeSettings settings;
1459         BLI_parallel_range_settings_defaults(&settings);
1460         BLI_task_parallel_range(
1461                 0, me->totvert,
1462                 &data,
1463                 do_wpaint_precompute_weight_cb_ex,
1464                 &settings);
1465
1466         wpd->precomputed_weight_ready = true;
1467 }
1468
1469 static void do_wpaint_brush_blur_task_cb_ex(
1470         void *__restrict userdata,
1471         const int n,
1472         const ParallelRangeTLS *__restrict UNUSED(tls))
1473 {
1474         SculptThreadedTaskData *data = userdata;
1475         SculptSession *ss = data->ob->sculpt;
1476         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
1477         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.wpaint.gmap;
1478
1479         const Brush *brush = data->brush;
1480         const StrokeCache *cache = ss->cache;
1481         Scene *scene = CTX_data_scene(data->C);
1482
1483         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
1484         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
1485         const bool use_normal = vwpaint_use_normal(data->vp);
1486         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
1487         const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
1488
1489         SculptBrushTest test;
1490         SculptBrushTestFn sculpt_brush_test_sq_fn =
1491                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
1492         const float *sculpt_normal_frontface =
1493                 sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
1494
1495         /* For each vertex */
1496         PBVHVertexIter vd;
1497         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1498         {
1499                 /* Test to see if the vertex coordinates are within the spherical brush region. */
1500                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
1501                         /* For grid based pbvh, take the vert whose loop coopresponds to the current grid.
1502                          * Otherwise, take the current vert. */
1503                         const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
1504                         const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
1505                         const char v_flag = data->me->mvert[v_index].flag;
1506                         /* If the vertex is selected */
1507                         if (!(use_face_sel || use_vert_sel) || v_flag & SELECT) {
1508                                 /* Get the average poly weight */
1509                                 int total_hit_loops = 0;
1510                                 float weight_final = 0.0f;
1511                                 for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
1512                                         const int p_index = gmap->vert_to_poly[v_index].indices[j];
1513                                         const MPoly *mp = &data->me->mpoly[p_index];
1514
1515                                         total_hit_loops += mp->totloop;
1516                                         for (int k = 0; k < mp->totloop; k++) {
1517                                                 const int l_index = mp->loopstart + k;
1518                                                 const MLoop *ml = &data->me->mloop[l_index];
1519                                                 weight_final += data->wpd->precomputed_weight[ml->v];
1520                                         }
1521                                 }
1522
1523                                 /* Apply the weight to the vertex. */
1524                                 if (total_hit_loops != 0) {
1525                                         float brush_strength = cache->bstrength;
1526                                         const float angle_cos = (use_normal && vd.no) ?
1527                                                 dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
1528                                         if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
1529                                              (angle_cos > 0.0f)) &&
1530                                             ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
1531                                              view_angle_limits_apply_falloff(&data->wpd->normal_angle_precalc, angle_cos, &brush_strength)))
1532                                         {
1533                                                 const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
1534                                                 const float final_alpha =
1535                                                         brush_fade * brush_strength *
1536                                                         grid_alpha * brush_alpha_pressure;
1537
1538                                                 if ((brush->flag & BRUSH_ACCUMULATE) == 0) {
1539                                                         if (ss->mode.wpaint.alpha_weight[v_index] < final_alpha) {
1540                                                                 ss->mode.wpaint.alpha_weight[v_index] = final_alpha;
1541                                                         }
1542                                                         else {
1543                                                                 continue;
1544                                                         }
1545                                                 }
1546
1547                                                 weight_final /= total_hit_loops;
1548                                                 /* Only paint visable verts */
1549                                                 do_weight_paint_vertex(
1550                                                         data->vp, data->ob, data->wpi,
1551                                                         v_index, final_alpha, weight_final);
1552                                         }
1553                                 }
1554                         }
1555                 }
1556         }
1557         BKE_pbvh_vertex_iter_end;
1558 }
1559
1560 static void do_wpaint_brush_smear_task_cb_ex(
1561         void *__restrict userdata,
1562         const int n,
1563         const ParallelRangeTLS *__restrict UNUSED(tls))
1564 {
1565         SculptThreadedTaskData *data = userdata;
1566         SculptSession *ss = data->ob->sculpt;
1567         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
1568         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.wpaint.gmap;
1569
1570         const Brush *brush = data->brush;
1571         const Scene *scene = CTX_data_scene(data->C);
1572         const StrokeCache *cache = ss->cache;
1573         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
1574         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
1575         const bool use_normal = vwpaint_use_normal(data->vp);
1576         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
1577         const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
1578         float brush_dir[3];
1579
1580         sub_v3_v3v3(brush_dir, cache->location, cache->last_location);
1581         project_plane_v3_v3v3(brush_dir, brush_dir, cache->view_normal);
1582
1583         if (cache->is_last_valid && (normalize_v3(brush_dir) != 0.0f)) {
1584
1585                 SculptBrushTest test;
1586                 SculptBrushTestFn sculpt_brush_test_sq_fn =
1587                         sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
1588                 const float *sculpt_normal_frontface =
1589                         sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
1590
1591                 /* For each vertex */
1592                 PBVHVertexIter vd;
1593                 BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1594                 {
1595                         /* Test to see if the vertex coordinates are within the spherical brush region. */
1596                         if (sculpt_brush_test_sq_fn(&test, vd.co)) {
1597                                 /* For grid based pbvh, take the vert whose loop cooresponds to the current grid.
1598                                  * Otherwise, take the current vert. */
1599                                 const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
1600                                 const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
1601                                 const MVert *mv_curr = &data->me->mvert[v_index];
1602
1603                                 /* If the vertex is selected */
1604                                 if (!(use_face_sel || use_vert_sel) || mv_curr->flag & SELECT) {
1605                                         float brush_strength = cache->bstrength;
1606                                         const float angle_cos = (use_normal && vd.no) ?
1607                                                 dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
1608                                         if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
1609                                              (angle_cos > 0.0f)) &&
1610                                             ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
1611                                              view_angle_limits_apply_falloff(&data->wpd->normal_angle_precalc, angle_cos, &brush_strength)))
1612                                         {
1613                                                 bool do_color = false;
1614                                                 /* Minimum dot product between brush direction and current
1615                                                  * to neighbor direction is 0.0, meaning orthogonal. */
1616                                                 float stroke_dot_max = 0.0f;
1617
1618                                                 /* Get the color of the loop in the opposite direction of the brush movement
1619                                                  * (this callback is specifically for smear.) */
1620                                                 float weight_final = 0.0;
1621                                                 for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
1622                                                         const int p_index = gmap->vert_to_poly[v_index].indices[j];
1623                                                         const MPoly *mp = &data->me->mpoly[p_index];
1624                                                         const MLoop *ml_other = &data->me->mloop[mp->loopstart];
1625                                                         for (int k = 0; k < mp->totloop; k++, ml_other++) {
1626                                                                 const uint v_other_index = ml_other->v;
1627                                                                 if (v_other_index != v_index) {
1628                                                                         const MVert *mv_other = &data->me->mvert[v_other_index];
1629
1630                                                                         /* Get the direction from the selected vert to the neighbor. */
1631                                                                         float other_dir[3];
1632                                                                         sub_v3_v3v3(other_dir, mv_curr->co, mv_other->co);
1633                                                                         project_plane_v3_v3v3(other_dir, other_dir, cache->view_normal);
1634
1635                                                                         normalize_v3(other_dir);
1636
1637                                                                         const float stroke_dot = dot_v3v3(other_dir, brush_dir);
1638
1639                                                                         if (stroke_dot > stroke_dot_max) {
1640                                                                                 stroke_dot_max = stroke_dot;
1641                                                                                 weight_final = data->wpd->precomputed_weight[v_other_index];
1642                                                                                 do_color = true;
1643                                                                         }
1644                                                                 }
1645                                                         }
1646                                                 }
1647                                                 /* Apply weight to vertex */
1648                                                 if (do_color) {
1649                                                         const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
1650                                                         const float final_alpha =
1651                                                                 brush_fade * brush_strength *
1652                                                                 grid_alpha * brush_alpha_pressure;
1653
1654                                                         if (final_alpha <= 0.0f)
1655                                                                 continue;
1656
1657                                                         do_weight_paint_vertex(
1658                                                                 data->vp, data->ob, data->wpi,
1659                                                                 v_index, final_alpha, (float)weight_final);
1660                                                 }
1661                                         }
1662                                 }
1663                         }
1664                 }
1665                 BKE_pbvh_vertex_iter_end;
1666         }
1667 }
1668
1669 static void do_wpaint_brush_draw_task_cb_ex(
1670         void *__restrict userdata,
1671         const int n,
1672         const ParallelRangeTLS *__restrict UNUSED(tls))
1673 {
1674         SculptThreadedTaskData *data = userdata;
1675         SculptSession *ss = data->ob->sculpt;
1676         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
1677         const Scene *scene = CTX_data_scene(data->C);
1678
1679         const Brush *brush = data->brush;
1680         const StrokeCache *cache = ss->cache;
1681         /* note: normally `BKE_brush_weight_get(scene, brush)` is used,
1682          * however in this case we calculate a new weight each time. */
1683         const float paintweight = data->strength;
1684         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
1685         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
1686         const bool use_normal = vwpaint_use_normal(data->vp);
1687         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
1688         const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
1689
1690         SculptBrushTest test;
1691         SculptBrushTestFn sculpt_brush_test_sq_fn =
1692                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
1693         const float *sculpt_normal_frontface =
1694                 sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
1695
1696         /* For each vertex */
1697         PBVHVertexIter vd;
1698         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1699         {
1700                 /* Test to see if the vertex coordinates are within the spherical brush region. */
1701                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
1702                         /* Note: grids are 1:1 with corners (aka loops).
1703                          * For multires, take the vert whose loop cooresponds to the current grid.
1704                          * Otherwise, take the current vert. */
1705                         const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
1706                         const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
1707
1708                         const char v_flag = data->me->mvert[v_index].flag;
1709                         /* If the vertex is selected */
1710                         if (!(use_face_sel || use_vert_sel) || v_flag & SELECT) {
1711                                 float brush_strength = cache->bstrength;
1712                                 const float angle_cos = (use_normal && vd.no) ?
1713                                         dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
1714                                 if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
1715                                      (angle_cos > 0.0f)) &&
1716                                     ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
1717                                      view_angle_limits_apply_falloff(&data->wpd->normal_angle_precalc, angle_cos, &brush_strength)))
1718                                 {
1719                                         const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
1720                                         const float final_alpha = brush_fade * brush_strength * grid_alpha * brush_alpha_pressure;
1721
1722                                         if ((brush->flag & BRUSH_ACCUMULATE) == 0) {
1723                                                 if (ss->mode.wpaint.alpha_weight[v_index] < final_alpha) {
1724                                                         ss->mode.wpaint.alpha_weight[v_index] = final_alpha;
1725                                                 }
1726                                                 else {
1727                                                         continue;
1728                                                 }
1729                                         }
1730
1731                                         do_weight_paint_vertex(
1732                                                 data->vp, data->ob, data->wpi,
1733                                                 v_index, final_alpha, paintweight);
1734                                 }
1735                         }
1736                 }
1737         }
1738         BKE_pbvh_vertex_iter_end;
1739 }
1740
1741 static void do_wpaint_brush_calc_average_weight_cb_ex(
1742         void *__restrict userdata,
1743         const int n,
1744         const ParallelRangeTLS *__restrict UNUSED(tls))
1745 {
1746         SculptThreadedTaskData *data = userdata;
1747         SculptSession *ss = data->ob->sculpt;
1748         StrokeCache *cache = ss->cache;
1749         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
1750
1751         const bool use_normal = vwpaint_use_normal(data->vp);
1752         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
1753         const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
1754
1755         struct WPaintAverageAccum *accum = (struct WPaintAverageAccum *)data->custom_data + n;
1756         accum->len = 0;
1757         accum->value = 0.0;
1758
1759         SculptBrushTest test;
1760         SculptBrushTestFn sculpt_brush_test_sq_fn =
1761                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
1762         const float *sculpt_normal_frontface =
1763                 sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
1764
1765         /* For each vertex */
1766         PBVHVertexIter vd;
1767         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1768         {
1769                 /* Test to see if the vertex coordinates are within the spherical brush region. */
1770                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
1771                         const float angle_cos = (use_normal && vd.no) ?
1772                                 dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
1773                         if (angle_cos > 0.0 && BKE_brush_curve_strength(data->brush, sqrtf(test.dist), cache->radius) > 0.0) {
1774                                 const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
1775                                 // const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
1776                                 const char v_flag = data->me->mvert[v_index].flag;
1777
1778                                 /* If the vertex is selected. */
1779                                 if (!(use_face_sel || use_vert_sel) || v_flag & SELECT) {
1780                                         const MDeformVert *dv = &data->me->dvert[v_index];
1781                                         accum->len += 1;
1782                                         accum->value += wpaint_get_active_weight(dv, data->wpi);
1783                                 }
1784                         }
1785                 }
1786         }
1787         BKE_pbvh_vertex_iter_end;
1788 }
1789
1790 static void calculate_average_weight(SculptThreadedTaskData *data, PBVHNode **UNUSED(nodes), int totnode)
1791 {
1792         struct WPaintAverageAccum *accum = MEM_mallocN(sizeof(*accum) * totnode, __func__);
1793         data->custom_data = accum;
1794
1795         ParallelRangeSettings settings;
1796         BLI_parallel_range_settings_defaults(&settings);
1797         settings.use_threading = ((data->sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
1798         BLI_task_parallel_range(
1799                 0, totnode,
1800                 data,
1801                 do_wpaint_brush_calc_average_weight_cb_ex,
1802                 &settings);
1803
1804         uint accum_len = 0;
1805         double accum_weight = 0.0;
1806         for (int i = 0; i < totnode; i++) {
1807                 accum_len += accum[i].len;
1808                 accum_weight += accum[i].value;
1809         }
1810         if (accum_len != 0) {
1811                 accum_weight /= accum_len;
1812                 data->strength = (float)accum_weight;
1813         }
1814
1815         MEM_SAFE_FREE(data->custom_data);  /* 'accum' */
1816 }
1817
1818
1819 static void wpaint_paint_leaves(
1820         bContext *C, Object *ob, Sculpt *sd, VPaint *vp, struct WPaintData *wpd, WeightPaintInfo *wpi,
1821         Mesh *me, PBVHNode **nodes, int totnode)
1822 {
1823         Scene *scene = CTX_data_scene(C);
1824         const Brush *brush = ob->sculpt->cache->brush;
1825
1826         /* threaded loop over nodes */
1827         SculptThreadedTaskData data = {
1828                 .sd = sd, .ob = ob, .brush = brush, .nodes = nodes, .vp = vp, .wpd = wpd, .wpi = wpi, .me = me, .C = C,
1829         };
1830
1831         /* Use this so average can modify its weight without touching the brush. */
1832         data.strength = BKE_brush_weight_get(scene, brush);
1833
1834         ParallelRangeSettings settings;
1835         BLI_parallel_range_settings_defaults(&settings);
1836         /* NOTE: current mirroring code cannot be run in parallel */
1837         settings.use_threading = !(me->editflag & ME_EDIT_MIRROR_X);
1838
1839         switch (brush->vertexpaint_tool) {
1840                 case PAINT_BLEND_AVERAGE:
1841                         calculate_average_weight(&data, nodes, totnode);
1842                         BLI_task_parallel_range(
1843                                 0, totnode,
1844                                 &data,
1845                                 do_wpaint_brush_draw_task_cb_ex,
1846                                 &settings);
1847                         break;
1848                 case PAINT_BLEND_SMEAR:
1849                         BLI_task_parallel_range(
1850                                 0, totnode,
1851                                 &data,
1852                                 do_wpaint_brush_smear_task_cb_ex,
1853                                 &settings);
1854                         break;
1855                 case PAINT_BLEND_BLUR:
1856                         BLI_task_parallel_range(
1857                                 0, totnode,
1858                                 &data,
1859                                 do_wpaint_brush_blur_task_cb_ex,
1860                                 &settings);
1861                         break;
1862                 default:
1863                         BLI_task_parallel_range(
1864                                 0, totnode,
1865                                 &data,
1866                                 do_wpaint_brush_draw_task_cb_ex,
1867                                 &settings);
1868                         break;
1869         }
1870 }
1871
1872 static PBVHNode **vwpaint_pbvh_gather_generic(
1873         Object *ob, VPaint *wp, Sculpt *sd, Brush *brush, int *r_totnode)
1874 {
1875         SculptSession *ss = ob->sculpt;
1876         const bool use_normal = vwpaint_use_normal(wp);
1877         PBVHNode **nodes = NULL;
1878
1879         /* Build a list of all nodes that are potentially within the brush's area of influence */
1880         if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE) {
1881                 SculptSearchSphereData data = {
1882                         .ss = ss,
1883                         .sd = sd,
1884                         .radius_squared = ss->cache->radius_squared,
1885                         .original = true,
1886                 };
1887                 BKE_pbvh_search_gather(ss->pbvh, sculpt_search_sphere_cb, &data, &nodes, r_totnode);
1888                 if (use_normal) {
1889                         sculpt_pbvh_calc_area_normal(brush, ob, nodes, *r_totnode, true, ss->cache->sculpt_normal_symm);
1890                 }
1891                 else {
1892                         zero_v3(ss->cache->sculpt_normal_symm);
1893                 }
1894         }
1895         else {
1896                 struct DistRayAABB_Precalc dist_ray_to_aabb_precalc;
1897                 dist_squared_ray_to_aabb_v3_precalc(&dist_ray_to_aabb_precalc, ss->cache->location, ss->cache->view_normal);
1898                 SculptSearchCircleData data = {
1899                         .ss = ss,
1900                         .sd = sd,
1901                         .radius_squared = ss->cache->radius_squared,
1902                         .original = true,
1903                         .dist_ray_to_aabb_precalc = &dist_ray_to_aabb_precalc,
1904                 };
1905                 BKE_pbvh_search_gather(ss->pbvh, sculpt_search_circle_cb, &data, &nodes, r_totnode);
1906                 if (use_normal) {
1907                         copy_v3_v3(ss->cache->sculpt_normal_symm, ss->cache->view_normal);
1908                 }
1909                 else {
1910                         zero_v3(ss->cache->sculpt_normal_symm);
1911                 }
1912         }
1913         return nodes;
1914 }
1915
1916 static void wpaint_do_paint(
1917         bContext *C, Object *ob, VPaint *wp, Sculpt *sd, struct WPaintData *wpd, WeightPaintInfo *wpi,
1918         Mesh *me, Brush *brush, const char symm, const int axis, const int i, const float angle)
1919 {
1920         SculptSession *ss = ob->sculpt;
1921         ss->cache->radial_symmetry_pass = i;
1922         sculpt_cache_calc_brushdata_symm(ss->cache, symm, axis, angle);
1923
1924         int totnode;
1925         PBVHNode **nodes = vwpaint_pbvh_gather_generic(ob, wp, sd, brush, &totnode);
1926
1927         wpaint_paint_leaves(C, ob, sd, wp, wpd, wpi, me, nodes, totnode);
1928
1929         if (nodes)
1930                 MEM_freeN(nodes);
1931 }
1932
1933 static void wpaint_do_radial_symmetry(
1934         bContext *C, Object *ob, VPaint *wp, Sculpt *sd, struct WPaintData *wpd, WeightPaintInfo *wpi,
1935         Mesh *me, Brush *brush, const char symm, const int axis)
1936 {
1937         for (int i = 1; i < wp->radial_symm[axis - 'X']; i++) {
1938                 const float angle = (2.0 * M_PI) * i / wp->radial_symm[axis - 'X'];
1939                 wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, symm, axis, i, angle);
1940         }
1941 }
1942
1943 /* near duplicate of: sculpt.c's, 'do_symmetrical_brush_actions' and 'vpaint_do_symmetrical_brush_actions'. */
1944 static void wpaint_do_symmetrical_brush_actions(
1945         bContext *C, Object *ob, VPaint *wp, Sculpt *sd, struct WPaintData *wpd, WeightPaintInfo *wpi)
1946 {
1947         Brush *brush = BKE_paint_brush(&wp->paint);
1948         Mesh *me = ob->data;
1949         SculptSession *ss = ob->sculpt;
1950         StrokeCache *cache = ss->cache;
1951         const char symm = wp->paint.symmetry_flags & PAINT_SYMM_AXIS_ALL;
1952         int i = 0;
1953
1954         /* initial stroke */
1955         wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'X', 0, 0);
1956         wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'X');
1957         wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'Y');
1958         wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'Z');
1959
1960         cache->symmetry = symm;
1961
1962         /* 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 */
1963         for (i = 1; i <= symm; i++) {
1964                 if ((symm & i && (symm != 5 || i != 3) && (symm != 6 || (i != 3 && i != 5)))) {
1965                         cache->mirror_symmetry_pass = i;
1966                         cache->radial_symmetry_pass = 0;
1967                         sculpt_cache_calc_brushdata_symm(cache, i, 0, 0);
1968
1969                         if (i & (1 << 0)) {
1970                                 wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, i, 'X', 0, 0);
1971                                 wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, i, 'X');
1972                         }
1973                         if (i & (1 << 1)) {
1974                                 wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Y', 0, 0);
1975                                 wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Y');
1976                         }
1977                         if (i & (1 << 2)) {
1978                                 wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Z', 0, 0);
1979                                 wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Z');
1980                         }
1981                 }
1982         }
1983         copy_v3_v3(cache->true_last_location, cache->true_location);
1984         cache->is_last_valid = true;
1985 }
1986
1987 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
1988 {
1989         Scene *scene = CTX_data_scene(C);
1990         ToolSettings *ts = CTX_data_tool_settings(C);
1991         VPaint *wp = ts->wpaint;
1992         Brush *brush = BKE_paint_brush(&wp->paint);
1993         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
1994         ViewContext *vc;
1995         Object *ob = CTX_data_active_object(C);
1996
1997         SculptSession *ss = ob->sculpt;
1998         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
1999
2000         vwpaint_update_cache_variants(C, wp, ob, itemptr);
2001
2002         float mat[4][4];
2003         float mval[2];
2004
2005         const float brush_alpha_value = BKE_brush_alpha_get(scene, brush);
2006
2007         /* intentionally don't initialize as NULL, make sure we initialize all members below */
2008         WeightPaintInfo wpi;
2009
2010         /* cannot paint if there is no stroke data */
2011         if (wpd == NULL) {
2012                 /* XXX: force a redraw here, since even though we can't paint,
2013                  * at least view won't freeze until stroke ends */
2014                 ED_region_tag_redraw(CTX_wm_region(C));
2015                 return;
2016         }
2017
2018         vc = &wpd->vc;
2019         ob = vc->obact;
2020
2021         view3d_operator_needs_opengl(C);
2022         ED_view3d_init_mats_rv3d(ob, vc->rv3d);
2023
2024         /* load projection matrix */
2025         mul_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2026
2027
2028         /* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
2029         wpi.defbase_tot =        wpd->defbase_tot;
2030         wpi.defbase_sel =        wpd->defbase_sel;
2031         wpi.defbase_tot_sel =    wpd->defbase_tot_sel;
2032
2033         wpi.defbase_tot_unsel =  wpi.defbase_tot - wpi.defbase_tot_sel;
2034         wpi.active =             wpd->active;
2035         wpi.mirror =             wpd->mirror;
2036         wpi.lock_flags =         wpd->lock_flags;
2037         wpi.vgroup_validmap =    wpd->vgroup_validmap;
2038         wpi.do_flip =            RNA_boolean_get(itemptr, "pen_flip");
2039         wpi.do_multipaint =      wpd->do_multipaint;
2040         wpi.do_auto_normalize =  ((ts->auto_normalize != 0) && (wpi.vgroup_validmap != NULL));
2041         wpi.brush_alpha_value =  brush_alpha_value;
2042         /* *** done setting up WeightPaintInfo *** */
2043
2044         if (wpd->precomputed_weight) {
2045                 precompute_weight_values(C, ob, brush, wpd, &wpi, ob->data);
2046         }
2047
2048         wpaint_do_symmetrical_brush_actions(C, ob, wp, sd, wpd, &wpi);
2049
2050         swap_m4m4(vc->rv3d->persmat, mat);
2051
2052         /* calculate pivot for rotation around seletion if needed */
2053         /* also needed for "View Selected" on last stroke */
2054         paint_last_stroke_update(scene, vc->ar, mval);
2055
2056         DAG_id_tag_update(ob->data, 0);
2057         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2058         swap_m4m4(wpd->vc.rv3d->persmat, mat);
2059
2060         rcti r;
2061         if (sculpt_get_redraw_rect(vc->ar, CTX_wm_region_view3d(C), ob, &r)) {
2062                 if (ss->cache) {
2063                         ss->cache->current_r = r;
2064                 }
2065
2066                 /* previous is not set in the current cache else
2067                  * the partial rect will always grow */
2068                 if (ss->cache) {
2069                         if (!BLI_rcti_is_empty(&ss->cache->previous_r))
2070                                 BLI_rcti_union(&r, &ss->cache->previous_r);
2071                 }
2072
2073                 r.xmin += vc->ar->winrct.xmin - 2;
2074                 r.xmax += vc->ar->winrct.xmin + 2;
2075                 r.ymin += vc->ar->winrct.ymin - 2;
2076                 r.ymax += vc->ar->winrct.ymin + 2;
2077
2078                 ss->partial_redraw = 1;
2079         }
2080         ED_region_tag_redraw_partial(vc->ar, &r);
2081 }
2082
2083 static void wpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2084 {
2085         Object *ob = CTX_data_active_object(C);
2086         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2087
2088         if (wpd) {
2089                 if (wpd->defbase_sel)
2090                         MEM_freeN((void *)wpd->defbase_sel);
2091                 if (wpd->vgroup_validmap)
2092                         MEM_freeN((void *)wpd->vgroup_validmap);
2093                 if (wpd->lock_flags)
2094                         MEM_freeN((void *)wpd->lock_flags);
2095                 if (wpd->active.lock)
2096                         MEM_freeN((void *)wpd->active.lock);
2097                 if (wpd->mirror.lock)
2098                         MEM_freeN((void *)wpd->mirror.lock);
2099                 if (wpd->precomputed_weight)
2100                         MEM_freeN(wpd->precomputed_weight);
2101
2102                 MEM_freeN(wpd);
2103         }
2104
2105         /* and particles too */
2106         if (ob->particlesystem.first) {
2107                 ParticleSystem *psys;
2108                 int i;
2109
2110                 for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2111                         for (i = 0; i < PSYS_TOT_VG; i++) {
2112                                 if (psys->vgroup[i] == ob->actdef) {
2113                                         psys->recalc |= PSYS_RECALC_RESET;
2114                                         break;
2115                                 }
2116                         }
2117                 }
2118         }
2119
2120         DAG_id_tag_update(ob->data, 0);
2121
2122         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2123
2124         sculpt_cache_free(ob->sculpt->cache);
2125         ob->sculpt->cache = NULL;
2126 }
2127
2128
2129 static int wpaint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2130 {
2131         int retval;
2132
2133         op->customdata = paint_stroke_new(
2134                 C, op, sculpt_stroke_get_location, wpaint_stroke_test_start,
2135                 wpaint_stroke_update_step, NULL,
2136                 wpaint_stroke_done, event->type);
2137
2138         if ((retval = op->type->modal(C, op, event)) == OPERATOR_FINISHED) {
2139                 paint_stroke_data_free(op);
2140                 return OPERATOR_FINISHED;
2141         }
2142         /* add modal handler */
2143         WM_event_add_modal_handler(C, op);
2144
2145         OPERATOR_RETVAL_CHECK(retval);
2146         BLI_assert(retval == OPERATOR_RUNNING_MODAL);
2147
2148         return OPERATOR_RUNNING_MODAL;
2149 }
2150
2151 static int wpaint_exec(bContext *C, wmOperator *op)
2152 {
2153         op->customdata = paint_stroke_new(
2154                 C, op, sculpt_stroke_get_location, wpaint_stroke_test_start,
2155                 wpaint_stroke_update_step, NULL,
2156                 wpaint_stroke_done, 0);
2157
2158         /* frees op->customdata */
2159         paint_stroke_exec(C, op);
2160
2161         return OPERATOR_FINISHED;
2162 }
2163
2164 static void wpaint_cancel(bContext *C, wmOperator *op)
2165 {
2166         Object *ob = CTX_data_active_object(C);
2167         if (ob->sculpt->cache) {
2168                 sculpt_cache_free(ob->sculpt->cache);
2169                 ob->sculpt->cache = NULL;
2170         }
2171
2172         paint_stroke_cancel(C, op);
2173 }
2174
2175 void PAINT_OT_weight_paint(wmOperatorType *ot)
2176 {
2177         /* identifiers */
2178         ot->name = "Weight Paint";
2179         ot->idname = "PAINT_OT_weight_paint";
2180         ot->description = "Paint a stroke in the current vertex group's weights";
2181
2182         /* api callbacks */
2183         ot->invoke = wpaint_invoke;
2184         ot->modal = paint_stroke_modal;
2185         ot->exec = wpaint_exec;
2186         ot->poll = weight_paint_poll;
2187         ot->cancel = wpaint_cancel;
2188
2189         /* flags */
2190         ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
2191
2192         paint_stroke_operator_properties(ot);
2193 }
2194
2195 /* ************ set / clear vertex paint mode ********** */
2196
2197 /**
2198  * \note Keep in sync with #wpaint_mode_toggle_exec
2199  */
2200 static int vpaint_mode_toggle_exec(bContext *C, wmOperator *op)
2201 {
2202         Object *ob = CTX_data_active_object(C);
2203         const int mode_flag = OB_MODE_VERTEX_PAINT;
2204         const bool is_mode_set = (ob->mode & mode_flag) != 0;
2205         Scene *scene = CTX_data_scene(C);
2206         VPaint *vp = scene->toolsettings->vpaint;
2207         Mesh *me;
2208
2209         if (!is_mode_set) {
2210                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
2211                         return OPERATOR_CANCELLED;
2212                 }
2213         }
2214
2215         me = BKE_mesh_from_object(ob);
2216
2217         /* toggle: end vpaint */
2218         if (is_mode_set) {
2219                 ob->mode &= ~mode_flag;
2220
2221                 if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
2222                         BKE_mesh_flush_select_from_polys(me);
2223                 }
2224                 else if (me->editflag & ME_EDIT_PAINT_VERT_SEL) {
2225                         BKE_mesh_flush_select_from_verts(me);
2226                 }
2227
2228                 /* If the cache is not released by a cancel or a done, free it now. */
2229                 if (ob->sculpt->cache) {
2230                         sculpt_cache_free(ob->sculpt->cache);
2231                         ob->sculpt->cache = NULL;
2232                 }
2233
2234                 BKE_sculptsession_free(ob);
2235
2236                 paint_cursor_delete_textures();
2237         }
2238         else {
2239                 ob->mode |= mode_flag;
2240
2241                 ED_mesh_color_ensure(me, NULL);
2242
2243                 if (vp == NULL)
2244                         vp = scene->toolsettings->vpaint = new_vpaint();
2245
2246                 paint_cursor_start(C, vertex_paint_poll);
2247
2248                 BKE_paint_init(scene, ePaintVertex, PAINT_CURSOR_VERTEX_PAINT);
2249
2250                 /* Create vertex/weight paint mode session data */
2251                 if (ob->sculpt) {
2252                         if (ob->sculpt->cache) {
2253                                 sculpt_cache_free(ob->sculpt->cache);
2254                                 ob->sculpt->cache = NULL;
2255                         }
2256                         BKE_sculptsession_free(ob);
2257                 }
2258                 vertex_paint_init_session(scene, ob);
2259         }
2260
2261         /* update modifier stack for mapping requirements */
2262         DAG_id_tag_update(&me->id, 0);
2263
2264         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
2265
2266         return OPERATOR_FINISHED;
2267 }
2268
2269 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2270 {
2271         /* identifiers */
2272         ot->name = "Vertex Paint Mode";
2273         ot->idname = "PAINT_OT_vertex_paint_toggle";
2274         ot->description = "Toggle the vertex paint mode in 3D view";
2275
2276         /* api callbacks */
2277         ot->exec = vpaint_mode_toggle_exec;
2278         ot->poll = paint_poll_test;
2279
2280         /* flags */
2281         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2282 }
2283
2284
2285
2286 /* ********************** vertex paint operator ******************* */
2287
2288 /* Implementation notes:
2289  *
2290  * Operator->invoke()
2291  * - validate context (add mcol)
2292  * - create customdata storage
2293  * - call paint once (mouse click)
2294  * - add modal handler
2295  *
2296  * Operator->modal()
2297  * - for every mousemove, apply vertex paint
2298  * - exit on mouse release, free customdata
2299  *   (return OPERATOR_FINISHED also removes handler and operator)
2300  *
2301  * For future:
2302  * - implement a stroke event (or mousemove with past positons)
2303  * - revise whether op->customdata should be added in object, in set_vpaint
2304  */
2305
2306 typedef struct PolyFaceMap {
2307         struct PolyFaceMap *next, *prev;
2308         int facenr;
2309 } PolyFaceMap;
2310
2311 struct VPaintData {
2312         ViewContext vc;
2313         struct NormalAnglePrecalc normal_angle_precalc;
2314
2315         uint paintcol;
2316
2317         struct VertProjHandle *vp_handle;
2318         struct DMCoNo *vertexcosnos;
2319
2320         /* modify 'me->mcol' directly, since the derived mesh is drawing from this
2321          * array, otherwise we need to refresh the modifier stack */
2322         bool use_fast_update;
2323
2324         /* loops tagged as having been painted, to apply shared vertex color
2325          * blending only to modified loops */
2326         bool *mlooptag;
2327
2328         bool is_texbrush;
2329
2330         /* Special storage for smear brush, avoid feedback loop - update each step. */
2331         struct {
2332                 uint *color_prev;
2333                 uint *color_curr;
2334         } smear;
2335 };
2336
2337 static bool vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const float mouse[2])
2338 {
2339         Scene *scene = CTX_data_scene(C);
2340         ToolSettings *ts = scene->toolsettings;
2341         struct PaintStroke *stroke = op->customdata;
2342         VPaint *vp = ts->vpaint;
2343         Brush *brush = BKE_paint_brush(&vp->paint);
2344         struct VPaintData *vpd;
2345         Object *ob = CTX_data_active_object(C);
2346         Mesh *me;
2347         SculptSession *ss = ob->sculpt;
2348
2349         /* context checks could be a poll() */
2350         me = BKE_mesh_from_object(ob);
2351         if (me == NULL || me->totpoly == 0)
2352                 return false;
2353
2354         ED_mesh_color_ensure(me, NULL);
2355         if (me->mloopcol == NULL)
2356                 return false;
2357
2358         /* make mode data storage */
2359         vpd = MEM_callocN(sizeof(*vpd), "VPaintData");
2360         paint_stroke_set_mode_data(stroke, vpd);
2361         view3d_set_viewcontext(C, &vpd->vc);
2362         view_angle_limits_init(&vpd->normal_angle_precalc, vp->paint.brush->falloff_angle,
2363                                (vp->paint.brush->flag & BRUSH_FRONTFACE_FALLOFF) != 0);
2364
2365         vpd->paintcol = vpaint_get_current_col(scene, vp);
2366
2367         vpd->is_texbrush = !(brush->vertexpaint_tool == PAINT_BLEND_BLUR) &&
2368                            brush->mtex.tex;
2369
2370         /* are we painting onto a modified mesh?,
2371          * if not we can skip face map trickiness */
2372         if (vertex_paint_use_fast_update_check(ob)) {
2373                 vpd->use_fast_update = true;
2374 /*              printf("Fast update!\n");*/
2375         }
2376         else {
2377                 vpd->use_fast_update = false;
2378 /*              printf("No fast update!\n");*/
2379         }
2380
2381         /* to keep tracked of modified loops for shared vertex color blending */
2382         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2383                 vpd->mlooptag = MEM_mallocN(sizeof(bool) * me->totloop, "VPaintData mlooptag");
2384         }
2385
2386         if (brush->vertexpaint_tool == PAINT_BLEND_SMEAR) {
2387                 vpd->smear.color_prev = MEM_mallocN(sizeof(uint) * me->totloop, __func__);
2388                 memcpy(vpd->smear.color_prev, me->mloopcol, sizeof(uint) * me->totloop);
2389                 vpd->smear.color_curr = MEM_dupallocN(vpd->smear.color_prev);
2390         }
2391
2392         /* Create projection handle */
2393         if (vpd->is_texbrush) {
2394                 ob->sculpt->building_vp_handle = true;
2395                 vpd->vp_handle = ED_vpaint_proj_handle_create(scene, ob, &vpd->vertexcosnos);
2396                 ob->sculpt->building_vp_handle = false;
2397         }
2398
2399         /* If not previously created, create vertex/weight paint mode session data */
2400         vertex_paint_init_session(scene, ob);
2401         vwpaint_update_cache_invariants(C, vp, ss, op, mouse);
2402         vertex_paint_init_session_data(ts, ob);
2403
2404         if (ob->sculpt->mode.vpaint.previous_color != NULL) {
2405                 memset(ob->sculpt->mode.vpaint.previous_color, 0, sizeof(uint) * me->totloop);
2406         }
2407
2408         return 1;
2409 }
2410
2411 static void do_vpaint_brush_calc_average_color_cb_ex(
2412         void *__restrict userdata,
2413         const int n,
2414         const ParallelRangeTLS *__restrict UNUSED(tls))
2415 {
2416         SculptThreadedTaskData *data = userdata;
2417         SculptSession *ss = data->ob->sculpt;
2418         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
2419         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
2420
2421         StrokeCache *cache = ss->cache;
2422         uint *lcol = data->lcol;
2423         char *col;
2424         const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
2425
2426         struct VPaintAverageAccum *accum = (struct VPaintAverageAccum *)data->custom_data + n;
2427         accum->len = 0;
2428         memset(accum->value, 0, sizeof(accum->value));
2429
2430         SculptBrushTest test;
2431         SculptBrushTestFn sculpt_brush_test_sq_fn =
2432                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2433
2434         /* For each vertex */
2435         PBVHVertexIter vd;
2436         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2437         {
2438                 /* Test to see if the vertex coordinates are within the spherical brush region. */
2439                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2440                         const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
2441                         if (BKE_brush_curve_strength(data->brush, 0.0, cache->radius) > 0.0) {
2442                                 /* If the vertex is selected for painting. */
2443                                 const MVert *mv = &data->me->mvert[v_index];
2444                                 if (!use_vert_sel || mv->flag & SELECT) {
2445                                         accum->len += gmap->vert_to_loop[v_index].count;
2446                                         /* if a vertex is within the brush region, then add it's color to the blend. */
2447                                         for (int j = 0; j < gmap->vert_to_loop[v_index].count; j++) {
2448                                                 const int l_index = gmap->vert_to_loop[v_index].indices[j];
2449                                                 col = (char *)(&lcol[l_index]);
2450                                                 /* Color is squared to compensate the sqrt color encoding. */
2451                                                 accum->value[0] += col[0] * col[0];
2452                                                 accum->value[1] += col[1] * col[1];
2453                                                 accum->value[2] += col[2] * col[2];
2454                                         }
2455                                 }
2456                         }
2457                 }
2458         }
2459         BKE_pbvh_vertex_iter_end;
2460 }
2461
2462 static float tex_color_alpha_ubyte(
2463         SculptThreadedTaskData *data, const float v_co[3],
2464         uint *r_color)
2465 {
2466         float rgba[4];
2467         float rgba_br[3];
2468         tex_color_alpha(data->vp, &data->vpd->vc, v_co, rgba);
2469         rgb_uchar_to_float(rgba_br, (const uchar *)&data->vpd->paintcol);
2470         mul_v3_v3(rgba_br, rgba);
2471         rgb_float_to_uchar((uchar *)r_color, rgba_br);
2472         return rgba[3];
2473 }
2474
2475 static void do_vpaint_brush_draw_task_cb_ex(
2476         void *__restrict userdata, 
2477         const int n,
2478         const ParallelRangeTLS *__restrict UNUSED(tls))
2479 {
2480         SculptThreadedTaskData *data = userdata;
2481         SculptSession *ss = data->ob->sculpt;
2482         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
2483         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
2484
2485         const Brush *brush = data->brush;
2486         const StrokeCache *cache = ss->cache;
2487         uint *lcol = data->lcol;
2488         const Scene *scene = CTX_data_scene(data->C);
2489         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
2490         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
2491         const bool use_normal = vwpaint_use_normal(data->vp);
2492         const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
2493         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
2494
2495         SculptBrushTest test;
2496         SculptBrushTestFn sculpt_brush_test_sq_fn =
2497                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2498         const float *sculpt_normal_frontface =
2499                 sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
2500
2501         /* For each vertex */
2502         PBVHVertexIter vd;
2503         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2504         {
2505                 /* Test to see if the vertex coordinates are within the spherical brush region. */
2506                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2507                         /* Note: Grids are 1:1 with corners (aka loops).
2508                          * For grid based pbvh, take the vert whose loop cooresponds to the current grid.
2509                          * Otherwise, take the current vert. */
2510                         const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
2511                         const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
2512                         const MVert *mv = &data->me->mvert[v_index];
2513
2514                         /* If the vertex is selected for painting. */
2515                         if (!use_vert_sel || mv->flag & SELECT) {
2516                                 /* Calc the dot prod. between ray norm on surf and current vert
2517                                  * (ie splash prevention factor), and only paint front facing verts. */
2518                                 float brush_strength = cache->bstrength;
2519                                 const float angle_cos = (use_normal && vd.no) ?
2520                                         dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
2521                                 if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
2522                                      (angle_cos > 0.0f)) &&
2523                                     ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
2524                                      view_angle_limits_apply_falloff(&data->vpd->normal_angle_precalc, angle_cos, &brush_strength)))
2525                                 {
2526                                         const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
2527                                         uint color_final = data->vpd->paintcol;
2528
2529                                         /* If we're painting with a texture, sample the texture color and alpha. */
2530                                         float tex_alpha = 1.0;
2531                                         if (data->vpd->is_texbrush) {
2532                                                 /* Note: we may want to paint alpha as vertex color alpha. */
2533                                                 tex_alpha = tex_color_alpha_ubyte(
2534                                                         data, data->vpd->vertexcosnos[v_index].co,
2535                                                         &color_final);
2536                                         }
2537                                         /* For each poly owning this vert, paint each loop belonging to this vert. */
2538                                         for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
2539                                                 const int p_index = gmap->vert_to_poly[v_index].indices[j];
2540                                                 const int l_index = gmap->vert_to_loop[v_index].indices[j];
2541                                                 BLI_assert(data->me->mloop[l_index].v == v_index);
2542                                                 const MPoly *mp = &data->me->mpoly[p_index];
2543                                                 if (!use_face_sel || mp->flag & ME_FACE_SEL) {
2544                                                         uint color_orig = 0;  /* unused when array is NULL */
2545                                                         if (ss->mode.vpaint.previous_color != NULL) {
2546                                                                 /* Get the previous loop color */
2547                                                                 if (ss->mode.vpaint.previous_color[l_index] == 0) {
2548                                                                         ss->mode.vpaint.previous_color[l_index] = lcol[l_index];
2549                                                                 }
2550                                                                 color_orig = ss->mode.vpaint.previous_color[l_index];
2551                                                         }
2552                                                         const float final_alpha =
2553                                                                 255 * brush_fade * brush_strength *
2554                                                                 tex_alpha * brush_alpha_pressure * grid_alpha;
2555
2556                                                         /* Mix the new color with the original based on final_alpha. */
2557                                                         lcol[l_index] = vpaint_blend(
2558                                                                 data->vp, lcol[l_index], color_orig, color_final,
2559                                                                 final_alpha, 255 * brush_strength);
2560                                                 }
2561                                         }
2562                                 }
2563                         }
2564                 }
2565         }
2566         BKE_pbvh_vertex_iter_end;
2567 }
2568
2569 static void do_vpaint_brush_blur_task_cb_ex(
2570         void *__restrict userdata,
2571         const int n,
2572         const ParallelRangeTLS *__restrict UNUSED(tls))
2573 {
2574         SculptThreadedTaskData *data = userdata;
2575         SculptSession *ss = data->ob->sculpt;
2576         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
2577
2578         Scene *scene = CTX_data_scene(data->C);
2579         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
2580         const Brush *brush = data->brush;
2581         const StrokeCache *cache = ss->cache;
2582         uint *lcol = data->lcol;
2583         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
2584         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
2585         const bool use_normal = vwpaint_use_normal(data->vp);
2586         const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
2587         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
2588
2589         SculptBrushTest test;
2590         SculptBrushTestFn sculpt_brush_test_sq_fn =
2591                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2592         const float *sculpt_normal_frontface =
2593                 sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
2594
2595         /* For each vertex */
2596         PBVHVertexIter vd;
2597         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2598         {
2599                 /* Test to see if the vertex coordinates are within the spherical brush region. */
2600                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2601                         /* For grid based pbvh, take the vert whose loop cooresponds to the current grid.
2602                          * Otherwise, take the current vert. */
2603                         const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
2604                         const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
2605                         const MVert *mv = &data->me->mvert[v_index];
2606
2607                         /* If the vertex is selected for painting. */
2608                         if (!use_vert_sel || mv->flag & SELECT) {
2609                                 float brush_strength = cache->bstrength;
2610                                 const float angle_cos = (use_normal && vd.no) ?
2611                                         dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
2612                                 if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
2613                                      (angle_cos > 0.0f)) &&
2614                                     ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
2615                                      view_angle_limits_apply_falloff(&data->vpd->normal_angle_precalc, angle_cos, &brush_strength)))
2616                                 {
2617                                         const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
2618
2619                                         /* Get the average poly color */
2620                                         uint color_final = 0;
2621                                         int total_hit_loops = 0;
2622                                         uint blend[4] = {0};
2623                                         for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
2624                                                 int p_index = gmap->vert_to_poly[v_index].indices[j];
2625                                                 const MPoly *mp = &data->me->mpoly[p_index];
2626                                                 if (!use_face_sel || mp->flag & ME_FACE_SEL) {
2627                                                         total_hit_loops += mp->totloop;
2628                                                         for (int k = 0; k < mp->totloop; k++) {
2629                                                                 const uint l_index = mp->loopstart + k;
2630                                                                 const char *col = (const char *)(&lcol[l_index]);
2631                                                                 /* Color is squared to compensate the sqrt color encoding. */
2632                                                                 blend[0] += (uint)col[0] * (uint)col[0];
2633                                                                 blend[1] += (uint)col[1] * (uint)col[1];
2634                                                                 blend[2] += (uint)col[2] * (uint)col[2];
2635                                                                 blend[3] += (uint)col[3] * (uint)col[3];
2636                                                         }
2637                                                 }
2638                                         }
2639                                         if (total_hit_loops != 0) {
2640                                                 /* Use rgb^2 color averaging. */
2641                                                 char *col = (char *)(&color_final);
2642                                                 col[0] = round_fl_to_uchar(sqrtf(divide_round_i(blend[0], total_hit_loops)));
2643                                                 col[1] = round_fl_to_uchar(sqrtf(divide_round_i(blend[1], total_hit_loops)));
2644                                                 col[2] = round_fl_to_uchar(sqrtf(divide_round_i(blend[2], total_hit_loops)));
2645                                                 col[3] = round_fl_to_uchar(sqrtf(divide_round_i(blend[3], total_hit_loops)));
2646
2647                                                 /* For each poly owning this vert, paint each loop belonging to this vert. */
2648                                                 for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
2649                                                         const int p_index = gmap->vert_to_poly[v_index].indices[j];
2650                                                         const int l_index = gmap->vert_to_loop[v_index].indices[j];
2651                                                         BLI_assert(data->me->mloop[l_index].v == v_index);
2652                                                         const MPoly *mp = &data->me->mpoly[p_index];
2653                                                         if (!use_face_sel || mp->flag & ME_FACE_SEL) {
2654                                                                 uint color_orig = 0;  /* unused when array is NULL */
2655                                                                 if (ss->mode.vpaint.previous_color != NULL) {
2656                                                                         /* Get the previous loop color */
2657                                                                         if (ss->mode.vpaint.previous_color[l_index] == 0) {
2658                                                                                 ss->mode.vpaint.previous_color[l_index] = lcol[l_index];
2659                                                                         }
2660                                                                         color_orig = ss->mode.vpaint.previous_color[l_index];
2661                                                                 }
2662                                                                 const float final_alpha =
2663                                                                         255 * brush_fade * brush_strength *
2664                                                                         brush_alpha_pressure * grid_alpha;
2665                                                                 /* Mix the new color with the original
2666                                                                  * based on the brush strength and the curve. */
2667                                                                 lcol[l_index] = vpaint_blend(
2668                                                                         data->vp, lcol[l_index], color_orig, *((uint *)col),
2669                                                                         final_alpha, 255 * brush_strength);
2670                                                         }
2671                                                 }
2672                                         }
2673                                 }
2674                         }
2675                 }
2676         }
2677         BKE_pbvh_vertex_iter_end;
2678 }
2679
2680 static void do_vpaint_brush_smear_task_cb_ex(
2681         void *__restrict userdata,
2682         const int n,
2683         const ParallelRangeTLS *__restrict UNUSED(tls))
2684 {
2685         SculptThreadedTaskData *data = userdata;
2686         SculptSession *ss = data->ob->sculpt;
2687         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
2688
2689         Scene *scene = CTX_data_scene(data->C);
2690         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
2691         const Brush *brush = data->brush;
2692         const StrokeCache *cache = ss->cache;
2693         uint *lcol = data->lcol;
2694         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
2695         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
2696         float brush_dir[3];
2697         const bool use_normal = vwpaint_use_normal(data->vp);
2698         const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
2699         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
2700
2701         sub_v3_v3v3(brush_dir, cache->location, cache->last_location);
2702         project_plane_v3_v3v3(brush_dir, brush_dir, cache->view_normal);
2703
2704         if (cache->is_last_valid && (normalize_v3(brush_dir) != 0.0f)) {
2705
2706                 SculptBrushTest test;
2707                 SculptBrushTestFn sculpt_brush_test_sq_fn =
2708                         sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2709                 const float *sculpt_normal_frontface =
2710                         sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
2711
2712                 /* For each vertex */
2713                 PBVHVertexIter vd;
2714                 BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2715                 {
2716                         /* Test to see if the vertex coordinates are within the spherical brush region. */
2717                         if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2718                                 /* For grid based pbvh, take the vert whose loop cooresponds to the current grid.
2719                                  * Otherwise, take the current vert. */
2720                                 const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
2721                                 const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
2722                                 const MVert *mv_curr = &data->me->mvert[v_index];
2723
2724                                 /* if the vertex is selected for painting. */
2725                                 if (!use_vert_sel || mv_curr->flag & SELECT) {
2726                                         /* Calc the dot prod. between ray norm on surf and current vert
2727                                          * (ie splash prevention factor), and only paint front facing verts. */
2728                                         float brush_strength = cache->bstrength;
2729                                         const float angle_cos = (use_normal && vd.no) ?
2730                                                 dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
2731                                         if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
2732                                              (angle_cos > 0.0f)) &&
2733                                             ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
2734                                              view_angle_limits_apply_falloff(&data->vpd->normal_angle_precalc, angle_cos, &brush_strength)))
2735                                         {
2736                                                 const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
2737
2738                                                 bool do_color = false;
2739                                                 /* Minimum dot product between brush direction and current
2740                                                  * to neighbor direction is 0.0, meaning orthogonal. */
2741                                                 float stroke_dot_max = 0.0f;
2742
2743                                                 /* Get the color of the loop in the opposite direction of the brush movement */
2744                                                 uint color_final = 0;
2745                                                 for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
2746                                                         const int p_index = gmap->vert_to_poly[v_index].indices[j];
2747                                                         const int l_index = gmap->vert_to_loop[v_index].indices[j];
2748                                                         BLI_assert(data->me->mloop[l_index].v == v_index);
2749                                                         UNUSED_VARS_NDEBUG(l_index);
2750                                                         const MPoly *mp = &data->me->mpoly[p_index];
2751                                                         if (!use_face_sel || mp->flag & ME_FACE_SEL) {
2752                                                                 const MLoop *ml_other = &data->me->mloop[mp->loopstart];
2753                                                                 for (int k = 0; k < mp->totloop; k++, ml_other++) {
2754                                                                         const uint v_other_index = ml_other->v;
2755                                                                         if (v_other_index != v_index) {
2756                                                                                 const MVert *mv_other = &data->me->mvert[v_other_index];
2757
2758                                                                                 /* Get the direction from the selected vert to the neighbor. */
2759                                                                                 float other_dir[3];
2760                                                                                 sub_v3_v3v3(other_dir, mv_curr->co, mv_other->co);
2761                                                                                 project_plane_v3_v3v3(other_dir, other_dir, cache->view_normal);
2762
2763                                                                                 normalize_v3(other_dir);
2764
2765                                                                                 const float stroke_dot = dot_v3v3(other_dir, brush_dir);
2766
2767                                                                                 if (stroke_dot > stroke_dot_max) {
2768                                                                                         stroke_dot_max = stroke_dot;
2769                                                                                         color_final = data->vpd->smear.color_prev[mp->loopstart + k];
2770                                                                                         do_color = true;
2771                                                                                 }
2772                                                                         }
2773                                                                 }
2774                                                         }
2775                                                 }
2776
2777                                                 if (do_color) {
2778                                                         const float final_alpha =
2779                                                                 255 * brush_fade * brush_strength *
2780                                                                 brush_alpha_pressure * grid_alpha;
2781
2782                                                         /* For each poly owning this vert, paint each loop belonging to this vert. */
2783                                                         for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
2784                                                                 const int p_index = gmap->vert_to_poly[v_index].indices[j];
2785                                                                 const int l_index = gmap->vert_to_loop[v_index].indices[j];
2786                                                                 BLI_assert(data->me->mloop[l_index].v == v_index);
2787                                                                 const MPoly *mp = &data->me->mpoly[p_index];
2788                                                                 if (!use_face_sel || mp->flag & ME_FACE_SEL) {
2789                                                                         /* Get the previous loop color */
2790                                                                         uint color_orig = 0;  /* unused when array is NULL */
2791                                                                         if (ss->mode.vpaint.previous_color != NULL) {
2792                                                                                 /* Get the previous loop color */
2793                                                                                 if (ss->mode.vpaint.previous_color[l_index] == 0) {
2794                                                                                         ss->mode.vpaint.previous_color[l_index] = lcol[l_index];
2795                                                                                 }
2796                                                                                 color_orig = ss->mode.vpaint.previous_color[l_index];
2797                                                                         }
2798                                                                         /* Mix the new color with the original
2799                                                                          * based on the brush strength and the curve. */
2800                                                                         lcol[l_index] = vpaint_blend(
2801                                                                                 data->vp, lcol[l_index], color_orig, color_final,
2802                                                                                 final_alpha, 255 * brush_strength);
2803
2804                                                                         data->vpd->smear.color_curr[l_index] = lcol[l_index];
2805                                                                 }
2806                                                         }
2807                                                 }
2808                                         }
2809                                 }
2810                         }
2811                 }
2812                 BKE_pbvh_vertex_iter_end;
2813         }
2814 }
2815
2816 static void calculate_average_color(SculptThreadedTaskData *data, PBVHNode **UNUSED(nodes), int totnode)
2817 {
2818         struct VPaintAverageAccum *accum = MEM_mallocN(sizeof(*accum) * totnode, __func__);
2819         data->custom_data = accum;
2820
2821         ParallelRangeSettings settings;
2822         BLI_parallel_range_settings_defaults(&settings);
2823         BLI_task_parallel_range(
2824                 0, totnode,
2825                 data,
2826                 do_vpaint_brush_calc_average_color_cb_ex,
2827                 &settings);
2828
2829         uint accum_len = 0;
2830         uint accum_value[3] = {0};