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