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