Weight Paint: support accumulate for blur brush
[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
32 #include "MEM_guardedalloc.h"
33
34 #include "BLI_blenlib.h"
35 #include "BLI_math.h"
36 #include "BLI_array_utils.h"
37 #include "BLI_bitmap.h"
38 #include "BLI_stack.h"
39
40 #include "IMB_imbuf.h"
41 #include "IMB_imbuf_types.h"
42 #include "IMB_colormanagement.h"
43
44 #include "DNA_armature_types.h"
45 #include "DNA_mesh_types.h"
46 #include "DNA_particle_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_brush_types.h"
49 #include "DNA_object_types.h"
50
51 #include "RNA_access.h"
52 #include "RNA_define.h"
53 #include "RNA_enum_types.h"
54
55 #include "BKE_DerivedMesh.h"
56 #include "BKE_action.h"
57 #include "BKE_brush.h"
58 #include "BKE_context.h"
59 #include "BKE_depsgraph.h"
60 #include "BKE_deform.h"
61 #include "BKE_mesh.h"
62 #include "BKE_mesh_mapping.h"
63 #include "BKE_modifier.h"
64 #include "BKE_object_deform.h"
65 #include "BKE_paint.h"
66 #include "BKE_report.h"
67 #include "BKE_colortools.h"
68
69 #include "WM_api.h"
70 #include "WM_types.h"
71
72 #include "ED_armature.h"
73 #include "ED_object.h"
74 #include "ED_mesh.h"
75 #include "ED_screen.h"
76 #include "ED_view3d.h"
77
78 #include "paint_intern.h"  /* own include */
79
80 /* small structure to defer applying weight-paint results */
81 struct WPaintDefer {
82         int index;
83         float alpha, weight;
84 };
85
86 /* check if we can do partial updates and have them draw realtime
87  * (without rebuilding the 'derivedFinal') */
88 static bool vertex_paint_use_fast_update_check(Object *ob)
89 {
90         DerivedMesh *dm = ob->derivedFinal;
91
92         if (dm) {
93                 Mesh *me = BKE_mesh_from_object(ob);
94                 if (me && me->mloopcol) {
95                         return (me->mloopcol == CustomData_get_layer(&dm->loopData, CD_MLOOPCOL));
96                 }
97         }
98
99         return false;
100 }
101
102 static void paint_last_stroke_update(Scene *scene, ARegion *ar, const float mval[2])
103 {
104         const int mval_i[2] = {mval[0], mval[1]};
105         float world[3];
106
107         if (ED_view3d_autodist_simple(ar, mval_i, world, 0, NULL)) {
108                 UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
109                 ups->average_stroke_counter++;
110                 add_v3_v3(ups->average_stroke_accum, world);
111                 ups->last_stroke_valid = true;
112         }
113 }
114
115 /* polling - retrieve whether cursor should be set or operator should be done */
116
117 /* Returns true if vertex paint mode is active */
118 int vertex_paint_mode_poll(bContext *C)
119 {
120         Object *ob = CTX_data_active_object(C);
121
122         return ob && ob->mode == OB_MODE_VERTEX_PAINT && ((Mesh *)ob->data)->totpoly;
123 }
124
125 int vertex_paint_poll(bContext *C)
126 {
127         if (vertex_paint_mode_poll(C) && 
128             BKE_paint_brush(&CTX_data_tool_settings(C)->vpaint->paint))
129         {
130                 ScrArea *sa = CTX_wm_area(C);
131                 if (sa && sa->spacetype == SPACE_VIEW3D) {
132                         ARegion *ar = CTX_wm_region(C);
133                         if (ar->regiontype == RGN_TYPE_WINDOW)
134                                 return 1;
135                 }
136         }
137         return 0;
138 }
139
140 int weight_paint_mode_poll(bContext *C)
141 {
142         Object *ob = CTX_data_active_object(C);
143
144         return ob && ob->mode == OB_MODE_WEIGHT_PAINT && ((Mesh *)ob->data)->totpoly;
145 }
146
147 int weight_paint_poll(bContext *C)
148 {
149         Object *ob = CTX_data_active_object(C);
150         ScrArea *sa;
151
152         if ((ob != NULL) &&
153             (ob->mode & OB_MODE_WEIGHT_PAINT) &&
154             (BKE_paint_brush(&CTX_data_tool_settings(C)->wpaint->paint) != NULL) &&
155             (sa = CTX_wm_area(C)) &&
156             (sa->spacetype == SPACE_VIEW3D))
157         {
158                 ARegion *ar = CTX_wm_region(C);
159                 if (ar->regiontype == RGN_TYPE_WINDOW) {
160                         return 1;
161                 }
162         }
163         return 0;
164 }
165
166 static VPaint *new_vpaint(int wpaint)
167 {
168         VPaint *vp = MEM_callocN(sizeof(VPaint), "VPaint");
169         
170         vp->flag = (wpaint) ? 0 : VP_SPRAY;
171         vp->paint.flags |= PAINT_SHOW_BRUSH;
172
173         return vp;
174 }
175
176 static int *get_indexarray(Mesh *me)
177 {
178         return MEM_mallocN(sizeof(int) * (me->totpoly + 1), "vertexpaint");
179 }
180
181 unsigned int vpaint_get_current_col(Scene *scene, VPaint *vp)
182 {
183         Brush *brush = BKE_paint_brush(&vp->paint);
184         unsigned char col[4];
185         rgb_float_to_uchar(col, BKE_brush_color_get(scene, brush));
186         col[3] = 255; /* alpha isn't used, could even be removed to speedup paint a little */
187         return *(unsigned int *)col;
188 }
189
190 static void do_shared_vertexcol(Mesh *me, bool *mlooptag)
191 {
192         const bool use_face_sel = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
193         MPoly *mp;
194         int (*scol)[4];
195         int i, j;
196         bool has_shared = false;
197
198         /* if no mloopcol: do not do */
199         /* if mtexpoly: only the involved faces, otherwise all */
200
201         if (me->mloopcol == NULL || me->totvert == 0 || me->totpoly == 0) return;
202
203         scol = MEM_callocN(sizeof(int) * me->totvert * 5, "scol");
204
205         for (i = 0, mp = me->mpoly; i < me->totpoly; i++, mp++) {
206                 if ((use_face_sel == false) || (mp->flag & ME_FACE_SEL)) {
207                         MLoop *ml = me->mloop + mp->loopstart;
208                         MLoopCol *lcol = me->mloopcol + mp->loopstart;
209                         for (j = 0; j < mp->totloop; j++, ml++, lcol++) {
210                                 scol[ml->v][0] += lcol->r;
211                                 scol[ml->v][1] += lcol->g;
212                                 scol[ml->v][2] += lcol->b;
213                                 scol[ml->v][3] += 1;
214                                 has_shared = 1;
215                         }
216                 }
217         }
218
219         if (has_shared) {
220                 for (i = 0; i < me->totvert; i++) {
221                         if (scol[i][3] != 0) {
222                                 scol[i][0] = divide_round_i(scol[i][0], scol[i][3]);
223                                 scol[i][1] = divide_round_i(scol[i][1], scol[i][3]);
224                                 scol[i][2] = divide_round_i(scol[i][2], scol[i][3]);
225                         }
226                 }
227
228                 for (i = 0, mp = me->mpoly; i < me->totpoly; i++, mp++) {
229                         if ((use_face_sel == false) || (mp->flag & ME_FACE_SEL)) {
230                                 MLoop *ml = me->mloop + mp->loopstart;
231                                 MLoopCol *lcol = me->mloopcol + mp->loopstart;
232                                 for (j = 0; j < mp->totloop; j++, ml++, lcol++) {
233                                         if (mlooptag[mp->loopstart + j]) {
234                                                 lcol->r = scol[ml->v][0];
235                                                 lcol->g = scol[ml->v][1];
236                                                 lcol->b = scol[ml->v][2];
237                                         }
238                                 }
239                         }
240                 }
241         }
242
243         MEM_freeN(scol);
244 }
245
246 static bool make_vertexcol(Object *ob)  /* single ob */
247 {
248         Mesh *me;
249
250         if ((ob->id.lib) ||
251             ((me = BKE_mesh_from_object(ob)) == NULL) ||
252             (me->totpoly == 0) ||
253             (me->edit_btmesh))
254         {
255                 return false;
256         }
257
258         /* copies from shadedisplist to mcol */
259         if (!me->mloopcol && me->totloop) {
260                 if (!me->mloopcol) {
261                         CustomData_add_layer(&me->ldata, CD_MLOOPCOL, CD_DEFAULT, NULL, me->totloop);
262                 }
263                 BKE_mesh_update_customdata_pointers(me, true);
264         }
265
266         DAG_id_tag_update(&me->id, 0);
267         
268         return (me->mloopcol != NULL);
269 }
270
271 /* mirror_vgroup is set to -1 when invalid */
272 static int wpaint_mirror_vgroup_ensure(Object *ob, const int vgroup_active)
273 {
274         bDeformGroup *defgroup = BLI_findlink(&ob->defbase, vgroup_active);
275
276         if (defgroup) {
277                 int mirrdef;
278                 char name_flip[MAXBONENAME];
279
280                 BKE_deform_flip_side_name(name_flip, defgroup->name, false);
281                 mirrdef = defgroup_name_index(ob, name_flip);
282                 if (mirrdef == -1) {
283                         if (BKE_defgroup_new(ob, name_flip)) {
284                                 mirrdef = BLI_listbase_count(&ob->defbase) - 1;
285                         }
286                 }
287
288                 /* curdef should never be NULL unless this is
289                  * a  lamp and BKE_object_defgroup_add_name fails */
290                 return mirrdef;
291         }
292
293         return -1;
294 }
295
296 static void free_vpaint_prev(VPaint *vp)
297 {
298         if (vp->vpaint_prev) {
299                 MEM_freeN(vp->vpaint_prev);
300                 vp->vpaint_prev = NULL;
301                 vp->tot = 0;
302         }
303 }
304
305 static void free_wpaint_prev(VPaint *vp)
306 {
307         if (vp->wpaint_prev) {
308                 BKE_defvert_array_free(vp->wpaint_prev, vp->tot);
309                 vp->wpaint_prev = NULL;
310                 vp->tot = 0;
311         }
312 }
313
314 static void copy_vpaint_prev(VPaint *vp, unsigned int *lcol, int tot)
315 {
316         free_vpaint_prev(vp);
317
318         vp->tot = tot;
319         
320         if (lcol == NULL || tot == 0) return;
321         
322         vp->vpaint_prev = MEM_mallocN(sizeof(int) * tot, "vpaint_prev");
323         memcpy(vp->vpaint_prev, lcol, sizeof(int) * tot);
324         
325 }
326
327 static void copy_wpaint_prev(VPaint *wp, MDeformVert *dverts, int dcount)
328 {
329         free_wpaint_prev(wp);
330         
331         if (dverts && dcount) {
332                 
333                 wp->wpaint_prev = MEM_mallocN(sizeof(MDeformVert) * dcount, "wpaint prev");
334                 wp->tot = dcount;
335                 BKE_defvert_array_copy(wp->wpaint_prev, dverts, dcount);
336         }
337 }
338
339 bool ED_vpaint_fill(Object *ob, unsigned int paintcol)
340 {
341         Mesh *me;
342         MPoly *mp;
343         int i, j;
344         bool selected;
345
346         if (((me = BKE_mesh_from_object(ob)) == NULL) ||
347             (me->mloopcol == NULL && (make_vertexcol(ob) == false)))
348         {
349                 return false;
350         }
351
352         selected = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
353
354         mp = me->mpoly;
355         for (i = 0; i < me->totpoly; i++, mp++) {
356                 MLoopCol *lcol = me->mloopcol + mp->loopstart;
357
358                 if (selected && !(mp->flag & ME_FACE_SEL))
359                         continue;
360
361                 for (j = 0; j < mp->totloop; j++, lcol++) {
362                         *(int *)lcol = paintcol;
363                 }
364         }
365         
366         /* remove stale me->mcol, will be added later */
367         BKE_mesh_tessface_clear(me);
368
369         DAG_id_tag_update(&me->id, 0);
370
371         return true;
372 }
373
374
375 /* fills in the selected faces with the current weight and vertex group */
376 bool ED_wpaint_fill(VPaint *wp, Object *ob, float paintweight)
377 {
378         Mesh *me = ob->data;
379         MPoly *mp;
380         MDeformWeight *dw, *dw_prev;
381         int vgroup_active, vgroup_mirror = -1;
382         unsigned int index;
383         const bool topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
384
385         /* mutually exclusive, could be made into a */
386         const short paint_selmode = ME_EDIT_PAINT_SEL_MODE(me);
387
388         if (me->totpoly == 0 || me->dvert == NULL || !me->mpoly) {
389                 return false;
390         }
391         
392         vgroup_active = ob->actdef - 1;
393
394         /* if mirror painting, find the other group */
395         if (me->editflag & ME_EDIT_MIRROR_X) {
396                 vgroup_mirror = wpaint_mirror_vgroup_ensure(ob, vgroup_active);
397         }
398         
399         copy_wpaint_prev(wp, me->dvert, me->totvert);
400         
401         for (index = 0, mp = me->mpoly; index < me->totpoly; index++, mp++) {
402                 unsigned int fidx = mp->totloop - 1;
403
404                 if ((paint_selmode == SCE_SELECT_FACE) && !(mp->flag & ME_FACE_SEL)) {
405                         continue;
406                 }
407
408                 do {
409                         unsigned int vidx = me->mloop[mp->loopstart + fidx].v;
410
411                         if (!me->dvert[vidx].flag) {
412                                 if ((paint_selmode == SCE_SELECT_VERTEX) && !(me->mvert[vidx].flag & SELECT)) {
413                                         continue;
414                                 }
415
416                                 dw = defvert_verify_index(&me->dvert[vidx], vgroup_active);
417                                 if (dw) {
418                                         dw_prev = defvert_verify_index(wp->wpaint_prev + vidx, vgroup_active);
419                                         dw_prev->weight = dw->weight; /* set the undo weight */
420                                         dw->weight = paintweight;
421
422                                         if (me->editflag & ME_EDIT_MIRROR_X) {  /* x mirror painting */
423                                                 int j = mesh_get_x_mirror_vert(ob, NULL, vidx, topology);
424                                                 if (j >= 0) {
425                                                         /* copy, not paint again */
426                                                         if (vgroup_mirror != -1) {
427                                                                 dw = defvert_verify_index(me->dvert + j, vgroup_mirror);
428                                                                 dw_prev = defvert_verify_index(wp->wpaint_prev + j, vgroup_mirror);
429                                                         }
430                                                         else {
431                                                                 dw = defvert_verify_index(me->dvert + j, vgroup_active);
432                                                                 dw_prev = defvert_verify_index(wp->wpaint_prev + j, vgroup_active);
433                                                         }
434                                                         dw_prev->weight = dw->weight; /* set the undo weight */
435                                                         dw->weight = paintweight;
436                                                 }
437                                         }
438                                 }
439                                 me->dvert[vidx].flag = 1;
440                         }
441
442                 } while (fidx--);
443         }
444
445         {
446                 MDeformVert *dv = me->dvert;
447                 for (index = me->totvert; index != 0; index--, dv++) {
448                         dv->flag = 0;
449                 }
450         }
451
452         copy_wpaint_prev(wp, NULL, 0);
453
454         DAG_id_tag_update(&me->id, 0);
455
456         return true;
457 }
458
459 bool ED_vpaint_smooth(Object *ob)
460 {
461         Mesh *me;
462         MPoly *mp;
463
464         int i, j;
465
466         bool *mlooptag;
467         bool selected;
468
469         if (((me = BKE_mesh_from_object(ob)) == NULL) ||
470             (me->mloopcol == NULL && (make_vertexcol(ob) == false)))
471         {
472                 return false;
473         }
474
475         selected = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
476
477         mlooptag = MEM_callocN(sizeof(bool) * me->totloop, "VPaintData mlooptag");
478
479         /* simply tag loops of selected faces */
480         mp = me->mpoly;
481         for (i = 0; i < me->totpoly; i++, mp++) {
482                 MLoop *ml = me->mloop + mp->loopstart;
483                 int ml_index = mp->loopstart;
484
485                 if (selected && !(mp->flag & ME_FACE_SEL))
486                         continue;
487
488                 for (j = 0; j < mp->totloop; j++, ml_index++, ml++) {
489                         mlooptag[ml_index] = true;
490                 }
491         }
492
493         /* remove stale me->mcol, will be added later */
494         BKE_mesh_tessface_clear(me);
495
496         do_shared_vertexcol(me, mlooptag);
497
498         MEM_freeN(mlooptag);
499
500         DAG_id_tag_update(&me->id, 0);
501
502         return true;
503 }
504
505 /* XXX: should be re-implemented as a vertex/weight paint 'color correct' operator */
506 #if 0
507 void vpaint_dogamma(Scene *scene)
508 {
509         VPaint *vp = scene->toolsettings->vpaint;
510         Mesh *me;
511         Object *ob;
512         float igam, fac;
513         int a, temp;
514         unsigned char *cp, gamtab[256];
515
516         ob = OBACT;
517         me = BKE_mesh_from_object(ob);
518
519         if (!(ob->mode & OB_MODE_VERTEX_PAINT)) return;
520         if (me == 0 || me->mcol == 0 || me->totface == 0) return;
521
522         igam = 1.0 / vp->gamma;
523         for (a = 0; a < 256; a++) {
524
525                 fac = ((float)a) / 255.0;
526                 fac = vp->mul * pow(fac, igam);
527
528                 temp = 255.9 * fac;
529
530                 if (temp <= 0) gamtab[a] = 0;
531                 else if (temp >= 255) gamtab[a] = 255;
532                 else gamtab[a] = temp;
533         }
534
535         a = 4 * me->totface;
536         cp = (unsigned char *)me->mcol;
537         while (a--) {
538
539                 cp[1] = gamtab[cp[1]];
540                 cp[2] = gamtab[cp[2]];
541                 cp[3] = gamtab[cp[3]];
542
543                 cp += 4;
544         }
545 }
546 #endif
547
548 BLI_INLINE unsigned int mcol_blend(unsigned int col1, unsigned int col2, int fac)
549 {
550         unsigned char *cp1, *cp2, *cp;
551         int mfac;
552         unsigned int col = 0;
553
554         if (fac == 0) {
555                 return col1;
556         }
557
558         if (fac >= 255) {
559                 return col2;
560         }
561
562         mfac = 255 - fac;
563
564         cp1 = (unsigned char *)&col1;
565         cp2 = (unsigned char *)&col2;
566         cp  = (unsigned char *)&col;
567
568         cp[0] = divide_round_i((mfac * cp1[0] + fac * cp2[0]), 255);
569         cp[1] = divide_round_i((mfac * cp1[1] + fac * cp2[1]), 255);
570         cp[2] = divide_round_i((mfac * cp1[2] + fac * cp2[2]), 255);
571         cp[3] = 255;
572
573         return col;
574 }
575
576 BLI_INLINE unsigned int mcol_add(unsigned int col1, unsigned int col2, int fac)
577 {
578         unsigned char *cp1, *cp2, *cp;
579         int temp;
580         unsigned int col = 0;
581
582         if (fac == 0) {
583                 return col1;
584         }
585
586         cp1 = (unsigned char *)&col1;
587         cp2 = (unsigned char *)&col2;
588         cp  = (unsigned char *)&col;
589
590         temp = cp1[0] + divide_round_i((fac * cp2[0]), 255);
591         cp[0] = (temp > 254) ? 255 : temp;
592         temp = cp1[1] + divide_round_i((fac * cp2[1]), 255);
593         cp[1] = (temp > 254) ? 255 : temp;
594         temp = cp1[2] + divide_round_i((fac * cp2[2]), 255);
595         cp[2] = (temp > 254) ? 255 : temp;
596         cp[3] = 255;
597         
598         return col;
599 }
600
601 BLI_INLINE unsigned int mcol_sub(unsigned int col1, unsigned int col2, int fac)
602 {
603         unsigned char *cp1, *cp2, *cp;
604         int temp;
605         unsigned int col = 0;
606
607         if (fac == 0) {
608                 return col1;
609         }
610
611         cp1 = (unsigned char *)&col1;
612         cp2 = (unsigned char *)&col2;
613         cp  = (unsigned char *)&col;
614
615         temp = cp1[0] - divide_round_i((fac * cp2[0]), 255);
616         cp[0] = (temp < 0) ? 0 : temp;
617         temp = cp1[1] - divide_round_i((fac * cp2[1]), 255);
618         cp[1] = (temp < 0) ? 0 : temp;
619         temp = cp1[2] - divide_round_i((fac * cp2[2]), 255);
620         cp[2] = (temp < 0) ? 0 : temp;
621         cp[3] = 255;
622
623         return col;
624 }
625
626 BLI_INLINE unsigned int mcol_mul(unsigned int col1, unsigned int col2, int fac)
627 {
628         unsigned char *cp1, *cp2, *cp;
629         int mfac;
630         unsigned int col = 0;
631
632         if (fac == 0) {
633                 return col1;
634         }
635
636         mfac = 255 - fac;
637
638         cp1 = (unsigned char *)&col1;
639         cp2 = (unsigned char *)&col2;
640         cp  = (unsigned char *)&col;
641
642         /* first mul, then blend the fac */
643         cp[0] = divide_round_i(mfac * cp1[0] * 255 + fac * cp2[0] * cp1[0], 255 * 255);
644         cp[1] = divide_round_i(mfac * cp1[1] * 255 + fac * cp2[1] * cp1[1], 255 * 255);
645         cp[2] = divide_round_i(mfac * cp1[2] * 255 + fac * cp2[2] * cp1[2], 255 * 255);
646         cp[3] = 255;
647
648         return col;
649 }
650
651 BLI_INLINE unsigned int mcol_lighten(unsigned int col1, unsigned int col2, int fac)
652 {
653         unsigned char *cp1, *cp2, *cp;
654         int mfac;
655         unsigned int col = 0;
656
657         if (fac == 0) {
658                 return col1;
659         }
660         else if (fac >= 255) {
661                 return col2;
662         }
663
664         mfac = 255 - fac;
665
666         cp1 = (unsigned char *)&col1;
667         cp2 = (unsigned char *)&col2;
668         cp  = (unsigned char *)&col;
669
670         /* See if are lighter, if so mix, else don't do anything.
671          * if the paint col is darker then the original, then ignore */
672         if (IMB_colormanagement_get_luminance_byte(cp1) > IMB_colormanagement_get_luminance_byte(cp2)) {
673                 return col1;
674         }
675
676         cp[0] = divide_round_i(mfac * cp1[0] + fac * cp2[0], 255);
677         cp[1] = divide_round_i(mfac * cp1[1] + fac * cp2[1], 255);
678         cp[2] = divide_round_i(mfac * cp1[2] + fac * cp2[2], 255);
679         cp[3] = 255;
680
681         return col;
682 }
683
684 BLI_INLINE unsigned int mcol_darken(unsigned int col1, unsigned int col2, int fac)
685 {
686         unsigned char *cp1, *cp2, *cp;
687         int mfac;
688         unsigned int col = 0;
689
690         if (fac == 0) {
691                 return col1;
692         }
693         else if (fac >= 255) {
694                 return col2;
695         }
696
697         mfac = 255 - fac;
698
699         cp1 = (unsigned char *)&col1;
700         cp2 = (unsigned char *)&col2;
701         cp  = (unsigned char *)&col;
702
703         /* See if were darker, if so mix, else don't do anything.
704          * if the paint col is brighter then the original, then ignore */
705         if (IMB_colormanagement_get_luminance_byte(cp1) < IMB_colormanagement_get_luminance_byte(cp2)) {
706                 return col1;
707         }
708
709         cp[0] = divide_round_i((mfac * cp1[0] + fac * cp2[0]), 255);
710         cp[1] = divide_round_i((mfac * cp1[1] + fac * cp2[1]), 255);
711         cp[2] = divide_round_i((mfac * cp1[2] + fac * cp2[2]), 255);
712         cp[3] = 255;
713         return col;
714 }
715
716 /* wpaint has 'wpaint_blend_tool' */
717 static unsigned int vpaint_blend_tool(const int tool, const unsigned int col,
718                                       const unsigned int paintcol, const int alpha_i)
719 {
720         switch (tool) {
721                 case PAINT_BLEND_MIX:
722                 case PAINT_BLEND_BLUR:     return mcol_blend(col, paintcol, alpha_i);
723                 case PAINT_BLEND_ADD:      return mcol_add(col, paintcol, alpha_i);
724                 case PAINT_BLEND_SUB:      return mcol_sub(col, paintcol, alpha_i);
725                 case PAINT_BLEND_MUL:      return mcol_mul(col, paintcol, alpha_i);
726                 case PAINT_BLEND_LIGHTEN:  return mcol_lighten(col, paintcol, alpha_i);
727                 case PAINT_BLEND_DARKEN:   return mcol_darken(col, paintcol, alpha_i);
728                 default:
729                         BLI_assert(0);
730                         return 0;
731         }
732 }
733
734 /* wpaint has 'wpaint_blend' */
735 static unsigned int vpaint_blend(VPaint *vp, unsigned int col, unsigned int colorig, const
736                                  unsigned int paintcol, const int alpha_i,
737                                  /* pre scaled from [0-1] --> [0-255] */
738                                  const int brush_alpha_value_i)
739 {
740         Brush *brush = BKE_paint_brush(&vp->paint);
741         const int tool = brush->vertexpaint_tool;
742
743         col = vpaint_blend_tool(tool, col, paintcol, alpha_i);
744
745         /* if no spray, clip color adding with colorig & orig alpha */
746         if ((vp->flag & VP_SPRAY) == 0) {
747                 unsigned int testcol, a;
748                 char *cp, *ct, *co;
749                 
750                 testcol = vpaint_blend_tool(tool, colorig, paintcol, brush_alpha_value_i);
751                 
752                 cp = (char *)&col;
753                 ct = (char *)&testcol;
754                 co = (char *)&colorig;
755                 
756                 for (a = 0; a < 4; a++) {
757                         if (ct[a] < co[a]) {
758                                 if (cp[a] < ct[a]) cp[a] = ct[a];
759                                 else if (cp[a] > co[a]) cp[a] = co[a];
760                         }
761                         else {
762                                 if (cp[a] < co[a]) cp[a] = co[a];
763                                 else if (cp[a] > ct[a]) cp[a] = ct[a];
764                         }
765                 }
766         }
767
768         return col;
769 }
770
771
772 static int sample_backbuf_area(ViewContext *vc, int *indexar, int totpoly, int x, int y, float size)
773 {
774         struct ImBuf *ibuf;
775         int a, tot = 0, index;
776         
777         /* brecht: disabled this because it obviously fails for
778          * brushes with size > 64, why is this here? */
779         /*if (size > 64.0) size = 64.0;*/
780         
781         ibuf = ED_view3d_backbuf_read(vc, x - size, y - size, x + size, y + size);
782         if (ibuf) {
783                 unsigned int *rt = ibuf->rect;
784
785                 memset(indexar, 0, sizeof(int) * (totpoly + 1));
786                 
787                 size = ibuf->x * ibuf->y;
788                 while (size--) {
789                                 
790                         if (*rt) {
791                                 index = *rt;
792                                 if (index > 0 && index <= totpoly) {
793                                         indexar[index] = 1;
794                                 }
795                         }
796                 
797                         rt++;
798                 }
799                 
800                 for (a = 1; a <= totpoly; a++) {
801                         if (indexar[a]) {
802                                 indexar[tot++] = a;
803                         }
804                 }
805
806                 IMB_freeImBuf(ibuf);
807         }
808         
809         return tot;
810 }
811
812 /* whats _dl mean? */
813 static float calc_vp_strength_col_dl(VPaint *vp, ViewContext *vc, const float co[3],
814                                  const float mval[2], const float brush_size_pressure, float rgba[4])
815 {
816         float co_ss[2];  /* screenspace */
817
818         if (ED_view3d_project_float_object(vc->ar,
819                                            co, co_ss,
820                                            V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
821         {
822                 const float dist_sq = len_squared_v2v2(mval, co_ss);
823
824                 if (dist_sq <= SQUARE(brush_size_pressure)) {
825                         Brush *brush = BKE_paint_brush(&vp->paint);
826                         const float dist = sqrtf(dist_sq);
827                         float factor;
828
829                         if (brush->mtex.tex && rgba) {
830                                 if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_3D) {
831                                         BKE_brush_sample_tex_3D(vc->scene, brush, co, rgba, 0, NULL);
832                                 }
833                                 else {
834                                         const float co_ss_3d[3] = {co_ss[0], co_ss[1], 0.0f};  /* we need a 3rd empty value */
835                                         BKE_brush_sample_tex_3D(vc->scene, brush, co_ss_3d, rgba, 0, NULL);
836                                 }
837                                 factor = rgba[3];
838                         }
839                         else {
840                                 factor = 1.0f;
841                         }
842                         return factor * BKE_brush_curve_strength_clamped(brush, dist, brush_size_pressure);
843                 }
844         }
845         if (rgba)
846                 zero_v4(rgba);
847         return 0.0f;
848 }
849
850 static float calc_vp_alpha_col_dl(VPaint *vp, ViewContext *vc,
851                               float vpimat[3][3], const DMCoNo *v_co_no,
852                               const float mval[2],
853                               const float brush_size_pressure, const float brush_alpha_pressure, float rgba[4])
854 {
855         float strength = calc_vp_strength_col_dl(vp, vc, v_co_no->co, mval, brush_size_pressure, rgba);
856
857         if (strength > 0.0f) {
858                 float alpha = brush_alpha_pressure * strength;
859
860                 if (vp->flag & VP_NORMALS) {
861                         float dvec[3];
862
863                         /* transpose ! */
864                         dvec[2] = dot_v3v3(vpimat[2], v_co_no->no);
865                         if (dvec[2] > 0.0f) {
866                                 dvec[0] = dot_v3v3(vpimat[0], v_co_no->no);
867                                 dvec[1] = dot_v3v3(vpimat[1], v_co_no->no);
868
869                                 alpha *= dvec[2] / len_v3(dvec);
870                         }
871                         else {
872                                 return 0.0f;
873                         }
874                 }
875
876                 return alpha;
877         }
878
879         return 0.0f;
880 }
881
882
883 BLI_INLINE float wval_blend(const float weight, const float paintval, const float alpha)
884 {
885         const float talpha = min_ff(alpha, 1.0f);  /* blending with values over 1 doesn't make sense */
886         return (paintval * talpha) + (weight * (1.0f - talpha));
887 }
888 BLI_INLINE float wval_add(const float weight, const float paintval, const float alpha)
889 {
890         return weight + (paintval * alpha);
891 }
892 BLI_INLINE float wval_sub(const float weight, const float paintval, const float alpha)
893 {
894         return weight - (paintval * alpha);
895 }
896 BLI_INLINE float wval_mul(const float weight, const float paintval, const float alpha)
897 {   /* first mul, then blend the fac */
898         return ((1.0f - alpha) + (alpha * paintval)) * weight;
899 }
900 BLI_INLINE float wval_lighten(const float weight, const float paintval, const float alpha)
901 {
902         return (weight < paintval) ? wval_blend(weight, paintval, alpha) : weight;
903 }
904 BLI_INLINE float wval_darken(const float weight, const float paintval, const float alpha)
905 {
906         return (weight > paintval) ? wval_blend(weight, paintval, alpha) : weight;
907 }
908
909
910 /* vpaint has 'vpaint_blend_tool' */
911 /* result is not clamped from [0-1] */
912 static float wpaint_blend_tool(const int tool,
913                                /* dw->weight */
914                                const float weight,
915                                const float paintval, const float alpha)
916 {
917         switch (tool) {
918                 case PAINT_BLEND_MIX:
919                 case PAINT_BLEND_BLUR:     return wval_blend(weight, paintval, alpha);
920                 case PAINT_BLEND_ADD:      return wval_add(weight, paintval, alpha);
921                 case PAINT_BLEND_SUB:      return wval_sub(weight, paintval, alpha);
922                 case PAINT_BLEND_MUL:      return wval_mul(weight, paintval, alpha);
923                 case PAINT_BLEND_LIGHTEN:  return wval_lighten(weight, paintval, alpha);
924                 case PAINT_BLEND_DARKEN:   return wval_darken(weight, paintval, alpha);
925                 default:
926                         BLI_assert(0);
927                         return 0.0f;
928         }
929 }
930
931 /* vpaint has 'vpaint_blend' */
932 static float wpaint_blend(VPaint *wp, float weight, float weight_prev,
933                           const float alpha, float paintval,
934                           const float brush_alpha_value,
935                           const short do_flip)
936 {
937         Brush *brush = BKE_paint_brush(&wp->paint);
938         int tool = brush->vertexpaint_tool;
939
940         if (do_flip) {
941                 switch (tool) {
942                         case PAINT_BLEND_MIX:
943                                 paintval = 1.f - paintval; break;
944                         case PAINT_BLEND_ADD:
945                                 tool = PAINT_BLEND_SUB; break;
946                         case PAINT_BLEND_SUB:
947                                 tool = PAINT_BLEND_ADD; break;
948                         case PAINT_BLEND_LIGHTEN:
949                                 tool = PAINT_BLEND_DARKEN; break;
950                         case PAINT_BLEND_DARKEN:
951                                 tool = PAINT_BLEND_LIGHTEN; break;
952                 }
953         }
954         
955         weight = wpaint_blend_tool(tool, weight, paintval, alpha);
956
957         CLAMP(weight, 0.0f, 1.0f);
958         
959         /* if no spray, clip result with orig weight & orig alpha */
960         if ((wp->flag & VP_SPRAY) == 0) {
961                 float testw = wpaint_blend_tool(tool, weight_prev, paintval, brush_alpha_value);
962
963                 CLAMP(testw, 0.0f, 1.0f);
964                 if (testw < weight_prev) {
965                         if (weight < testw) weight = testw;
966                         else if (weight > weight_prev) weight = weight_prev;
967                 }
968                 else {
969                         if (weight > testw) weight = testw;
970                         else if (weight < weight_prev) weight = weight_prev;
971                 }
972         }
973
974         return weight;
975 }
976
977 /* ----------------------------------------------------- */
978
979
980 /* sets wp->weight to the closest weight value to vertex */
981 /* note: we cant sample frontbuf, weight colors are interpolated too unpredictable */
982 static int weight_sample_invoke(bContext *C, wmOperator *op, const wmEvent *event)
983 {
984         ViewContext vc;
985         Mesh *me;
986         bool changed = false;
987
988         view3d_set_viewcontext(C, &vc);
989         me = BKE_mesh_from_object(vc.obact);
990
991         if (me && me->dvert && vc.v3d && vc.rv3d && (vc.obact->actdef != 0)) {
992                 const bool use_vert_sel = (me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
993                 int v_idx_best = -1;
994                 unsigned int index;
995
996                 view3d_operator_needs_opengl(C);
997                 ED_view3d_init_mats_rv3d(vc.obact, vc.rv3d);
998
999                 if (use_vert_sel) {
1000                         if (ED_mesh_pick_vert(C, vc.obact, event->mval, &index, ED_MESH_PICK_DEFAULT_VERT_SIZE, true)) {
1001                                 v_idx_best = index;
1002                         }
1003                 }
1004                 else {
1005                         if (ED_mesh_pick_face_vert(C, vc.obact, event->mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
1006                                 v_idx_best = index;
1007                         }
1008                         else if (ED_mesh_pick_face(C, vc.obact, event->mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
1009                                 /* this relies on knowning the internal worksings of ED_mesh_pick_face_vert() */
1010                                 BKE_report(op->reports, RPT_WARNING, "The modifier used does not support deformed locations");
1011                         }
1012                 }
1013
1014                 if (v_idx_best != -1) { /* should always be valid */
1015                         ToolSettings *ts = vc.scene->toolsettings;
1016                         Brush *brush = BKE_paint_brush(&ts->wpaint->paint);
1017                         const int vgroup_active = vc.obact->actdef - 1;
1018                         float vgroup_weight = defvert_find_weight(&me->dvert[v_idx_best], vgroup_active);
1019
1020                         /* use combined weight in multipaint mode, since that's what is displayed to the user in the colors */
1021                         if (ts->multipaint) {
1022                                 int defbase_tot_sel;
1023                                 const int defbase_tot = BLI_listbase_count(&vc.obact->defbase);
1024                                 bool *defbase_sel = BKE_object_defgroup_selected_get(vc.obact, defbase_tot, &defbase_tot_sel);
1025
1026                                 if (defbase_tot_sel > 1) {
1027                                         if (me->editflag & ME_EDIT_MIRROR_X) {
1028                                                 BKE_object_defgroup_mirror_selection(
1029                                                         vc.obact, defbase_tot, defbase_sel, defbase_sel, &defbase_tot_sel);
1030                                         }
1031
1032                                         vgroup_weight = BKE_defvert_multipaint_collective_weight(
1033                                                 &me->dvert[v_idx_best], defbase_tot, defbase_sel, defbase_tot_sel, ts->auto_normalize);
1034
1035                                         /* if autonormalize is enabled, but weights are not normalized, the value can exceed 1 */
1036                                         CLAMP(vgroup_weight, 0.0f, 1.0f);
1037                                 }
1038
1039                                 MEM_freeN(defbase_sel);
1040                         }
1041
1042                         BKE_brush_weight_set(vc.scene, brush, vgroup_weight);
1043                         changed = true;
1044                 }
1045         }
1046
1047         if (changed) {
1048                 /* not really correct since the brush didnt change, but redraws the toolbar */
1049                 WM_main_add_notifier(NC_BRUSH | NA_EDITED, NULL); /* ts->wpaint->paint.brush */
1050
1051                 return OPERATOR_FINISHED;
1052         }
1053         else {
1054                 return OPERATOR_CANCELLED;
1055         }
1056 }
1057
1058 void PAINT_OT_weight_sample(wmOperatorType *ot)
1059 {
1060         /* identifiers */
1061         ot->name = "Weight Paint Sample Weight";
1062         ot->idname = "PAINT_OT_weight_sample";
1063         ot->description = "Use the mouse to sample a weight in the 3D view";
1064
1065         /* api callbacks */
1066         ot->invoke = weight_sample_invoke;
1067         ot->poll = weight_paint_mode_poll;
1068
1069         /* flags */
1070         ot->flag = OPTYPE_UNDO;
1071 }
1072
1073 /* samples cursor location, and gives menu with vertex groups to activate */
1074 static bool weight_paint_sample_enum_itemf__helper(const MDeformVert *dvert, const int defbase_tot, int *groups)
1075 {
1076         /* this func fills in used vgroup's */
1077         bool found = false;
1078         int i = dvert->totweight;
1079         MDeformWeight *dw;
1080         for (dw = dvert->dw; i > 0; dw++, i--) {
1081                 if (dw->def_nr < defbase_tot) {
1082                         groups[dw->def_nr] = true;
1083                         found = true;
1084                 }
1085         }
1086         return found;
1087 }
1088 static EnumPropertyItem *weight_paint_sample_enum_itemf(
1089         bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
1090 {
1091         if (C) {
1092                 wmWindow *win = CTX_wm_window(C);
1093                 if (win && win->eventstate) {
1094                         ViewContext vc;
1095                         Mesh *me;
1096
1097                         view3d_set_viewcontext(C, &vc);
1098                         me = BKE_mesh_from_object(vc.obact);
1099
1100                         if (me && me->dvert && vc.v3d && vc.rv3d && vc.obact->defbase.first) {
1101                                 const int defbase_tot = BLI_listbase_count(&vc.obact->defbase);
1102                                 const bool use_vert_sel = (me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
1103                                 int *groups = MEM_callocN(defbase_tot * sizeof(int), "groups");
1104                                 bool found = false;
1105                                 unsigned int index;
1106
1107                                 const int mval[2] = {
1108                                     win->eventstate->x - vc.ar->winrct.xmin,
1109                                     win->eventstate->y - vc.ar->winrct.ymin,
1110                                 };
1111
1112                                 view3d_operator_needs_opengl(C);
1113                                 ED_view3d_init_mats_rv3d(vc.obact, vc.rv3d);
1114
1115                                 if (use_vert_sel) {
1116                                         if (ED_mesh_pick_vert(C, vc.obact, mval, &index, ED_MESH_PICK_DEFAULT_VERT_SIZE, true)) {
1117                                                 MDeformVert *dvert = &me->dvert[index];
1118                                                 found |= weight_paint_sample_enum_itemf__helper(dvert, defbase_tot, groups);
1119                                         }
1120                                 }
1121                                 else {
1122                                         if (ED_mesh_pick_face(C, vc.obact, mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
1123                                                 MPoly *mp = &me->mpoly[index];
1124                                                 unsigned int fidx = mp->totloop - 1;
1125
1126                                                 do {
1127                                                         MDeformVert *dvert = &me->dvert[me->mloop[mp->loopstart + fidx].v];
1128                                                         found |= weight_paint_sample_enum_itemf__helper(dvert, defbase_tot, groups);
1129                                                 } while (fidx--);
1130                                         }
1131                                 }
1132
1133                                 if (found == false) {
1134                                         MEM_freeN(groups);
1135                                 }
1136                                 else {
1137                                         EnumPropertyItem *item = NULL, item_tmp = {0};
1138                                         int totitem = 0;
1139                                         int i = 0;
1140                                         bDeformGroup *dg;
1141                                         for (dg = vc.obact->defbase.first; dg && i < defbase_tot; i++, dg = dg->next) {
1142                                                 if (groups[i]) {
1143                                                         item_tmp.identifier = item_tmp.name = dg->name;
1144                                                         item_tmp.value = i;
1145                                                         RNA_enum_item_add(&item, &totitem, &item_tmp);
1146                                                 }
1147                                         }
1148
1149                                         RNA_enum_item_end(&item, &totitem);
1150                                         *r_free = true;
1151
1152                                         MEM_freeN(groups);
1153                                         return item;
1154                                 }
1155                         }
1156                 }
1157         }
1158
1159         return DummyRNA_NULL_items;
1160 }
1161
1162 static int weight_sample_group_exec(bContext *C, wmOperator *op)
1163 {
1164         int type = RNA_enum_get(op->ptr, "group");
1165         ViewContext vc;
1166         view3d_set_viewcontext(C, &vc);
1167
1168         BLI_assert(type + 1 >= 0);
1169         vc.obact->actdef = type + 1;
1170
1171         DAG_id_tag_update(&vc.obact->id, OB_RECALC_DATA);
1172         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, vc.obact);
1173         return OPERATOR_FINISHED;
1174 }
1175
1176 /* TODO, we could make this a menu into OBJECT_OT_vertex_group_set_active rather than its own operator */
1177 void PAINT_OT_weight_sample_group(wmOperatorType *ot)
1178 {
1179         PropertyRNA *prop = NULL;
1180
1181         /* identifiers */
1182         ot->name = "Weight Paint Sample Group";
1183         ot->idname = "PAINT_OT_weight_sample_group";
1184         ot->description = "Select one of the vertex groups available under current mouse position";
1185
1186         /* api callbacks */
1187         ot->exec = weight_sample_group_exec;
1188         ot->invoke = WM_menu_invoke;
1189         ot->poll = weight_paint_mode_poll;
1190
1191         /* flags */
1192         ot->flag = OPTYPE_UNDO;
1193
1194         /* keyingset to use (dynamic enum) */
1195         prop = RNA_def_enum(ot->srna, "group", DummyRNA_DEFAULT_items, 0, "Keying Set", "The Keying Set to use");
1196         RNA_def_enum_funcs(prop, weight_paint_sample_enum_itemf);
1197         RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
1198         ot->prop = prop;
1199 }
1200
1201 static void do_weight_paint_normalize_all(MDeformVert *dvert, const int defbase_tot, const bool *vgroup_validmap)
1202 {
1203         float sum = 0.0f, fac;
1204         unsigned int i, tot = 0;
1205         MDeformWeight *dw;
1206
1207         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1208                 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1209                         tot++;
1210                         sum += dw->weight;
1211                 }
1212         }
1213
1214         if ((tot == 0) || (sum == 1.0f)) {
1215                 return;
1216         }
1217
1218         if (sum != 0.0f) {
1219                 fac = 1.0f / sum;
1220
1221                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1222                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1223                                 dw->weight *= fac;
1224                         }
1225                 }
1226         }
1227         else {
1228                 /* hrmf, not a factor in this case */
1229                 fac = 1.0f / tot;
1230
1231                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1232                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1233                                 dw->weight = fac;
1234                         }
1235                 }
1236         }
1237 }
1238
1239 /**
1240  * A version of #do_weight_paint_normalize_all that includes locked weights
1241  * but only changes unlocked weights.
1242  */
1243 static bool do_weight_paint_normalize_all_locked(
1244         MDeformVert *dvert, const int defbase_tot, const bool *vgroup_validmap,
1245         const bool *lock_flags)
1246 {
1247         float sum = 0.0f, fac;
1248         float sum_unlock = 0.0f;
1249         float lock_weight = 0.0f;
1250         unsigned int i, tot = 0;
1251         MDeformWeight *dw;
1252
1253         if (lock_flags == NULL) {
1254                 do_weight_paint_normalize_all(dvert, defbase_tot, vgroup_validmap);
1255                 return true;
1256         }
1257
1258         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1259                 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1260                         sum += dw->weight;
1261
1262                         if (lock_flags[dw->def_nr]) {
1263                                 lock_weight += dw->weight;
1264                         }
1265                         else {
1266                                 tot++;
1267                                 sum_unlock += dw->weight;
1268                         }
1269                 }
1270         }
1271
1272         if (sum == 1.0f) {
1273                 return true;
1274         }
1275
1276         if (tot == 0) {
1277                 return false;
1278         }
1279
1280         if (lock_weight >= 1.0f) {
1281                 /* locked groups make it impossible to fully normalize,
1282                  * zero out what we can and return false */
1283                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1284                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1285                                 if (lock_flags[dw->def_nr] == false) {
1286                                         dw->weight = 0.0f;
1287                                 }
1288                         }
1289                 }
1290
1291                 return (lock_weight == 1.0f);
1292         }
1293         else if (sum_unlock != 0.0f) {
1294                 fac = (1.0f - lock_weight) / sum_unlock;
1295
1296                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1297                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1298                                 if (lock_flags[dw->def_nr] == false) {
1299                                         dw->weight *= fac;
1300                                         /* paranoid but possibly with float error */
1301                                         CLAMP(dw->weight, 0.0f, 1.0f);
1302                                 }
1303                         }
1304                 }
1305         }
1306         else {
1307                 /* hrmf, not a factor in this case */
1308                 fac = (1.0f - lock_weight) / tot;
1309                 /* paranoid but possibly with float error */
1310                 CLAMP(fac, 0.0f, 1.0f);
1311
1312                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1313                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1314                                 if (lock_flags[dw->def_nr] == false) {
1315                                         dw->weight = fac;
1316                                 }
1317                         }
1318                 }
1319         }
1320
1321         return true;
1322 }
1323
1324 /**
1325  * \note same as function above except it does a second pass without active group
1326  * if nomalize fails with it.
1327  */
1328 static void do_weight_paint_normalize_all_locked_try_active(
1329         MDeformVert *dvert, const int defbase_tot, const bool *vgroup_validmap,
1330         const bool *lock_flags, const bool *lock_with_active)
1331 {
1332         /* first pass with both active and explicitly locked groups restricted from change */
1333
1334         bool success = do_weight_paint_normalize_all_locked(dvert, defbase_tot, vgroup_validmap, lock_with_active);
1335
1336         if (!success) {
1337                 /**
1338                  * Locks prevented the first pass from full completion, so remove restriction on active group; e.g:
1339                  *
1340                  * - With 1.0 weight painted into active:
1341                  *   nonzero locked weight; first pass zeroed out unlocked weight; scale 1 down to fit.
1342                  * - With 0.0 weight painted into active:
1343                  *   no unlocked groups; first pass did nothing; increaze 0 to fit.
1344                  */
1345                 do_weight_paint_normalize_all_locked(dvert, defbase_tot, vgroup_validmap, lock_flags);
1346         }
1347 }
1348
1349 #if 0 /* UNUSED */
1350 static bool has_unselected_unlocked_bone_group(int defbase_tot, bool *defbase_sel, int selected,
1351                                                const bool *lock_flags, const bool *vgroup_validmap)
1352 {
1353         int i;
1354         if (defbase_tot == selected) {
1355                 return false;
1356         }
1357         for (i = 0; i < defbase_tot; i++) {
1358                 if (vgroup_validmap[i] && !defbase_sel[i] && !lock_flags[i]) {
1359                         return true;
1360                 }
1361         }
1362         return false;
1363 }
1364 #endif
1365
1366 static void multipaint_clamp_change(
1367         MDeformVert *dvert, const int defbase_tot, const bool *defbase_sel,
1368         float *change_p)
1369 {
1370         int i;
1371         MDeformWeight *dw;
1372         float val;
1373         float change = *change_p;
1374
1375         /* verify that the change does not cause values exceeding 1 and clamp it */
1376         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1377                 if (dw->def_nr < defbase_tot && defbase_sel[dw->def_nr]) {
1378                         if (dw->weight) {
1379                                 val = dw->weight * change;
1380                                 if (val > 1) {
1381                                         change = 1.0f / dw->weight;
1382                                 }
1383                         }
1384                 }
1385         }
1386
1387         *change_p = change;
1388 }
1389
1390 static bool multipaint_verify_change(MDeformVert *dvert, const int defbase_tot, float change, const bool *defbase_sel)
1391 {
1392         int i;
1393         MDeformWeight *dw;
1394         float val;
1395
1396         /* in case the change is reduced, you need to recheck
1397          * the earlier values to make sure they are not 0
1398          * (precision error) */
1399         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1400                 if (dw->def_nr < defbase_tot && defbase_sel[dw->def_nr]) {
1401                         if (dw->weight) {
1402                                 val = dw->weight * change;
1403                                 /* the value should never reach zero while multi-painting if it
1404                                  * was nonzero beforehand */
1405                                 if (val <= 0) {
1406                                         return false;
1407                                 }
1408                         }
1409                 }
1410         }
1411
1412         return true;
1413 }
1414
1415 static void multipaint_apply_change(MDeformVert *dvert, const int defbase_tot, float change, const bool *defbase_sel)
1416 {
1417         int i;
1418         MDeformWeight *dw;
1419
1420         /* apply the valid change */
1421         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1422                 if (dw->def_nr < defbase_tot && defbase_sel[dw->def_nr]) {
1423                         if (dw->weight) {
1424                                 dw->weight = dw->weight * change;
1425                                 CLAMP(dw->weight, 0.0f, 1.0f);
1426                         }
1427                 }
1428         }
1429 }
1430
1431 /**
1432  * Variables stored both for 'active' and 'mirror' sides.
1433  */
1434 struct WeightPaintGroupData {
1435         /** index of active group or its mirror 
1436          *
1437          * - 'active' is always `ob->actdef`.
1438          * - 'mirror' is -1 when 'ME_EDIT_MIRROR_X' flag id disabled,
1439          *   otherwise this will be set to the mirror or the active group (if the group isn't mirrored).
1440          */
1441         int index;
1442         /** lock that includes the 'index' as locked too
1443          *
1444          * - 'active' is set of locked or active/selected groups
1445          * - 'mirror' is set of locked or mirror groups
1446          */
1447         const bool *lock;
1448 };
1449
1450 /* struct to avoid passing many args each call to do_weight_paint_vertex()
1451  * this _could_ be made a part of the operators 'WPaintData' struct, or at
1452  * least a member, but for now keep its own struct, initialized on every
1453  * paint stroke update - campbell */
1454 typedef struct WeightPaintInfo {
1455
1456         int defbase_tot;
1457
1458         /* both must add up to 'defbase_tot' */
1459         int defbase_tot_sel;
1460         int defbase_tot_unsel;
1461
1462         struct WeightPaintGroupData active, mirror;
1463
1464         const bool *lock_flags;  /* boolean array for locked bones,
1465                                   * length of defbase_tot */
1466         const bool *defbase_sel; /* boolean array for selected bones,
1467                                   * length of defbase_tot, cant be const because of how its passed */
1468
1469         const bool *vgroup_validmap; /* same as WeightPaintData.vgroup_validmap,
1470                                       * only added here for convenience */
1471
1472         bool do_flip;
1473         bool do_multipaint;
1474         bool do_auto_normalize;
1475
1476         float brush_alpha_value;  /* result of BKE_brush_alpha_get() */
1477 } WeightPaintInfo;
1478
1479 static void do_weight_paint_vertex_single(
1480         /* vars which remain the same for every vert */
1481         VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
1482         /* vars which change on each stroke */
1483         const unsigned int index, float alpha, float paintweight
1484         )
1485 {
1486         Mesh *me = ob->data;
1487         MDeformVert *dv = &me->dvert[index];
1488         bool topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
1489         
1490         MDeformWeight *dw, *dw_prev;
1491
1492         /* mirror vars */
1493         int index_mirr;
1494         int vgroup_mirr;
1495
1496         MDeformVert *dv_mirr;
1497         MDeformWeight *dw_mirr;
1498
1499         if (wp->flag & VP_ONLYVGROUP) {
1500                 dw = defvert_find_index(dv, wpi->active.index);
1501                 dw_prev = defvert_find_index(wp->wpaint_prev + index, wpi->active.index);
1502         }
1503         else {
1504                 dw = defvert_verify_index(dv, wpi->active.index);
1505                 dw_prev = defvert_verify_index(wp->wpaint_prev + index, wpi->active.index);
1506         }
1507
1508         if (dw == NULL || dw_prev == NULL) {
1509                 return;
1510         }
1511
1512
1513         /* from now on we can check if mirrors enabled if this var is -1 and not bother with the flag */
1514         if (me->editflag & ME_EDIT_MIRROR_X) {
1515                 index_mirr = mesh_get_x_mirror_vert(ob, NULL, index, topology);
1516                 vgroup_mirr = wpi->mirror.index;
1517
1518                 /* another possible error - mirror group _and_ active group are the same (which is fine),
1519                  * but we also are painting onto a center vertex - this would paint the same weight twice */
1520                 if (index_mirr == index && vgroup_mirr == wpi->active.index) {
1521                         index_mirr = vgroup_mirr = -1;
1522                 }
1523         }
1524         else {
1525                 index_mirr = vgroup_mirr = -1;
1526         }
1527
1528
1529         /* get the mirror def vars */
1530         if (index_mirr != -1) {
1531                 dv_mirr = &me->dvert[index_mirr];
1532                 if (wp->flag & VP_ONLYVGROUP) {
1533                         dw_mirr = defvert_find_index(dv_mirr, vgroup_mirr);
1534
1535                         if (dw_mirr == NULL) {
1536                                 index_mirr = vgroup_mirr = -1;
1537                                 dv_mirr = NULL;
1538                         }
1539                 }
1540                 else {
1541                         if (index != index_mirr) {
1542                                 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
1543                         }
1544                         else {
1545                                 /* dv and dv_mirr are the same */
1546                                 int totweight_prev = dv_mirr->totweight;
1547                                 int dw_offset = (int)(dw - dv_mirr->dw);
1548                                 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
1549
1550                                 /* if we added another, get our old one back */
1551                                 if (totweight_prev != dv_mirr->totweight) {
1552                                         dw = &dv_mirr->dw[dw_offset];
1553                                 }
1554                         }
1555                 }
1556         }
1557         else {
1558                 dv_mirr = NULL;
1559                 dw_mirr = NULL;
1560         }
1561
1562         /* If there are no normalize-locks or multipaint,
1563          * then there is no need to run the more complicated checks */
1564
1565         {
1566                 dw->weight = wpaint_blend(wp, dw->weight, dw_prev->weight, alpha, paintweight,
1567                                           wpi->brush_alpha_value, wpi->do_flip);
1568
1569                 /* WATCH IT: take care of the ordering of applying mirror -> normalize,
1570                  * can give wrong results [#26193], least confusing if normalize is done last */
1571
1572                 /* apply mirror */
1573                 if (index_mirr != -1) {
1574                         /* copy, not paint again */
1575                         dw_mirr->weight = dw->weight;
1576                 }
1577
1578                 /* apply normalize */
1579                 if (wpi->do_auto_normalize) {
1580                         /* note on normalize - this used to be applied after painting and normalize all weights,
1581                          * in some ways this is good because there is feedback where the more weights involved would
1582                          * 'resist' so you couldn't instantly zero out other weights by painting 1.0 on the active.
1583                          *
1584                          * However this gave a problem since applying mirror, then normalize both verts
1585                          * the resulting weight wont match on both sides.
1586                          *
1587                          * If this 'resisting', slower normalize is nicer, we could call
1588                          * do_weight_paint_normalize_all() and only use...
1589                          * do_weight_paint_normalize_all_active() when normalizing the mirror vertex.
1590                          * - campbell
1591                          */
1592                         do_weight_paint_normalize_all_locked_try_active(
1593                                 dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->active.lock);
1594
1595                         if (index_mirr != -1) {
1596                                 /* only normalize if this is not a center vertex, else we get a conflict, normalizing twice */
1597                                 if (index != index_mirr) {
1598                                         do_weight_paint_normalize_all_locked_try_active(
1599                                                 dv_mirr, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->mirror.lock);
1600                                 }
1601                                 else {
1602                                         /* this case accounts for...
1603                                          * - painting onto a center vertex of a mesh
1604                                          * - x mirror is enabled
1605                                          * - auto normalize is enabled
1606                                          * - the group you are painting onto has a L / R version
1607                                          *
1608                                          * We want L/R vgroups to have the same weight but this cant be if both are over 0.5,
1609                                          * We _could_ have special check for that, but this would need its own normalize function which
1610                                          * holds 2 groups from changing at once.
1611                                          *
1612                                          * So! just balance out the 2 weights, it keeps them equal and everything normalized.
1613                                          *
1614                                          * While it wont hit the desired weight immediately as the user waggles their mouse,
1615                                          * constant painting and re-normalizing will get there. this is also just simpler logic.
1616                                          * - campbell */
1617                                         dw_mirr->weight = dw->weight = (dw_mirr->weight + dw->weight) * 0.5f;
1618                                 }
1619                         }
1620                 }
1621         }
1622 }
1623
1624 static void do_weight_paint_vertex_multi(
1625         /* vars which remain the same for every vert */
1626         VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
1627         /* vars which change on each stroke */
1628         const unsigned int index, float alpha, float paintweight)
1629 {
1630         Mesh *me = ob->data;
1631         MDeformVert *dv = &me->dvert[index];
1632         MDeformVert *dv_prev = &wp->wpaint_prev[index];
1633         bool topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
1634
1635         /* mirror vars */
1636         int index_mirr = -1;
1637         MDeformVert *dv_mirr = NULL;
1638
1639         /* weights */
1640         float oldw, curw, neww, change, curw_mirr, change_mirr;
1641
1642         /* from now on we can check if mirrors enabled if this var is -1 and not bother with the flag */
1643         if (me->editflag & ME_EDIT_MIRROR_X) {
1644                 index_mirr = mesh_get_x_mirror_vert(ob, NULL, index, topology);
1645
1646                 if (index_mirr != -1 && index_mirr != index) {
1647                         dv_mirr = &me->dvert[index_mirr];
1648                 }
1649         }
1650
1651         /* compute weight change by applying the brush to average or sum of group weights */
1652         oldw = BKE_defvert_multipaint_collective_weight(
1653                 dv_prev, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
1654         curw = BKE_defvert_multipaint_collective_weight(
1655                 dv, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
1656
1657         if (curw == 0.0f) {
1658                 /* note: no weight to assign to this vertex, could add all groups? */
1659                 return;
1660         }
1661
1662         neww = wpaint_blend(wp, curw, oldw, alpha, paintweight, wpi->brush_alpha_value, wpi->do_flip);
1663
1664         change = neww / curw;
1665
1666         /* verify for all groups that 0 < result <= 1 */
1667         multipaint_clamp_change(dv, wpi->defbase_tot, wpi->defbase_sel, &change);
1668
1669         if (dv_mirr != NULL) {
1670                 curw_mirr = BKE_defvert_multipaint_collective_weight(
1671                         dv_mirr, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
1672
1673                 if (curw_mirr == 0.0f) {
1674                         /* can't mirror into a zero weight vertex */
1675                         dv_mirr = NULL;
1676                 }
1677                 else {
1678                         /* mirror is changed to achieve the same collective weight value */
1679                         float orig = change_mirr = curw * change / curw_mirr;
1680
1681                         multipaint_clamp_change(dv_mirr, wpi->defbase_tot, wpi->defbase_sel, &change_mirr);
1682
1683                         if (!multipaint_verify_change(dv_mirr, wpi->defbase_tot, change_mirr, wpi->defbase_sel)) {
1684                                 return;
1685                         }
1686
1687                         change *= change_mirr / orig;
1688                 }
1689         }
1690
1691         if (!multipaint_verify_change(dv, wpi->defbase_tot, change, wpi->defbase_sel)) {
1692                 return;
1693         }
1694
1695         /* apply validated change to vertex and mirror */
1696         multipaint_apply_change(dv, wpi->defbase_tot, change, wpi->defbase_sel);
1697
1698         if (dv_mirr != NULL) {
1699                 multipaint_apply_change(dv_mirr, wpi->defbase_tot, change_mirr, wpi->defbase_sel);
1700         }
1701
1702         /* normalize */
1703         if (wpi->do_auto_normalize) {
1704                 do_weight_paint_normalize_all_locked_try_active(
1705                         dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->active.lock);
1706
1707                 if (dv_mirr != NULL) {
1708                         do_weight_paint_normalize_all_locked_try_active(
1709                                 dv_mirr, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->active.lock);
1710                 }
1711         }
1712 }
1713
1714 static void do_weight_paint_vertex(
1715         /* vars which remain the same for every vert */
1716         VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
1717         /* vars which change on each stroke */
1718         const unsigned int index, float alpha, float paintweight)
1719 {
1720         if (wpi->do_multipaint) {
1721                 do_weight_paint_vertex_multi(wp, ob, wpi, index, alpha, paintweight);
1722         }
1723         else {
1724                 do_weight_paint_vertex_single(wp, ob, wpi, index, alpha, paintweight);
1725         }
1726 }
1727
1728 /* *************** set wpaint operator ****************** */
1729
1730 /**
1731  * \note Keep in sync with #vpaint_mode_toggle_exec
1732  */
1733 static int wpaint_mode_toggle_exec(bContext *C, wmOperator *op)
1734 {               
1735         Object *ob = CTX_data_active_object(C);
1736         const int mode_flag = OB_MODE_WEIGHT_PAINT;
1737         const bool is_mode_set = (ob->mode & mode_flag) != 0;
1738         Scene *scene = CTX_data_scene(C);
1739         VPaint *wp = scene->toolsettings->wpaint;
1740         Mesh *me;
1741
1742         if (!is_mode_set) {
1743                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
1744                         return OPERATOR_CANCELLED;
1745                 }
1746         }
1747
1748         me = BKE_mesh_from_object(ob);
1749
1750         if (ob->mode & mode_flag) {
1751                 ob->mode &= ~mode_flag;
1752
1753                 if (me->editflag & ME_EDIT_PAINT_VERT_SEL) {
1754                         BKE_mesh_flush_select_from_verts(me);
1755                 }
1756                 else if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
1757                         BKE_mesh_flush_select_from_polys(me);
1758                 }
1759
1760                 /* weight paint specific */
1761                 ED_mesh_mirror_spatial_table(NULL, NULL, NULL, NULL, 'e');
1762                 ED_mesh_mirror_topo_table(NULL, NULL, 'e');
1763
1764                 paint_cursor_delete_textures();
1765         }
1766         else {
1767                 ob->mode |= mode_flag;
1768
1769                 if (wp == NULL)
1770                         wp = scene->toolsettings->wpaint = new_vpaint(1);
1771
1772                 paint_cursor_start(C, weight_paint_poll);
1773
1774                 BKE_paint_init(scene, ePaintWeight, PAINT_CURSOR_WEIGHT_PAINT);
1775
1776                 /* weight paint specific */
1777                 ED_mesh_mirror_spatial_table(ob, NULL, NULL, NULL, 's');
1778                 ED_vgroup_sync_from_pose(ob);
1779         }
1780         
1781         /* Weightpaint works by overriding colors in mesh,
1782          * so need to make sure we recalc on enter and
1783          * exit (exit needs doing regardless because we
1784          * should redeform).
1785          */
1786         DAG_id_tag_update(&me->id, 0);
1787
1788         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
1789
1790         return OPERATOR_FINISHED;
1791 }
1792
1793 /* for switching to/from mode */
1794 static int paint_poll_test(bContext *C)
1795 {
1796         Object *ob = CTX_data_active_object(C);
1797         if (ob == NULL || ob->type != OB_MESH)
1798                 return 0;
1799         if (!ob->data || ((ID *)ob->data)->lib)
1800                 return 0;
1801         if (CTX_data_edit_object(C))
1802                 return 0;
1803         return 1;
1804 }
1805
1806 void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
1807 {
1808         
1809         /* identifiers */
1810         ot->name = "Weight Paint Mode";
1811         ot->idname = "PAINT_OT_weight_paint_toggle";
1812         ot->description = "Toggle weight paint mode in 3D view";
1813         
1814         /* api callbacks */
1815         ot->exec = wpaint_mode_toggle_exec;
1816         ot->poll = paint_poll_test;
1817         
1818         /* flags */
1819         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1820         
1821 }
1822
1823 /* ************ weight paint operator ********** */
1824
1825 enum eWPaintFlag {
1826         WPAINT_ENSURE_MIRROR = (1 << 0),
1827 };
1828
1829 struct WPaintVGroupIndex {
1830         int active;
1831         int mirror;
1832 };
1833
1834 struct WPaintData {
1835         ViewContext vc;
1836         int *indexar;
1837
1838         struct WeightPaintGroupData active, mirror;
1839
1840         void *vp_handle;
1841         DMCoNo *vertexcosnos;
1842
1843         float wpimat[3][3];
1844
1845         /* variables for auto normalize */
1846         const bool *vgroup_validmap; /* stores if vgroups tie to deforming bones or not */
1847         const bool *lock_flags;
1848
1849         /* variables for multipaint */
1850         const bool *defbase_sel;      /* set of selected groups */
1851         int defbase_tot_sel;          /* number of selected groups */
1852         bool do_multipaint;           /* true if multipaint enabled and multiple groups selected */
1853
1854         /* variables for blur */
1855         struct {
1856                 MeshElemMap *vmap;
1857                 int *vmap_mem;
1858         } blur_data;
1859
1860         BLI_Stack *accumulate_stack;  /* for reuse (WPaintDefer) */
1861
1862         int defbase_tot;
1863 };
1864
1865 /* ensure we have data on wpaint start, add if needed */
1866 static bool wpaint_ensure_data(
1867         bContext *C, wmOperator *op,
1868         enum eWPaintFlag flag, struct WPaintVGroupIndex *vgroup_index)
1869 {
1870         Scene *scene = CTX_data_scene(C);
1871         Object *ob = CTX_data_active_object(C);
1872         Mesh *me = BKE_mesh_from_object(ob);
1873
1874         if (vgroup_index) {
1875                 vgroup_index->active = -1;
1876                 vgroup_index->mirror = -1;
1877         }
1878
1879         if (scene->obedit) {
1880                 return false;
1881         }
1882
1883         if (me == NULL || me->totpoly == 0) {
1884                 return false;
1885         }
1886
1887         /* if nothing was added yet, we make dverts and a vertex deform group */
1888         if (!me->dvert) {
1889                 BKE_object_defgroup_data_create(&me->id);
1890                 WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
1891         }
1892
1893         /* this happens on a Bone select, when no vgroup existed yet */
1894         if (ob->actdef <= 0) {
1895                 Object *modob;
1896                 if ((modob = modifiers_isDeformedByArmature(ob))) {
1897                         Bone *actbone = ((bArmature *)modob->data)->act_bone;
1898                         if (actbone) {
1899                                 bPoseChannel *pchan = BKE_pose_channel_find_name(modob->pose, actbone->name);
1900
1901                                 if (pchan) {
1902                                         bDeformGroup *dg = defgroup_find_name(ob, pchan->name);
1903                                         if (dg == NULL) {
1904                                                 dg = BKE_object_defgroup_add_name(ob, pchan->name);  /* sets actdef */
1905                                         }
1906                                         else {
1907                                                 int actdef = 1 + BLI_findindex(&ob->defbase, dg);
1908                                                 BLI_assert(actdef >= 0);
1909                                                 ob->actdef = actdef;
1910                                         }
1911                                 }
1912                         }
1913                 }
1914         }
1915         if (BLI_listbase_is_empty(&ob->defbase)) {
1916                 BKE_object_defgroup_add(ob);
1917         }
1918
1919         /* ensure we don't try paint onto an invalid group */
1920         if (ob->actdef <= 0) {
1921                 BKE_report(op->reports, RPT_WARNING, "No active vertex group for painting, aborting");
1922                 return false;
1923         }
1924
1925         if (vgroup_index) {
1926                 vgroup_index->active = ob->actdef - 1;
1927         }
1928
1929         if (flag & WPAINT_ENSURE_MIRROR) {
1930                 if (me->editflag & ME_EDIT_MIRROR_X) {
1931                         int mirror = wpaint_mirror_vgroup_ensure(ob, ob->actdef - 1);
1932                         if (vgroup_index) {
1933                                 vgroup_index->mirror = mirror;
1934                         }
1935                 }
1936         }
1937
1938         return true;
1939 }
1940
1941 static bool wpaint_stroke_test_start(bContext *C, wmOperator *op, const float UNUSED(mouse[2]))
1942 {
1943         Scene *scene = CTX_data_scene(C);
1944         struct PaintStroke *stroke = op->customdata;
1945         ToolSettings *ts = scene->toolsettings;
1946         VPaint *wp = ts->wpaint;
1947         Object *ob = CTX_data_active_object(C);
1948         Mesh *me = BKE_mesh_from_object(ob);
1949         struct WPaintData *wpd;
1950         struct WPaintVGroupIndex vgroup_index;
1951         int defbase_tot, defbase_tot_sel;
1952         bool *defbase_sel;
1953         const Brush *brush = BKE_paint_brush(&wp->paint);
1954
1955         float mat[4][4], imat[4][4];
1956
1957         if (wpaint_ensure_data(C, op, WPAINT_ENSURE_MIRROR, &vgroup_index) == false) {
1958                 return false;
1959         }
1960
1961         {
1962                 /* check if we are attempting to paint onto a locked vertex group,
1963                  * and other options disallow it from doing anything useful */
1964                 bDeformGroup *dg;
1965                 dg = BLI_findlink(&ob->defbase, vgroup_index.active);
1966                 if (dg->flag & DG_LOCK_WEIGHT) {
1967                         BKE_report(op->reports, RPT_WARNING, "Active group is locked, aborting");
1968                         return false;
1969                 }
1970                 if (vgroup_index.mirror != -1) {
1971                         dg = BLI_findlink(&ob->defbase, vgroup_index.mirror);
1972                         if (dg->flag & DG_LOCK_WEIGHT) {
1973                                 BKE_report(op->reports, RPT_WARNING, "Mirror group is locked, aborting");
1974                                 return false;
1975                         }
1976                 }
1977         }
1978
1979         /* check that multipaint groups are unlocked */
1980         defbase_tot = BLI_listbase_count(&ob->defbase);
1981         defbase_sel = BKE_object_defgroup_selected_get(ob, defbase_tot, &defbase_tot_sel);
1982
1983         if (ts->multipaint && defbase_tot_sel > 1) {
1984                 int i;
1985                 bDeformGroup *dg;
1986
1987                 if (me->editflag & ME_EDIT_MIRROR_X) {
1988                         BKE_object_defgroup_mirror_selection(ob, defbase_tot, defbase_sel, defbase_sel, &defbase_tot_sel);
1989                 }
1990
1991                 for (i = 0; i < defbase_tot; i++) {
1992                         if (defbase_sel[i]) {
1993                                 dg = BLI_findlink(&ob->defbase, i);
1994                                 if (dg->flag & DG_LOCK_WEIGHT) {
1995                                         BKE_report(op->reports, RPT_WARNING, "Multipaint group is locked, aborting");
1996                                         MEM_freeN(defbase_sel);
1997                                         return false;
1998                                 }
1999                         }
2000                 }
2001         }
2002
2003         /* ALLOCATIONS! no return after this line */
2004         /* make mode data storage */
2005         wpd = MEM_callocN(sizeof(struct WPaintData), "WPaintData");
2006         paint_stroke_set_mode_data(stroke, wpd);
2007         view3d_set_viewcontext(C, &wpd->vc);
2008
2009         wpd->active.index = vgroup_index.active;
2010         wpd->mirror.index = vgroup_index.mirror;
2011
2012         /* multipaint */
2013         wpd->defbase_tot = defbase_tot;
2014         wpd->defbase_sel = defbase_sel;
2015         wpd->defbase_tot_sel = defbase_tot_sel > 1 ? defbase_tot_sel : 1;
2016         wpd->do_multipaint = (ts->multipaint && defbase_tot_sel > 1);
2017
2018         /* set up auto-normalize, and generate map for detecting which
2019          * vgroups affect deform bones */
2020         wpd->lock_flags = BKE_object_defgroup_lock_flags_get(ob, wpd->defbase_tot);
2021         if (ts->auto_normalize || ts->multipaint || wpd->lock_flags) {
2022                 wpd->vgroup_validmap = BKE_object_defgroup_validmap_get(ob, wpd->defbase_tot);
2023         }
2024
2025         if (wpd->do_multipaint && ts->auto_normalize) {
2026                 bool *tmpflags;
2027                 tmpflags = MEM_mallocN(sizeof(bool) * defbase_tot, __func__);
2028                 if (wpd->lock_flags) {
2029                         BLI_array_binary_or(tmpflags, wpd->defbase_sel, wpd->lock_flags, wpd->defbase_tot);
2030                 }
2031                 else {
2032                         memcpy(tmpflags, wpd->defbase_sel, sizeof(*tmpflags) * wpd->defbase_tot);
2033                 }
2034                 wpd->active.lock = tmpflags;
2035         }
2036         else if (ts->auto_normalize) {
2037                 bool *tmpflags;
2038
2039                 tmpflags = wpd->lock_flags ?
2040                         MEM_dupallocN(wpd->lock_flags) :
2041                         MEM_callocN(sizeof(bool) * defbase_tot, __func__);
2042                 tmpflags[wpd->active.index] = true;
2043                 wpd->active.lock = tmpflags;
2044
2045                 tmpflags = wpd->lock_flags ?
2046                         MEM_dupallocN(wpd->lock_flags) :
2047                         MEM_callocN(sizeof(bool) * defbase_tot, __func__);
2048                 tmpflags[(wpd->mirror.index != -1) ? wpd->mirror.index : wpd->active.index] = true;
2049                 wpd->mirror.lock = tmpflags;
2050         }
2051
2052         /* painting on subsurfs should give correct points too, this returns me->totvert amount */
2053         wpd->vp_handle = ED_vpaint_proj_handle_create(scene, ob, &wpd->vertexcosnos);
2054
2055         wpd->indexar = get_indexarray(me);
2056         copy_wpaint_prev(wp, me->dvert, me->totvert);
2057
2058         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2059                 BKE_mesh_vert_edge_vert_map_create(
2060                         &wpd->blur_data.vmap, &wpd->blur_data.vmap_mem,
2061                         me->medge, me->totvert, me->totedge);
2062         }
2063
2064         if ((brush->vertexpaint_tool == PAINT_BLEND_BLUR) &&
2065             (brush->flag & BRUSH_ACCUMULATE))
2066         {
2067                 wpd->accumulate_stack = BLI_stack_new(sizeof(struct WPaintDefer), __func__);
2068         }
2069
2070         /* imat for normals */
2071         mul_m4_m4m4(mat, wpd->vc.rv3d->viewmat, ob->obmat);
2072         invert_m4_m4(imat, mat);
2073         copy_m3_m4(wpd->wpimat, imat);
2074
2075         return true;
2076 }
2077
2078 static float wpaint_blur_weight_single(const MDeformVert *dv, const WeightPaintInfo *wpi)
2079 {
2080         return defvert_find_weight(dv, wpi->active.index);
2081 }
2082
2083 static float wpaint_blur_weight_multi(const MDeformVert *dv, const WeightPaintInfo *wpi)
2084 {
2085         float weight = BKE_defvert_multipaint_collective_weight(
2086                 dv, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
2087         CLAMP(weight, 0.0f, 1.0f);
2088         return weight;
2089 }
2090
2091 static float wpaint_blur_weight_calc_from_connected(
2092         const MDeformVert *dvert, WeightPaintInfo *wpi, struct WPaintData *wpd, const unsigned int vidx,
2093         float (*blur_weight_func)(const MDeformVert *, const WeightPaintInfo *))
2094 {
2095         const MeshElemMap *map = &wpd->blur_data.vmap[vidx];
2096         float paintweight;
2097         if (map->count != 0) {
2098                 paintweight = 0.0f;
2099                 for (int j = 0; j < map->count; j++) {
2100                         paintweight += blur_weight_func(&dvert[map->indices[j]], wpi);
2101                 }
2102                 paintweight /= map->count;
2103         }
2104         else {
2105                 paintweight = blur_weight_func(&dvert[vidx], wpi);
2106         }
2107
2108         return paintweight;
2109 }
2110
2111 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2112 {
2113         Scene *scene = CTX_data_scene(C);
2114         ToolSettings *ts = CTX_data_tool_settings(C);
2115         VPaint *wp = ts->wpaint;
2116         Brush *brush = BKE_paint_brush(&wp->paint);
2117         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2118         ViewContext *vc;
2119         Object *ob;
2120         Mesh *me;
2121         float mat[4][4];
2122         float paintweight;
2123         int *indexar;
2124         unsigned int index, totindex;
2125         float mval[2];
2126         const bool use_blur = (brush->vertexpaint_tool == PAINT_BLEND_BLUR);
2127         bool use_vert_sel;
2128         bool use_face_sel;
2129         bool use_depth;
2130
2131         const float pressure = RNA_float_get(itemptr, "pressure");
2132         const float brush_size_pressure =
2133                 BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2134         const float brush_alpha_value = BKE_brush_alpha_get(scene, brush);
2135         const float brush_alpha_pressure =
2136                 brush_alpha_value * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2137
2138         /* intentionally don't initialize as NULL, make sure we initialize all members below */
2139         WeightPaintInfo wpi;
2140
2141         /* cannot paint if there is no stroke data */
2142         if (wpd == NULL) {
2143                 /* XXX: force a redraw here, since even though we can't paint,
2144                  * at least view won't freeze until stroke ends */
2145                 ED_region_tag_redraw(CTX_wm_region(C));
2146                 return;
2147         }
2148
2149         float (*blur_weight_func)(const MDeformVert *, const WeightPaintInfo *) =
2150                 wpd->do_multipaint ? wpaint_blur_weight_multi : wpaint_blur_weight_single;
2151
2152         vc = &wpd->vc;
2153         ob = vc->obact;
2154         me = ob->data;
2155         indexar = wpd->indexar;
2156         
2157         view3d_operator_needs_opengl(C);
2158         ED_view3d_init_mats_rv3d(ob, vc->rv3d);
2159
2160         /* load projection matrix */
2161         mul_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2162
2163         RNA_float_get_array(itemptr, "mouse", mval);
2164
2165         /* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
2166         wpi.defbase_tot =        wpd->defbase_tot;
2167         wpi.defbase_sel =        wpd->defbase_sel;
2168         wpi.defbase_tot_sel =    wpd->defbase_tot_sel;
2169
2170         wpi.defbase_tot_unsel =  wpi.defbase_tot - wpi.defbase_tot_sel;
2171         wpi.active =             wpd->active;
2172         wpi.mirror =             wpd->mirror;
2173         wpi.lock_flags =         wpd->lock_flags;
2174         wpi.vgroup_validmap =    wpd->vgroup_validmap;
2175         wpi.do_flip =            RNA_boolean_get(itemptr, "pen_flip");
2176         wpi.do_multipaint =      wpd->do_multipaint;
2177         wpi.do_auto_normalize =  ((ts->auto_normalize != 0) && (wpi.vgroup_validmap != NULL));
2178         wpi.brush_alpha_value =  brush_alpha_value;
2179         /* *** done setting up WeightPaintInfo *** */
2180
2181
2182
2183         swap_m4m4(wpd->vc.rv3d->persmat, mat);
2184
2185         use_vert_sel = (me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
2186         use_face_sel = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
2187         use_depth = (vc->v3d->flag & V3D_ZBUF_SELECT) != 0;
2188
2189         /* which faces are involved */
2190         if (use_depth) {
2191                 char editflag_prev = me->editflag;
2192
2193                 /* Ugly hack, to avoid drawing vertex index when getting the face index buffer - campbell */
2194                 me->editflag &= ~ME_EDIT_PAINT_VERT_SEL;
2195                 if (use_vert_sel) {
2196                         /* Ugly x2, we need this so hidden faces don't draw */
2197                         me->editflag |= ME_EDIT_PAINT_FACE_SEL;
2198                 }
2199                 totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2200                 me->editflag = editflag_prev;
2201
2202                 if (use_face_sel && me->totpoly) {
2203                         MPoly *mpoly = me->mpoly;
2204                         for (index = 0; index < totindex; index++) {
2205                                 if (indexar[index] && indexar[index] <= me->totpoly) {
2206                                         MPoly *mp = &mpoly[indexar[index] - 1];
2207
2208                                         if ((mp->flag & ME_FACE_SEL) == 0) {
2209                                                 indexar[index] = 0;
2210                                         }
2211                                 }
2212                         }
2213                 }
2214         }
2215         else {
2216                 indexar = NULL;
2217         }
2218
2219         /* incase we have modifiers */
2220         ED_vpaint_proj_handle_update(wpd->vp_handle, vc->ar, mval);
2221
2222         /* make sure each vertex gets treated only once */
2223         /* and calculate filter weight */
2224         paintweight = BKE_brush_weight_get(scene, brush);
2225
2226         if (use_depth) {
2227                 for (index = 0; index < totindex; index++) {
2228                         if (indexar[index] && indexar[index] <= me->totpoly) {
2229                                 MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2230                                 MLoop *ml = me->mloop + mpoly->loopstart;
2231                                 int i;
2232
2233                                 if (use_vert_sel) {
2234                                         for (i = 0; i < mpoly->totloop; i++, ml++) {
2235                                                 me->dvert[ml->v].flag = (me->mvert[ml->v].flag & SELECT);
2236                                         }
2237                                 }
2238                                 else {
2239                                         for (i = 0; i < mpoly->totloop; i++, ml++) {
2240                                                 me->dvert[ml->v].flag = 1;
2241                                         }
2242                                 }
2243                         }
2244                 }
2245         }
2246         else {
2247                 const unsigned int totvert = me->totvert;
2248                 unsigned int       i;
2249
2250                 /* in the case of face selection we need to flush */
2251                 if (use_vert_sel || use_face_sel) {
2252                         for (i = 0; i < totvert; i++) {
2253                                 me->dvert[i].flag = me->mvert[i].flag & SELECT;
2254                         }
2255                 }
2256                 else {
2257                         for (i = 0; i < totvert; i++) {
2258                                 me->dvert[i].flag = SELECT;
2259                         }
2260                 }
2261         }
2262
2263         /* accumulate means we refer to the previous,
2264          * which is either the last update, or when we started painting */
2265         BLI_Stack *accumulate_stack = wpd->accumulate_stack;
2266         const bool use_accumulate = (accumulate_stack != NULL);
2267         BLI_assert(accumulate_stack == NULL || BLI_stack_is_empty(accumulate_stack));
2268
2269         const MDeformVert *dvert_prev = use_accumulate ? me->dvert : wp->wpaint_prev;
2270
2271 #define WP_PAINT(v_idx_var)  \
2272         { \
2273                 unsigned int vidx = v_idx_var; \
2274                 if (me->dvert[vidx].flag) { \
2275                         const float alpha = calc_vp_alpha_col_dl( \
2276                                 wp, vc, wpd->wpimat, &wpd->vertexcosnos[vidx], \
2277                                 mval, brush_size_pressure, brush_alpha_pressure, NULL); \
2278                         if (alpha) { \
2279                                 if (use_blur) { \
2280                                         paintweight = wpaint_blur_weight_calc_from_connected( \
2281                                                 dvert_prev, &wpi, wpd, vidx, blur_weight_func); \
2282                                 } \
2283                                 if (use_accumulate) { \
2284                                         struct WPaintDefer *dweight = BLI_stack_push_r(accumulate_stack); \
2285                                         dweight->index = vidx; \
2286                                         dweight->alpha = alpha; \
2287                                         dweight->weight = paintweight; \
2288                                 } \
2289                                 else { \
2290                                         do_weight_paint_vertex(wp, ob, &wpi, vidx, alpha, paintweight); \
2291                                 } \
2292                         } \
2293                         me->dvert[vidx].flag = 0; \
2294                 } \
2295         } (void)0
2296
2297         if (use_depth) {
2298                 for (index = 0; index < totindex; index++) {
2299
2300                         if (indexar[index] && indexar[index] <= me->totpoly) {
2301                                 MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2302                                 MLoop *ml = me->mloop + mpoly->loopstart;
2303                                 int i;
2304
2305                                 for (i = 0; i < mpoly->totloop; i++, ml++) {
2306                                         WP_PAINT(ml->v);
2307                                 }
2308                         }
2309                 }
2310         }
2311         else {
2312                 const unsigned int totvert = me->totvert;
2313                 unsigned int       i;
2314
2315                 for (i = 0; i < totvert; i++) {
2316                         WP_PAINT(i);
2317                 }
2318         }
2319 #undef WP_PAINT
2320
2321         if (use_accumulate) {
2322                 unsigned int defer_count = BLI_stack_count(accumulate_stack);
2323                 while (defer_count--) {
2324                         struct WPaintDefer *dweight = BLI_stack_peek(accumulate_stack);
2325                         do_weight_paint_vertex(wp, ob, &wpi, dweight->index, dweight->alpha, dweight->weight);
2326                         BLI_stack_discard(accumulate_stack);
2327                 }
2328         }
2329
2330
2331         /* *** free wpi members */
2332         /* *** done freeing wpi members */
2333
2334
2335         swap_m4m4(vc->rv3d->persmat, mat);
2336
2337         /* calculate pivot for rotation around seletion if needed */
2338         if (U.uiflag & USER_ORBIT_SELECTION) {
2339                 paint_last_stroke_update(scene, vc->ar, mval);
2340         }
2341
2342         DAG_id_tag_update(ob->data, 0);
2343         ED_region_tag_redraw(vc->ar);
2344 }
2345
2346 static void wpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2347 {
2348         ToolSettings *ts = CTX_data_tool_settings(C);
2349         Object *ob = CTX_data_active_object(C);
2350         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2351         
2352         if (wpd) {
2353                 ED_vpaint_proj_handle_free(wpd->vp_handle);
2354                 MEM_freeN(wpd->indexar);
2355                 
2356                 if (wpd->defbase_sel)
2357                         MEM_freeN((void *)wpd->defbase_sel);
2358                 if (wpd->vgroup_validmap)
2359                         MEM_freeN((void *)wpd->vgroup_validmap);
2360                 if (wpd->lock_flags)
2361                         MEM_freeN((void *)wpd->lock_flags);
2362                 if (wpd->active.lock)
2363                         MEM_freeN((void *)wpd->active.lock);
2364                 if (wpd->mirror.lock)
2365                         MEM_freeN((void *)wpd->mirror.lock);
2366
2367                 if (wpd->blur_data.vmap) {
2368                         MEM_freeN(wpd->blur_data.vmap);
2369                 }
2370                 if (wpd->blur_data.vmap_mem) {
2371                         MEM_freeN(wpd->blur_data.vmap_mem);
2372                 }
2373
2374                 if (wpd->accumulate_stack) {
2375                         BLI_stack_free(wpd->accumulate_stack);
2376                 }
2377
2378                 MEM_freeN(wpd);
2379         }
2380         
2381         /* frees prev buffer */
2382         copy_wpaint_prev(ts->wpaint, NULL, 0);
2383         
2384         /* and particles too */
2385         if (ob->particlesystem.first) {
2386                 ParticleSystem *psys;
2387                 int i;
2388                 
2389                 for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2390                         for (i = 0; i < PSYS_TOT_VG; i++) {
2391                                 if (psys->vgroup[i] == ob->actdef) {
2392                                         psys->recalc |= PSYS_RECALC_RESET;
2393                                         break;
2394                                 }
2395                         }
2396                 }
2397         }
2398
2399         DAG_id_tag_update(ob->data, 0);
2400
2401         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2402 }
2403
2404
2405 static int wpaint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2406 {
2407         int retval;
2408
2409         op->customdata = paint_stroke_new(C, op, NULL, wpaint_stroke_test_start,
2410                                           wpaint_stroke_update_step, NULL,
2411                                           wpaint_stroke_done, event->type);
2412         
2413         if ((retval = op->type->modal(C, op, event)) == OPERATOR_FINISHED) {
2414                 paint_stroke_data_free(op);
2415                 return OPERATOR_FINISHED;
2416         }
2417         /* add modal handler */
2418         WM_event_add_modal_handler(C, op);
2419
2420         OPERATOR_RETVAL_CHECK(retval);
2421         BLI_assert(retval == OPERATOR_RUNNING_MODAL);
2422         
2423         return OPERATOR_RUNNING_MODAL;
2424 }
2425
2426 static int wpaint_exec(bContext *C, wmOperator *op)
2427 {
2428         op->customdata = paint_stroke_new(C, op, NULL, wpaint_stroke_test_start,
2429                                           wpaint_stroke_update_step, NULL,
2430                                           wpaint_stroke_done, 0);
2431
2432         /* frees op->customdata */
2433         paint_stroke_exec(C, op);
2434
2435         return OPERATOR_FINISHED;
2436 }
2437
2438 static void wpaint_cancel(bContext *C, wmOperator *op)
2439 {
2440         paint_stroke_cancel(C, op);
2441 }
2442
2443 void PAINT_OT_weight_paint(wmOperatorType *ot)
2444 {
2445         
2446         /* identifiers */
2447         ot->name = "Weight Paint";
2448         ot->idname = "PAINT_OT_weight_paint";
2449         ot->description = "Paint a stroke in the current vertex group's weights";
2450         
2451         /* api callbacks */
2452         ot->invoke = wpaint_invoke;
2453         ot->modal = paint_stroke_modal;
2454         ot->exec = wpaint_exec;
2455         ot->poll = weight_paint_poll;
2456         ot->cancel = wpaint_cancel;
2457         
2458         /* flags */
2459         ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
2460         
2461         paint_stroke_operator_properties(ot);
2462 }
2463
2464 static int weight_paint_set_exec(bContext *C, wmOperator *op)
2465 {
2466         struct Scene *scene = CTX_data_scene(C);
2467         Object *obact = CTX_data_active_object(C);
2468         ToolSettings *ts = CTX_data_tool_settings(C);
2469         Brush *brush = BKE_paint_brush(&ts->wpaint->paint);
2470         float vgroup_weight = BKE_brush_weight_get(scene, brush);
2471
2472         if (wpaint_ensure_data(C, op, WPAINT_ENSURE_MIRROR, NULL) == false) {
2473                 return OPERATOR_CANCELLED;
2474         }
2475
2476         if (ED_wpaint_fill(scene->toolsettings->wpaint, obact, vgroup_weight)) {
2477                 ED_region_tag_redraw(CTX_wm_region(C)); /* XXX - should redraw all 3D views */
2478                 return OPERATOR_FINISHED;
2479         }
2480         else {
2481                 return OPERATOR_CANCELLED;
2482         }
2483 }
2484
2485 void PAINT_OT_weight_set(wmOperatorType *ot)
2486 {
2487         /* identifiers */
2488         ot->name = "Set Weight";
2489         ot->idname = "PAINT_OT_weight_set";
2490         ot->description = "Fill the active vertex group with the current paint weight";
2491
2492         /* api callbacks */
2493         ot->exec = weight_paint_set_exec;
2494         ot->poll = mask_paint_poll;
2495
2496         /* flags */
2497         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2498 }
2499
2500 /* ************ set / clear vertex paint mode ********** */
2501
2502 /**
2503  * \note Keep in sync with #wpaint_mode_toggle_exec
2504  */
2505 static int vpaint_mode_toggle_exec(bContext *C, wmOperator *op)
2506 {       
2507         Object *ob = CTX_data_active_object(C);
2508         const int mode_flag = OB_MODE_VERTEX_PAINT;
2509         const bool is_mode_set = (ob->mode & mode_flag) != 0;
2510         Scene *scene = CTX_data_scene(C);
2511         VPaint *vp = scene->toolsettings->vpaint;
2512         Mesh *me;
2513
2514         if (!is_mode_set) {
2515                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
2516                         return OPERATOR_CANCELLED;
2517                 }
2518         }
2519
2520         me = BKE_mesh_from_object(ob);
2521         
2522         /* toggle: end vpaint */
2523         if (is_mode_set) {
2524                 ob->mode &= ~mode_flag;
2525
2526                 if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
2527                         BKE_mesh_flush_select_from_polys(me);
2528                 }
2529
2530                 paint_cursor_delete_textures();
2531         }
2532         else {
2533                 ob->mode |= mode_flag;
2534
2535                 if (me->mloopcol == NULL) {
2536                         make_vertexcol(ob);
2537                 }
2538
2539                 if (vp == NULL)
2540                         vp = scene->toolsettings->vpaint = new_vpaint(0);
2541                 
2542                 paint_cursor_start(C, vertex_paint_poll);
2543
2544                 BKE_paint_init(scene, ePaintVertex, PAINT_CURSOR_VERTEX_PAINT);
2545         }
2546         
2547         /* update modifier stack for mapping requirements */
2548         DAG_id_tag_update(&me->id, 0);
2549         
2550         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
2551         
2552         return OPERATOR_FINISHED;
2553 }
2554
2555 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2556 {
2557         
2558         /* identifiers */
2559         ot->name = "Vertex Paint Mode";
2560         ot->idname = "PAINT_OT_vertex_paint_toggle";
2561         ot->description = "Toggle the vertex paint mode in 3D view";
2562         
2563         /* api callbacks */
2564         ot->exec = vpaint_mode_toggle_exec;
2565         ot->poll = paint_poll_test;
2566         
2567         /* flags */
2568         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2569 }
2570
2571
2572
2573 /* ********************** vertex paint operator ******************* */
2574
2575 /* Implementation notes:
2576  *
2577  * Operator->invoke()
2578  * - validate context (add mcol)
2579  * - create customdata storage
2580  * - call paint once (mouse click)
2581  * - add modal handler 
2582  *
2583  * Operator->modal()
2584  * - for every mousemove, apply vertex paint
2585  * - exit on mouse release, free customdata
2586  *   (return OPERATOR_FINISHED also removes handler and operator)
2587  *
2588  * For future:
2589  * - implement a stroke event (or mousemove with past positons)
2590  * - revise whether op->customdata should be added in object, in set_vpaint
2591  */
2592
2593 typedef struct PolyFaceMap {
2594         struct PolyFaceMap *next, *prev;
2595         int facenr;
2596 } PolyFaceMap;
2597
2598 typedef struct VPaintData {
2599         ViewContext vc;
2600         unsigned int paintcol;
2601         int *indexar;
2602
2603         struct VertProjHandle *vp_handle;
2604         DMCoNo *vertexcosnos;
2605
2606         float vpimat[3][3];
2607
2608         /* modify 'me->mcol' directly, since the derived mesh is drawing from this
2609          * array, otherwise we need to refresh the modifier stack */
2610         bool use_fast_update;
2611
2612         /* loops tagged as having been painted, to apply shared vertex color
2613          * blending only to modified loops */
2614         bool *mlooptag;
2615
2616         bool is_texbrush;
2617 } VPaintData;
2618
2619 static bool vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const float UNUSED(mouse[2]))
2620 {
2621         Scene *scene = CTX_data_scene(C);
2622         ToolSettings *ts = scene->toolsettings;
2623         struct PaintStroke *stroke = op->customdata;
2624         VPaint *vp = ts->vpaint;
2625         Brush *brush = BKE_paint_brush(&vp->paint);
2626         struct VPaintData *vpd;
2627         Object *ob = CTX_data_active_object(C);
2628         Mesh *me;
2629         float mat[4][4], imat[4][4];
2630
2631         /* context checks could be a poll() */
2632         me = BKE_mesh_from_object(ob);
2633         if (me == NULL || me->totpoly == 0)
2634                 return false;
2635         
2636         if (me->mloopcol == NULL)
2637                 make_vertexcol(ob);
2638         if (me->mloopcol == NULL)
2639                 return false;
2640
2641         /* make mode data storage */
2642         vpd = MEM_callocN(sizeof(struct VPaintData), "VPaintData");
2643         paint_stroke_set_mode_data(stroke, vpd);
2644         view3d_set_viewcontext(C, &vpd->vc);
2645         
2646         vpd->vp_handle = ED_vpaint_proj_handle_create(vpd->vc.scene, ob, &vpd->vertexcosnos);
2647
2648         vpd->indexar = get_indexarray(me);
2649         vpd->paintcol = vpaint_get_current_col(scene, vp);
2650
2651         vpd->is_texbrush = !(brush->vertexpaint_tool == PAINT_BLEND_BLUR) &&
2652                            brush->mtex.tex;
2653
2654         /* are we painting onto a modified mesh?,
2655          * if not we can skip face map trickiness */
2656         if (vertex_paint_use_fast_update_check(ob)) {
2657                 vpd->use_fast_update = true;
2658 /*              printf("Fast update!\n");*/
2659         }
2660         else {
2661                 vpd->use_fast_update = false;
2662 /*              printf("No fast update!\n");*/
2663         }
2664
2665         /* to keep tracked of modified loops for shared vertex color blending */
2666         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2667                 vpd->mlooptag = MEM_mallocN(sizeof(bool) * me->totloop, "VPaintData mlooptag");
2668         }
2669
2670         /* for filtering */
2671         copy_vpaint_prev(vp, (unsigned int *)me->mloopcol, me->totloop);
2672         
2673         /* some old cruft to sort out later */
2674         mul_m4_m4m4(mat, vpd->vc.rv3d->viewmat, ob->obmat);
2675         invert_m4_m4(imat, mat);
2676         copy_m3_m4(vpd->vpimat, imat);
2677
2678         return 1;
2679 }
2680
2681 static void vpaint_paint_poly(VPaint *vp, VPaintData *vpd, Mesh *me,
2682                               const unsigned int index, const float mval[2],
2683                               const float brush_size_pressure, const float brush_alpha_pressure)
2684 {
2685         ViewContext *vc = &vpd->vc;
2686         Brush *brush = BKE_paint_brush(&vp->paint);
2687         MPoly *mpoly = &me->mpoly[index];
2688         MLoop *ml;
2689         unsigned int *lcol = ((unsigned int *)me->mloopcol) + mpoly->loopstart;
2690         unsigned int *lcolorig = ((unsigned int *)vp->vpaint_prev) + mpoly->loopstart;
2691         bool *mlooptag = (vpd->mlooptag) ? vpd->mlooptag + mpoly->loopstart : NULL;
2692         float alpha;
2693         int i, j;
2694         int totloop = mpoly->totloop;
2695
2696         int brush_alpha_pressure_i = (int)(brush_alpha_pressure * 255.0f);
2697
2698         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2699                 unsigned int blend[4] = {0};
2700                 unsigned int tcol;
2701                 char *col;
2702
2703                 for (j = 0; j < totloop; j++) {
2704                         col = (char *)(lcol + j);
2705                         blend[0] += col[0];
2706                         blend[1] += col[1];
2707                         blend[2] += col[2];
2708                         blend[3] += col[3];
2709                 }
2710
2711                 blend[0] = divide_round_i(blend[0], totloop);
2712                 blend[1] = divide_round_i(blend[1], totloop);
2713                 blend[2] = divide_round_i(blend[2], totloop);
2714                 blend[3] = divide_round_i(blend[3], totloop);
2715                 col = (char *)&tcol;
2716                 col[0] = blend[0];
2717                 col[1] = blend[1];
2718                 col[2] = blend[2];
2719                 col[3] = blend[3];
2720
2721                 vpd->paintcol = *((unsigned int *)col);
2722         }
2723
2724         ml = me->mloop + mpoly->loopstart;
2725         for (i = 0; i < totloop; i++, ml++) {
2726                 float rgba[4];
2727                 unsigned int paintcol;
2728                 alpha = calc_vp_alpha_col_dl(vp, vc, vpd->vpimat,
2729                                          &vpd->vertexcosnos[ml->v], mval,
2730                                          brush_size_pressure, brush_alpha_pressure, rgba);
2731
2732                 if (vpd->is_texbrush) {
2733                         float rgba_br[3];
2734                         rgb_uchar_to_float(rgba_br, (const unsigned char *)&vpd->paintcol);
2735                         mul_v3_v3(rgba_br, rgba);
2736                         rgb_float_to_uchar((unsigned char *)&paintcol, rgba_br);
2737                 }
2738                 else
2739                         paintcol = vpd->paintcol;
2740
2741                 if (alpha > 0.0f) {
2742                         const int alpha_i = (int)(alpha * 255.0f);
2743                         lcol[i] = vpaint_blend(vp, lcol[i], lcolorig[i], paintcol, alpha_i, brush_alpha_pressure_i);
2744
2745                         if (mlooptag) mlooptag[i] = 1;
2746                 }
2747         }
2748 }
2749
2750 static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2751 {
2752         Scene *scene = CTX_data_scene(C);
2753         ToolSettings *ts = CTX_data_tool_settings(C);
2754         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2755         VPaint *vp = ts->vpaint;
2756         Brush *brush = BKE_paint_brush(&vp->paint);
2757         ViewContext *vc = &vpd->vc;
2758         Object *ob = vc->obact;
2759         Mesh *me = ob->data;
2760         float mat[4][4];
2761         int *indexar = vpd->indexar;
2762         int totindex, index;
2763         float mval[2];
2764
2765         const float pressure = RNA_float_get(itemptr, "pressure");
2766         const float brush_size_pressure =
2767                 BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2768         const float brush_alpha_pressure =
2769                 BKE_brush_alpha_get(scene, brush) * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2770
2771         RNA_float_get_array(itemptr, "mouse", mval);
2772
2773         view3d_operator_needs_opengl(C);
2774         ED_view3d_init_mats_rv3d(ob, vc->rv3d);
2775
2776         /* load projection matrix */
2777         mul_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2778
2779         /* which faces are involved */
2780         totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2781
2782         if ((me->editflag & ME_EDIT_PAINT_FACE_SEL) && me->mpoly) {
2783                 for (index = 0; index < totindex; index++) {
2784                         if (indexar[index] && indexar[index] <= me->totpoly) {
2785                                 const MPoly *mpoly = &me->mpoly[indexar[index] - 1];
2786
2787                                 if ((mpoly->flag & ME_FACE_SEL) == 0)
2788                                         indexar[index] = 0;
2789                         }
2790                 }
2791         }
2792         
2793         swap_m4m4(vc->rv3d->persmat, mat);
2794
2795         /* incase we have modifiers */
2796         ED_vpaint_proj_handle_update(vpd->vp_handle, vc->ar, mval);
2797
2798         /* clear modified tag for blur tool */
2799         if (vpd->mlooptag)
2800                 memset(vpd->mlooptag, 0, sizeof(bool) * me->totloop);
2801
2802         for (index = 0; index < totindex; index++) {
2803                 if (indexar[index] && indexar[index] <= me->totpoly) {
2804                         vpaint_paint_poly(vp, vpd, me, indexar[index] - 1, mval, brush_size_pressure, brush_alpha_pressure);
2805                 }
2806         }
2807                 
2808         swap_m4m4(vc->rv3d->persmat, mat);
2809
2810         /* was disabled because it is slow, but necessary for blur */
2811         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2812                 do_shared_vertexcol(me, vpd->mlooptag);
2813         }
2814
2815         /* calculate pivot for rotation around seletion if needed */
2816         if (U.uiflag & USER_ORBIT_SELECTION) {
2817                 paint_last_stroke_update(scene, vc->ar, mval);
2818         }
2819
2820         ED_region_tag_redraw(vc->ar);
2821
2822         if (vpd->use_fast_update == false) {
2823                 /* recalculate modifier stack to get new colors, slow,
2824                  * avoid this if we can! */
2825                 DAG_id_tag_update(ob->data, 0);
2826         }
2827         else {
2828                 /* If using new VBO drawing, mark mcol as dirty to force colors gpu buffer refresh! */
2829                 ob->derivedFinal->dirty |= DM_DIRTY_MCOL_UPDATE_DRAW;
2830         }
2831 }
2832
2833 static void vpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2834 {
2835         ToolSettings *ts = CTX_data_tool_settings(C);
2836         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2837         ViewContext *vc = &vpd->vc;
2838         Object *ob = vc->obact;
2839         
2840         ED_vpaint_proj_handle_free(vpd->vp_handle);
2841         MEM_freeN(vpd->indexar);
2842         
2843         /* frees prev buffer */
2844         copy_vpaint_prev(ts->vpaint, NULL, 0);
2845
2846         if (vpd->mlooptag)
2847                 MEM_freeN(vpd->mlooptag);
2848
2849         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2850
2851         MEM_freeN(vpd);
2852 }
2853
2854 static int vpaint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2855 {
2856         int retval;
2857
2858         op->customdata = paint_stroke_new(C, op, NULL, vpaint_stroke_test_start,
2859                                           vpaint_stroke_update_step, NULL,
2860                                           vpaint_stroke_done, event->type);
2861         
2862         if ((retval = op->type->modal(C, op, event)) == OPERATOR_FINISHED) {
2863                 paint_stroke_data_free(op);
2864                 return OPERATOR_FINISHED;
2865         }
2866
2867         /* add modal handler */
2868         WM_event_add_modal_handler(C, op);
2869
2870         OPERATOR_RETVAL_CHECK(retval);
2871         BLI_assert(retval == OPERATOR_RUNNING_MODAL);
2872         
2873         return OPERATOR_RUNNING_MODAL;
2874 }
2875
2876 static int vpaint_exec(bContext *C, wmOperator *op)
2877 {
2878         op->customdata = paint_stroke_new(C, op, NULL, vpaint_stroke_test_start,
2879                                           vpaint_stroke_update_step, NULL,
2880                                           vpaint_stroke_done, 0);
2881
2882         /* frees op->customdata */
2883         paint_stroke_exec(C, op);
2884
2885         return OPERATOR_FINISHED;
2886 }
2887
2888 static void vpaint_cancel(bContext *C, wmOperator *op)
2889 {
2890         paint_stroke_cancel(C, op);
2891 }
2892
2893 void PAINT_OT_vertex_paint(wmOperatorType *ot)
2894 {
2895         /* identifiers */
2896         ot->name = "Vertex Paint";
2897         ot->idname = "PAINT_OT_vertex_paint";
2898         ot->description = "Paint a stroke in the active vertex color layer";
2899         
2900         /* api callbacks */
2901         ot->invoke = vpaint_invoke;
2902         ot->modal = paint_stroke_modal;
2903         ot->exec = vpaint_exec;
2904         ot->poll = vertex_paint_poll;
2905         ot->cancel = vpaint_cancel;
2906         
2907         /* flags */
2908         ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
2909
2910         paint_stroke_operator_properties(ot);
2911 }
2912
2913 /* ********************** weight from bones operator ******************* */
2914
2915 static int weight_from_bones_poll(bContext *C)
2916 {
2917         Object *ob = CTX_data_active_object(C);
2918
2919         return (ob && (ob->mode & OB_MODE_WEIGHT_PAINT) && modifiers_isDeformedByArmature(ob));
2920 }
2921
2922 static int weight_from_bones_exec(bContext *C, wmOperator *op)
2923 {
2924         Scene *scene = CTX_data_scene(C);
2925         Object *ob = CTX_data_active_object(C);
2926         Object *armob = modifiers_isDeformedByArmature(ob);
2927         Mesh *me = ob->data;
2928         int type = RNA_enum_get(op->ptr, "type");
2929
2930         create_vgroups_from_armature(op->reports, scene, ob, armob, type, (me->editflag & ME_EDIT_MIRROR_X));
2931
2932         DAG_id_tag_update(&me->id, 0);
2933         WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
2934
2935         return OPERATOR_FINISHED;
2936 }
2937
2938 void PAINT_OT_weight_from_bones(wmOperatorType *ot)
2939 {
2940         static EnumPropertyItem type_items[] = {
2941                 {ARM_GROUPS_AUTO, "AUTOMATIC", 0, "Automatic", "Automatic weights from bones"},
2942                 {ARM_GROUPS_ENVELOPE, "ENVELOPES", 0, "From Envelopes", "Weights from envelopes with user defined radius"},
2943                 {0, NULL, 0, NULL, NULL}};
2944
2945         /* identifiers */
2946         ot->name = "Weight from Bones";
2947         ot->idname = "PAINT_OT_weight_from_bones";
2948         ot->description = "Set the weights of the groups matching the attached armature's selected bones, "
2949                           "using the distance between the vertices and the bones";
2950         
2951         /* api callbacks */
2952         ot->exec = weight_from_bones_exec;
2953         ot->invoke = WM_menu_invoke;
2954         ot->poll = weight_from_bones_poll;
2955         
2956         /* flags */
2957         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2958
2959         /* properties */
2960         ot->prop = RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "Method to use for assigning weights");
2961 }
2962
2963 /* *** VGroups Gradient *** */
2964 typedef struct DMGradient_vertStore {
2965         float sco[2];
2966         float weight_orig;
2967         enum {
2968                 VGRAD_STORE_NOP      = 0,
2969                 VGRAD_STORE_DW_EXIST = (1 << 0)
2970         } flag;
2971 } DMGradient_vertStore;
2972
2973 typedef struct DMGradient_userData {
2974         struct ARegion *ar;
2975         Scene *scene;
2976         Mesh *me;
2977         Brush *brush;
2978         const float *sco_start;     /* [2] */
2979         const float *sco_end;       /* [2] */
2980         float        sco_line_div;  /* store (1.0f / len_v2v2(sco_start, sco_end)) */
2981         int def_nr;
2982         short is_init;
2983         DMGradient_vertStore *vert_cache;
2984         /* only for init */
2985         BLI_bitmap *vert_visit;
2986
2987         /* options */
2988         short use_select;
2989         short type;
2990         float weightpaint;
2991 } DMGradient_userData;
2992
2993 static void gradientVert_update(DMGradient_userData *grad_data, int index)
2994 {
2995         Mesh *me = grad_data->me;
2996         DMGradient_vertStore *vs = &grad_data->vert_cache[index];
2997         float alpha;
2998
2999         if (grad_data->type == WPAINT_GRADIENT_TYPE_LINEAR) {
3000                 alpha = line_point_factor_v2(vs->sco, grad_data->sco_start, grad_data->sco_end);
3001         }
3002         else {
3003                 BLI_assert(grad_data->type == WPAINT_GRADIENT_TYPE_RADIAL);
3004                 alpha = len_v2v2(grad_data->sco_start, vs->sco) * grad_data->sco_line_div;
3005         }
3006         /* no need to clamp 'alpha' yet */
3007
3008         /* adjust weight */
3009         alpha = BKE_brush_curve_strength_clamped(grad_data->brush, alpha, 1.0f);
3010
3011         if (alpha != 0.0f) {
3012                 MDeformVert *dv = &me->dvert[index];
3013                 MDeformWeight *dw = defvert_verify_index(dv, grad_data->def_nr);
3014                 // dw->weight = alpha; // testing
3015                 int tool = grad_data->brush->vertexpaint_tool;
3016                 float testw;
3017
3018                 /* init if we just added */
3019                 testw = wpaint_blend_tool(tool, vs->weight_orig, grad_data->weightpaint, alpha * grad_data->brush->alpha);
3020                 CLAMP(testw, 0.0f, 1.0f);
3021                 dw->weight = testw;
3022         }
3023         else {
3024                 MDeformVert *dv = &me->dvert[index];
3025                 if (vs->flag & VGRAD_STORE_DW_EXIST) {
3026                         /* normally we NULL check, but in this case we know it exists */
3027                         MDeformWeight *dw = defvert_find_index(dv, grad_data->def_nr);
3028                         dw->weight = vs->weight_orig;
3029                 }
3030                 else {
3031                         /* wasn't originally existing, remove */
3032                         MDeformWeight *dw = defvert_find_index(dv, grad_data->def_nr);
3033                         if (dw) {
3034                                 defvert_remove_group(dv, dw);
3035                         }
3036                 }
3037         }
3038 }
3039
3040 static void gradientVertUpdate__mapFunc(
3041         void *userData, int index, const float UNUSED(co[3]),
3042         const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
3043 {
3044         DMGradient_userData *grad_data = userData;
3045         Mesh *me = grad_data->me;
3046         if ((grad_data->use_select == false) || (me->mvert[index].flag & SELECT)) {
3047                 DMGradient_vertStore *vs = &grad_data->vert_cache[index];
3048                 if (vs->sco[0] != FLT_MAX) {
3049                         gradientVert_update(grad_data, index);
3050                 }
3051         }
3052 }
3053
3054 static void gradientVertInit__mapFunc(
3055         void *userData, int index, const float co[3],
3056         const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
3057 {
3058         DMGradient_userData *grad_data = userData;
3059         Mesh *me = grad_data->me;
3060
3061         if ((grad_data->use_select == false) || (me->mvert[index].flag & SELECT)) {
3062                 /* run first pass only,
3063                  * the screen coords of the verts need to be cached because
3064                  * updating the mesh may move them about (entering feedback loop) */
3065
3066                 if (BLI_BITMAP_TEST(grad_data->vert_visit, index) == 0) {
3067                         DMGradient_vertStore *vs = &grad_data->vert_cache[index];
3068                         if (ED_view3d_project_float_object(grad_data->ar,
3069                                                            co, vs->sco,
3070                                                            V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
3071                         {
3072                                 /* ok */
3073                                 MDeformVert *dv = &me->dvert[index];
3074                                 MDeformWeight *dw;
3075                                 dw = defvert_find_index(dv, grad_data->def_nr);
3076                                 if (dw) {
3077                                         vs->weight_orig = dw->weight;
3078                                         vs->flag = VGRAD_STORE_DW_EXIST;
3079                                 }
3080                                 else {
3081                                         vs->weight_orig = 0.0f;
3082                                         vs->flag = VGRAD_STORE_NOP;
3083                                 }
3084
3085                                 BLI_BITMAP_ENABLE(grad_data->vert_visit, index);
3086
3087                                 gradientVert_update(grad_data, index);
3088                         }
3089                         else {
3090                                 /* no go */
3091                                 copy_v2_fl(vs->sco, FLT_MAX);
3092                         }
3093                 }
3094         }
3095 }
3096
3097 static int paint_weight_gradient_modal(bContext *C, wmOperator *op, const wmEvent *event)
3098 {
3099         int ret = WM_gesture_straightline_modal(C, op, event);
3100
3101         if (ret & OPERATOR_RUNNING_MODAL) {
3102                 if (event->type == LEFTMOUSE && event->val == KM_RELEASE) {  /* XXX, hardcoded */
3103                         /* generally crap! redo! */
3104                         WM_gesture_straightline_cancel(C, op);
3105                         ret &= ~OPERATOR_RUNNING_MODAL;
3106                         ret |= OPERATOR_FINISHED;
3107                 }
3108         }
3109
3110         if (ret & OPERATOR_CANCELLED) {
3111                 ToolSettings *ts = CTX_data_tool_settings(C);
3112                 VPaint *wp = ts->wpaint;
3113                 Object *ob = CTX_data_active_object(C);
3114                 Mesh *me = ob->data;
3115                 if (wp->wpaint_prev) {
3116                         BKE_defvert_array_free_elems(me->dvert, me->totvert);
3117                         BKE_defvert_array_copy(me->dvert, wp->wpaint_prev, me->totvert);
3118                         free_wpaint_prev(wp);
3119                 }
3120
3121                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
3122                 WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
3123         }
3124         else if (ret & OPERATOR_FINISHED) {
3125                 ToolSettings *ts = CTX_data_tool_settings(C);
3126                 VPaint *wp = ts->wpaint;