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