replace most uses of ED_view3d_project_float_noclip() with ED_view3d_project_float_gl...
[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         float vertco[2];
850
851         if (ED_view3d_project_float_global(vc->ar, vert_nor, vertco, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_SUCCESS) {
852                 float delta[2];
853                 float dist_squared;
854
855                 sub_v2_v2v2(delta, mval, vertco);
856                 dist_squared = dot_v2v2(delta, delta); /* len squared */
857                 if (dist_squared <= brush_size_pressure * brush_size_pressure) {
858                         Brush *brush = paint_brush(&vp->paint);
859                         const float dist = sqrtf(dist_squared);
860                         return BKE_brush_curve_strength_clamp(brush, dist, brush_size_pressure);
861                 }
862         }
863
864         return 0.0f;
865 }
866
867 static float calc_vp_alpha_dl(VPaint *vp, ViewContext *vc,
868                               float vpimat[][3], const float *vert_nor,
869                               const float mval[2],
870                               const float brush_size_pressure, const float brush_alpha_pressure)
871 {
872         float strength = calc_vp_strength_dl(vp, vc, vert_nor, mval, brush_size_pressure);
873
874         if (strength > 0.0f) {
875                 float alpha = brush_alpha_pressure * strength;
876
877                 if (vp->flag & VP_NORMALS) {
878                         float dvec[3];
879                         const float *no = vert_nor + 3;
880
881                         /* transpose ! */
882                         dvec[2] = dot_v3v3(vpimat[2], no);
883                         if (dvec[2] > 0.0f) {
884                                 dvec[0] = dot_v3v3(vpimat[0], no);
885                                 dvec[1] = dot_v3v3(vpimat[1], no);
886
887                                 alpha *= dvec[2] / len_v3(dvec);
888                         }
889                         else {
890                                 return 0.0f;
891                         }
892                 }
893
894                 return alpha;
895         }
896
897         return 0.0f;
898 }
899
900
901 BLI_INLINE float wval_blend(const float weight, const float paintval, const float alpha)
902 {
903         return (paintval * alpha) + (weight * (1.0f - alpha));
904 }
905 BLI_INLINE float wval_add(const float weight, const float paintval, const float alpha)
906 {
907         return weight + (paintval * alpha);
908 }
909 BLI_INLINE float wval_sub(const float weight, const float paintval, const float alpha)
910 {
911         return weight - (paintval * alpha);
912 }
913 BLI_INLINE float wval_mul(const float weight, const float paintval, const float alpha)
914 {   /* first mul, then blend the fac */
915         return ((1.0f - alpha) + (alpha * paintval)) * weight;
916 }
917 BLI_INLINE float wval_lighten(const float weight, const float paintval, const float alpha)
918 {
919         return (weight < paintval) ? wval_blend(weight, paintval, alpha) : weight;
920 }
921 BLI_INLINE float wval_darken(const float weight, const float paintval, const float alpha)
922 {
923         return (weight > paintval) ? wval_blend(weight, paintval, alpha) : weight;
924 }
925
926
927 /* vpaint has 'vpaint_blend_tool' */
928 /* result is not clamped from [0-1] */
929 static float wpaint_blend_tool(const int tool,
930                                /* dw->weight */
931                                const float weight,
932                                const float paintval, const float alpha)
933 {
934         switch (tool) {
935                 case PAINT_BLEND_MIX:
936                 case PAINT_BLEND_BLUR:     return wval_blend(weight, paintval, alpha);
937                 case PAINT_BLEND_ADD:      return wval_add(weight, paintval, alpha);
938                 case PAINT_BLEND_SUB:      return wval_sub(weight, paintval, alpha);
939                 case PAINT_BLEND_MUL:      return wval_mul(weight, paintval, alpha);
940                 case PAINT_BLEND_LIGHTEN:  return wval_lighten(weight, paintval, alpha);
941                 case PAINT_BLEND_DARKEN:   return wval_darken(weight, paintval, alpha);
942                 default:
943                         BLI_assert(0);
944                         return 0.0f;
945         }
946 }
947
948 /* vpaint has 'vpaint_blend' */
949 static float wpaint_blend(VPaint *wp, float weight, float weight_prev,
950                           const float alpha, float paintval,
951                           const float brush_alpha_value,
952                           const short do_flip, const short do_multipaint_totsel)
953 {
954         Brush *brush = paint_brush(&wp->paint);
955         int tool = brush->vertexpaint_tool;
956
957         if (do_flip) {
958                 switch (tool) {
959                         case PAINT_BLEND_MIX:
960                                 paintval = 1.f - paintval; break;
961                         case PAINT_BLEND_ADD:
962                                 tool = PAINT_BLEND_SUB; break;
963                         case PAINT_BLEND_SUB:
964                                 tool = PAINT_BLEND_ADD; break;
965                         case PAINT_BLEND_LIGHTEN:
966                                 tool = PAINT_BLEND_DARKEN; break;
967                         case PAINT_BLEND_DARKEN:
968                                 tool = PAINT_BLEND_LIGHTEN; break;
969                 }
970         }
971         
972         weight = wpaint_blend_tool(tool, weight, paintval, alpha);
973
974         /* delay clamping until the end so multi-paint can function when the active group is at the limits */
975         if (do_multipaint_totsel == FALSE) {
976                 CLAMP(weight, 0.0f, 1.0f);
977         }
978         
979         /* if no spray, clip result with orig weight & orig alpha */
980         if ((wp->flag & VP_SPRAY) == 0) {
981                 if (do_multipaint_totsel == FALSE) {
982                         float testw = wpaint_blend_tool(tool, weight_prev, paintval, brush_alpha_value);
983
984                         CLAMP(testw, 0.0f, 1.0f);
985                         if (testw < weight_prev) {
986                                 if (weight < testw) weight = testw;
987                                 else if (weight > weight_prev) weight = weight_prev;
988                         }
989                         else {
990                                 if (weight > testw) weight = testw;
991                                 else if (weight < weight_prev) weight = weight_prev;
992                         }
993                 }
994         }
995
996         return weight;
997 }
998
999 /* ----------------------------------------------------- */
1000
1001
1002 /* sets wp->weight to the closest weight value to vertex */
1003 /* note: we cant sample frontbuf, weight colors are interpolated too unpredictable */
1004 static int weight_sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
1005 {
1006         ViewContext vc;
1007         Mesh *me;
1008         short change = FALSE;
1009
1010         view3d_set_viewcontext(C, &vc);
1011         me = BKE_mesh_from_object(vc.obact);
1012
1013         if (me && me->dvert && vc.v3d && vc.rv3d) {
1014                 const int use_vert_sel = (me->editflag & ME_EDIT_VERT_SEL) != 0;
1015                 int v_idx_best = -1;
1016                 unsigned int index;
1017
1018                 view3d_operator_needs_opengl(C);
1019
1020                 if (use_vert_sel) {
1021                         if (ED_mesh_pick_vert(C, me, event->mval, &index, ED_MESH_PICK_DEFAULT_VERT_SIZE)) {
1022                                 v_idx_best = index;
1023                         }
1024                 }
1025                 else {
1026                         if (ED_mesh_pick_face_vert(C, me, vc.obact, event->mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
1027                                 v_idx_best = index;
1028                         }
1029                         else if (ED_mesh_pick_face(C, me, event->mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
1030                                 /* this relies on knowning the internal worksings of ED_mesh_pick_face_vert() */
1031                                 BKE_report(op->reports, RPT_WARNING, "The modifier used does not support deformed locations");
1032                         }
1033                 }
1034
1035                 if (v_idx_best != -1) { /* should always be valid */
1036                         ToolSettings *ts = vc.scene->toolsettings;
1037                         Brush *brush = paint_brush(&ts->wpaint->paint);
1038                         const int vgroup_active = vc.obact->actdef - 1;
1039                         float vgroup_weight = defvert_find_weight(&me->dvert[v_idx_best], vgroup_active);
1040                         BKE_brush_weight_set(vc.scene, brush, vgroup_weight);
1041                         change = TRUE;
1042                 }
1043         }
1044
1045         if (change) {
1046                 /* not really correct since the brush didnt change, but redraws the toolbar */
1047                 WM_main_add_notifier(NC_BRUSH | NA_EDITED, NULL); /* ts->wpaint->paint.brush */
1048
1049                 return OPERATOR_FINISHED;
1050         }
1051         else {
1052                 return OPERATOR_CANCELLED;
1053         }
1054 }
1055
1056 void PAINT_OT_weight_sample(wmOperatorType *ot)
1057 {
1058         /* identifiers */
1059         ot->name = "Weight Paint Sample Weight";
1060         ot->idname = "PAINT_OT_weight_sample";
1061         ot->description = "Use the mouse to sample a weight in the 3D view";
1062
1063         /* api callbacks */
1064         ot->invoke = weight_sample_invoke;
1065         ot->poll = weight_paint_mode_poll;
1066
1067         /* flags */
1068         ot->flag = OPTYPE_UNDO;
1069 }
1070
1071 /* samples cursor location, and gives menu with vertex groups to activate */
1072 static int weight_paint_sample_enum_itemf__helper(const MDeformVert *dvert, const int defbase_tot, int *groups)
1073 {
1074         /* this func fills in used vgroup's */
1075         int found = FALSE;
1076         int i = dvert->totweight;
1077         MDeformWeight *dw;
1078         for (dw = dvert->dw; i > 0; dw++, i--) {
1079                 if (dw->def_nr < defbase_tot) {
1080                         groups[dw->def_nr] = TRUE;
1081                         found = TRUE;
1082                 }
1083         }
1084         return found;
1085 }
1086 static EnumPropertyItem *weight_paint_sample_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), int *free)
1087 {
1088         if (C) {
1089                 wmWindow *win = CTX_wm_window(C);
1090                 if (win && win->eventstate) {
1091                         ViewContext vc;
1092                         Mesh *me;
1093
1094                         view3d_set_viewcontext(C, &vc);
1095                         me = BKE_mesh_from_object(vc.obact);
1096
1097                         if (me && me->dvert && vc.v3d && vc.rv3d && vc.obact->defbase.first) {
1098                                 const int defbase_tot = BLI_countlist(&vc.obact->defbase);
1099                                 const int use_vert_sel = (me->editflag & ME_EDIT_VERT_SEL) != 0;
1100                                 int *groups = MEM_callocN(defbase_tot * sizeof(int), "groups");
1101                                 int found = FALSE;
1102                                 unsigned int index;
1103
1104                                 int mval[2] = {win->eventstate->x - vc.ar->winrct.xmin,
1105                                                win->eventstate->y - vc.ar->winrct.ymin};
1106
1107                                 view3d_operator_needs_opengl(C);
1108
1109                                 if (use_vert_sel) {
1110                                         if (ED_mesh_pick_vert(C, me, mval, &index, ED_MESH_PICK_DEFAULT_VERT_SIZE)) {
1111                                                 MDeformVert *dvert = &me->dvert[index];
1112                                                 found |= weight_paint_sample_enum_itemf__helper(dvert, defbase_tot, groups);
1113                                         }
1114                                 }
1115                                 else {
1116                                         if (ED_mesh_pick_face(C, me, mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
1117                                                 MPoly *mp = &me->mpoly[index];
1118                                                 unsigned int fidx = mp->totloop - 1;
1119
1120                                                 do {
1121                                                         MDeformVert *dvert = &me->dvert[me->mloop[mp->loopstart + fidx].v];
1122                                                         found |= weight_paint_sample_enum_itemf__helper(dvert, defbase_tot, groups);
1123                                                 } while (fidx--);
1124                                         }
1125                                 }
1126
1127                                 if (found == FALSE) {
1128                                         MEM_freeN(groups);
1129                                 }
1130                                 else {
1131                                         EnumPropertyItem *item = NULL, item_tmp = {0};
1132                                         int totitem = 0;
1133                                         int i = 0;
1134                                         bDeformGroup *dg;
1135                                         for (dg = vc.obact->defbase.first; dg && i < defbase_tot; i++, dg = dg->next) {
1136                                                 if (groups[i]) {
1137                                                         item_tmp.identifier = item_tmp.name = dg->name;
1138                                                         item_tmp.value = i;
1139                                                         RNA_enum_item_add(&item, &totitem, &item_tmp);
1140                                                 }
1141                                         }
1142
1143                                         RNA_enum_item_end(&item, &totitem);
1144                                         *free = 1;
1145
1146                                         MEM_freeN(groups);
1147                                         return item;
1148                                 }
1149                         }
1150                 }
1151         }
1152
1153         return DummyRNA_NULL_items;
1154 }
1155
1156 static int weight_sample_group_exec(bContext *C, wmOperator *op)
1157 {
1158         int type = RNA_enum_get(op->ptr, "group");
1159         ViewContext vc;
1160         view3d_set_viewcontext(C, &vc);
1161
1162         BLI_assert(type + 1 >= 0);
1163         vc.obact->actdef = type + 1;
1164
1165         DAG_id_tag_update(&vc.obact->id, OB_RECALC_DATA);
1166         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, vc.obact);
1167         return OPERATOR_FINISHED;
1168 }
1169
1170 /* TODO, we could make this a menu into OBJECT_OT_vertex_group_set_active rather than its own operator */
1171 void PAINT_OT_weight_sample_group(wmOperatorType *ot)
1172 {
1173         PropertyRNA *prop = NULL;
1174
1175         /* identifiers */
1176         ot->name = "Weight Paint Sample Group";
1177         ot->idname = "PAINT_OT_weight_sample_group";
1178         ot->description = "Select one of the vertex groups available under current mouse position";
1179
1180         /* api callbacks */
1181         ot->exec = weight_sample_group_exec;
1182         ot->invoke = WM_menu_invoke;
1183         ot->poll = weight_paint_mode_poll;
1184
1185         /* flags */
1186         ot->flag = OPTYPE_UNDO;
1187
1188         /* keyingset to use (dynamic enum) */
1189         prop = RNA_def_enum(ot->srna, "group", DummyRNA_DEFAULT_items, 0, "Keying Set", "The Keying Set to use");
1190         RNA_def_enum_funcs(prop, weight_paint_sample_enum_itemf);
1191         ot->prop = prop;
1192 }
1193
1194 static void do_weight_paint_normalize_all(MDeformVert *dvert, const int defbase_tot, const char *vgroup_validmap)
1195 {
1196         float sum = 0.0f, fac;
1197         unsigned int i, tot = 0;
1198         MDeformWeight *dw;
1199
1200         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1201                 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1202                         tot++;
1203                         sum += dw->weight;
1204                 }
1205         }
1206
1207         if ((tot == 0) || (sum == 1.0f)) {
1208                 return;
1209         }
1210
1211         if (sum != 0.0f) {
1212                 fac = 1.0f / sum;
1213
1214                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1215                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1216                                 dw->weight *= fac;
1217                         }
1218                 }
1219         }
1220         else {
1221                 /* hrmf, not a factor in this case */
1222                 fac = 1.0f / tot;
1223
1224                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1225                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1226                                 dw->weight = fac;
1227                         }
1228                 }
1229         }
1230 }
1231
1232 /* same as function above except it normalizes against the active vgroup which remains unchanged
1233  *
1234  * note that the active is just the group which is unchanged, it can be any,
1235  * can also be -1 to normalize all but in that case call 'do_weight_paint_normalize_all' */
1236 static void do_weight_paint_normalize_all_active(MDeformVert *dvert, const int defbase_tot, const char *vgroup_validmap,
1237                                                  const int vgroup_active)
1238 {
1239         float sum = 0.0f, fac;
1240         unsigned int i, tot = 0;
1241         MDeformWeight *dw;
1242         float act_weight = 0.0f;
1243
1244         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1245                 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1246                         if (dw->def_nr != vgroup_active) {
1247                                 sum += dw->weight;
1248                                 tot++;
1249                         }
1250                         else {
1251                                 act_weight = dw->weight;
1252                         }
1253                 }
1254         }
1255
1256         if ((tot == 0) || (sum + act_weight == 1.0f)) {
1257                 return;
1258         }
1259
1260         if (sum != 0.0f) {
1261                 fac = (1.0f / sum) * (1.0f - act_weight);
1262
1263                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1264                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1265                                 if (dw->def_nr != vgroup_active) {
1266                                         dw->weight *= fac;
1267
1268                                         /* paranoid but possibly with float error */
1269                                         CLAMP(dw->weight, 0.0f, 1.0f);
1270                                 }
1271                         }
1272                 }
1273         }
1274         else {
1275                 /* corner case where we need to scale all weights evenly because they're all zero */
1276
1277                 /* hrmf, not a factor in this case */
1278                 fac = (1.0f - act_weight) / tot;
1279
1280                 /* paranoid but possibly with float error */
1281                 CLAMP(fac, 0.0f, 1.0f);
1282
1283                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1284                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1285                                 if (dw->def_nr != vgroup_active) {
1286                                         dw->weight = fac;
1287                                 }
1288                         }
1289                 }
1290         }
1291 }
1292
1293 /*
1294  * See if the current deform vertex has a locked group
1295  */
1296 static char has_locked_group(MDeformVert *dvert, const int defbase_tot,
1297                              const char *bone_groups, const char *lock_flags)
1298 {
1299         int i;
1300         MDeformWeight *dw;
1301
1302         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1303                 if (dw->def_nr < defbase_tot) {
1304                         if (bone_groups[dw->def_nr] && lock_flags[dw->def_nr] && dw->weight > 0.0f) {
1305                                 return TRUE;
1306                         }
1307                 }
1308         }
1309         return FALSE;
1310 }
1311
1312 static int has_locked_group_selected(int defbase_tot, const char *defbase_sel, const char *lock_flags)
1313 {
1314         int i;
1315         for (i = 0; i < defbase_tot; i++) {
1316                 if (defbase_sel[i] && lock_flags[i]) {
1317                         return TRUE;
1318                 }
1319         }
1320         return FALSE;
1321 }
1322
1323
1324 #if 0 /* UNUSED */
1325 static int has_unselected_unlocked_bone_group(int defbase_tot, char *defbase_sel, int selected, char *lock_flags, char *vgroup_validmap)
1326 {
1327         int i;
1328         if (defbase_tot == selected) {
1329                 return FALSE;
1330         }
1331         for (i = 0; i < defbase_tot; i++) {
1332                 if (vgroup_validmap[i] && !defbase_sel[i] && !lock_flags[i]) {
1333                         return TRUE;
1334                 }
1335         }
1336         return FALSE;
1337 }
1338 #endif
1339
1340
1341 static void multipaint_selection(MDeformVert *dvert, const int defbase_tot, float change, const char *defbase_sel)
1342 {
1343         int i;
1344         MDeformWeight *dw;
1345         float val;
1346         /* make sure they are all at most 1 after the change */
1347         for (i = 0; i < defbase_tot; i++) {
1348                 if (defbase_sel[i]) {
1349                         dw = defvert_find_index(dvert, i);
1350                         if (dw && dw->weight) {
1351                                 val = dw->weight * change;
1352                                 if (val > 1) {
1353                                         /* TODO: when the change is reduced, you need to recheck
1354                                          * the earlier values to make sure they are not 0
1355                                          * (precision error) */
1356                                         change = 1.0f / dw->weight;
1357                                 }
1358                                 /* the value should never reach zero while multi-painting if it
1359                                  * was nonzero beforehand */
1360                                 if (val <= 0) {
1361                                         return;
1362                                 }
1363                         }
1364                 }
1365         }
1366         /* apply the valid change */
1367         for (i = 0; i < defbase_tot; i++) {
1368                 if (defbase_sel[i]) {
1369                         dw = defvert_find_index(dvert, i);
1370                         if (dw && dw->weight) {
1371                                 dw->weight = dw->weight * change;
1372                         }
1373                 }
1374         }
1375 }
1376
1377 /* move all change onto valid, unchanged groups.  If there is change left over,
1378  * then return it.
1379  * assumes there are valid groups to shift weight onto */
1380 static float redistribute_change(MDeformVert *ndv, const int defbase_tot,
1381                                  char *change_status, const char change_me, int changeto,
1382                                  float totchange, float total_valid,
1383                                  char do_auto_normalize)
1384 {
1385         float was_change;
1386         float change;
1387         float oldval;
1388         MDeformWeight *ndw;
1389         int i;
1390         do {
1391                 /* assume there is no change until you see one */
1392                 was_change = FALSE;
1393                 /* change each group by the same amount each time */
1394                 change = totchange / total_valid;
1395                 for (i = 0; i < ndv->totweight && total_valid && totchange; i++) {
1396                         ndw = (ndv->dw + i);
1397
1398                         /* ignore anything outside the value range */
1399                         if (ndw->def_nr < defbase_tot) {
1400
1401                                 /* change only the groups with a valid status */
1402                                 if (change_status[ndw->def_nr] == change_me) {
1403                                         oldval = ndw->weight;
1404                                         /* if auto normalize is active, don't worry about upper bounds */
1405                                         if (do_auto_normalize == FALSE && ndw->weight + change > 1) {
1406                                                 totchange -= 1.0f - ndw->weight;
1407                                                 ndw->weight = 1.0f;
1408                                                 /* stop the changes to this group */
1409                                                 change_status[ndw->def_nr] = changeto;
1410                                                 total_valid--;
1411                                         }
1412                                         else if (ndw->weight + change < 0) { /* check the lower bound */
1413                                                 totchange -= ndw->weight;
1414                                                 ndw->weight = 0;
1415                                                 change_status[ndw->def_nr] = changeto;
1416                                                 total_valid--;
1417                                         }
1418                                         else { /* a perfectly valid change occurred to ndw->weight */
1419                                                 totchange -= change;
1420                                                 ndw->weight += change;
1421                                         }
1422                                         /* see if there was a change */
1423                                         if (oldval != ndw->weight) {
1424                                                 was_change = TRUE;
1425                                         }
1426                                 }
1427                         }
1428                 }
1429                 /* don't go again if there was no change, if there is no valid group,
1430                  * or there is no change left */
1431         } while (was_change && total_valid && totchange);
1432         /* left overs */
1433         return totchange;
1434 }
1435 static float get_mp_change(MDeformVert *odv, const int defbase_tot, const char *defbase_sel, float brush_change);
1436 /* observe the changes made to the weights of groups.
1437  * make sure all locked groups on the vertex have the same deformation
1438  * by moving the changes made to groups onto other unlocked groups */
1439 static void enforce_locks(MDeformVert *odv, MDeformVert *ndv,
1440                           const int defbase_tot, const char *defbase_sel,
1441                           const char *lock_flags, const char *vgroup_validmap,
1442                           char do_auto_normalize, char do_multipaint)
1443 {
1444         float totchange = 0.0f;
1445         float totchange_allowed = 0.0f;
1446         float left_over;
1447
1448         int total_valid = 0;
1449         int total_changed = 0;
1450         unsigned int i;
1451         MDeformWeight *ndw;
1452         MDeformWeight *odw;
1453
1454         float changed_sum = 0.0f;
1455
1456         char *change_status;
1457
1458         if (!lock_flags || !has_locked_group(ndv, defbase_tot, vgroup_validmap, lock_flags)) {
1459                 return;
1460         }
1461         /* record if a group was changed, unlocked and not changed, or locked */
1462         change_status = MEM_callocN(sizeof(char) * defbase_tot, "unlocked_unchanged");
1463
1464         for (i = 0; i < defbase_tot; i++) {
1465                 ndw = defvert_find_index(ndv, i);
1466                 odw = defvert_find_index(odv, i);
1467                 /* the weights are zero, so we can assume a lot */
1468                 if (!ndw || !odw) {
1469                         if (!lock_flags[i] && vgroup_validmap[i]) {
1470                                 defvert_verify_index(odv, i);
1471                                 defvert_verify_index(ndv, i);
1472                                 total_valid++;
1473                                 change_status[i] = 1; /* can be altered while redistributing */
1474                         }
1475                         continue;
1476                 }
1477                 /* locked groups should not be changed */
1478                 if (lock_flags[i]) {
1479                         ndw->weight = odw->weight;
1480                 }
1481                 else if (ndw->weight != odw->weight) { /* changed groups are handled here */
1482                         totchange += ndw->weight - odw->weight;
1483                         changed_sum += ndw->weight;
1484                         change_status[i] = 2; /* was altered already */
1485                         total_changed++;
1486                 } /* unchanged, unlocked bone groups are handled here */
1487                 else if (vgroup_validmap[i]) {
1488                         totchange_allowed += ndw->weight;
1489                         total_valid++;
1490                         change_status[i] = 1; /* can be altered while redistributing */
1491                 }
1492         }
1493         /* if there was any change, redistribute it */
1494         if (total_changed) {
1495                 /* auto normalize will allow weights to temporarily go above 1 in redistribution */
1496                 if (vgroup_validmap && total_changed < 0 && total_valid) {
1497                         totchange_allowed = total_valid;
1498                 }
1499                 /* the way you modify the unlocked + unchanged groups is different depending
1500                  * on whether or not you are painting the weight(s) up or down */
1501                 if (totchange < 0) {
1502                         totchange_allowed = total_valid - totchange_allowed;
1503                 }
1504                 else {
1505                         totchange_allowed *= -1;
1506                 }
1507                 /* there needs to be change allowed, or you should not bother */
1508                 if (totchange_allowed) {
1509                         left_over = 0;
1510                         if (fabsf(totchange_allowed) < fabsf(totchange)) {
1511                                 /* this amount goes back onto the changed, unlocked weights */
1512                                 left_over = fabsf(fabsf(totchange) - fabsf(totchange_allowed));
1513                                 if (totchange > 0) {
1514                                         left_over *= -1;
1515                                 }
1516                         }
1517                         else {
1518                                 /* all of the change will be permitted */
1519                                 totchange_allowed = -totchange;
1520                         }
1521                         /* move the weight evenly between the allowed groups, move excess back onto the used groups based on the change */
1522                         totchange_allowed = redistribute_change(ndv, defbase_tot, change_status, 1, -1, totchange_allowed, total_valid, do_auto_normalize);
1523                         left_over += totchange_allowed;
1524                         if (left_over) {
1525                                 /* more than one nonzero weights were changed with the same ratio with multipaint, so keep them changed that way! */
1526                                 if (total_changed > 1 && do_multipaint) {
1527                                         float undo_change = get_mp_change(ndv, defbase_tot, defbase_sel, left_over);
1528                                         multipaint_selection(ndv, defbase_tot, undo_change, defbase_sel);
1529                                 }       
1530                                 /* or designatedw is still -1 put weight back as evenly as possible */
1531                                 else {
1532                                         redistribute_change(ndv, defbase_tot, change_status, 2, -2, left_over, total_changed, do_auto_normalize);
1533                                 }
1534                         }
1535                 }
1536                 else {
1537                         /* reset the weights */
1538                         unsigned int i;
1539                         MDeformWeight *dw_old = odv->dw;
1540                         MDeformWeight *dw_new = ndv->dw;
1541
1542                         for (i = odv->totweight; i != 0; i--, dw_old++, dw_new++) {
1543                                 dw_new->weight = dw_old->weight;
1544                         }
1545                 }
1546         }
1547
1548         MEM_freeN(change_status);
1549 }
1550
1551 /* multi-paint's initial, potential change is computed here based on the user's stroke */
1552 static float get_mp_change(MDeformVert *odv, const int defbase_tot, const char *defbase_sel, float brush_change)
1553 {
1554         float selwsum = 0.0f;
1555         unsigned int i;
1556         MDeformWeight *dw = odv->dw;
1557
1558         for (i = odv->totweight; i != 0; i--, dw++) {
1559                 if (dw->def_nr < defbase_tot) {
1560                         if (defbase_sel[dw->def_nr]) {
1561                                 selwsum += dw->weight;
1562                         }
1563                 }
1564         }
1565         if (selwsum && selwsum + brush_change > 0) {
1566                 return (selwsum + brush_change) / selwsum;
1567         }
1568         return 0.0f;
1569 }
1570
1571 /* change the weights back to the wv's weights
1572  * it assumes you already have the correct pointer index */
1573 static void defvert_reset_to_prev(MDeformVert *dv_prev, MDeformVert *dv)
1574 {
1575         MDeformWeight *dw = dv->dw;
1576         MDeformWeight *dw_prev;
1577         unsigned int i;
1578         for (i = dv->totweight; i != 0; i--, dw++) {
1579                 dw_prev = defvert_find_index(dv_prev, dw->def_nr);
1580                 /* if there was no w when there is a d, then the old weight was 0 */
1581                 dw->weight = dw_prev ? dw_prev->weight : 0.0f;
1582         }
1583 }
1584
1585 static void clamp_weights(MDeformVert *dvert)
1586 {
1587         MDeformWeight *dw = dvert->dw;
1588         unsigned int i;
1589         for (i = dvert->totweight; i != 0; i--, dw++) {
1590                 CLAMP(dw->weight, 0.0f, 1.0f);
1591         }
1592 }
1593
1594 /* struct to avoid passing many args each call to do_weight_paint_vertex()
1595  * this _could_ be made a part of the operators 'WPaintData' struct, or at
1596  * least a member, but for now keep its own struct, initialized on every
1597  * paint stroke update - campbell */
1598 typedef struct WeightPaintInfo {
1599
1600         int defbase_tot;
1601
1602         /* both must add up to 'defbase_tot' */
1603         int defbase_tot_sel;
1604         int defbase_tot_unsel;
1605
1606         int vgroup_active; /* (ob->actdef - 1) */
1607         int vgroup_mirror; /* mirror group or -1 */
1608
1609         const char *lock_flags;  /* boolean array for locked bones,
1610                                   * length of defbase_tot */
1611         const char *defbase_sel; /* boolean array for selected bones,
1612                                   * length of defbase_tot, cant be const because of how its passed */
1613
1614         const char *vgroup_validmap; /* same as WeightPaintData.vgroup_validmap,
1615                                       * only added here for convenience */
1616
1617         char do_flip;
1618         char do_multipaint;
1619         char do_auto_normalize;
1620
1621         float brush_alpha_value;  /* result of BKE_brush_alpha_get() */
1622 } WeightPaintInfo;
1623
1624 /* fresh start to make multi-paint and locking modular */
1625 /* returns TRUE if it thinks you need to reset the weights due to
1626  * normalizing while multi-painting
1627  *
1628  * note: this assumes dw->def_nr range has been checked by the caller
1629  */
1630 static int apply_mp_locks_normalize(Mesh *me, const WeightPaintInfo *wpi,
1631                                     const unsigned int index,
1632                                     MDeformWeight *dw, MDeformWeight *tdw,
1633                                     float change, float oldChange,
1634                                     float oldw, float neww)
1635 {
1636         MDeformVert *dv = &me->dvert[index];
1637         MDeformVert dv_test = {NULL};
1638
1639         dv_test.dw = MEM_dupallocN(dv->dw);
1640         dv_test.flag = dv->flag;
1641         dv_test.totweight = dv->totweight;
1642         /* do not multi-paint if a locked group is selected or the active group is locked
1643          * !lock_flags[dw->def_nr] helps if nothing is selected, but active group is locked */
1644         if ((wpi->lock_flags == NULL) ||
1645             ((wpi->lock_flags[dw->def_nr] == FALSE) && /* def_nr range has to be checked for by caller */
1646              has_locked_group_selected(wpi->defbase_tot, wpi->defbase_sel, wpi->lock_flags) == FALSE))
1647         {
1648                 if (wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1649                         if (change && change != 1) {
1650                                 multipaint_selection(dv, wpi->defbase_tot, change, wpi->defbase_sel);
1651                         }
1652                 }
1653                 else { /* this lets users paint normally, but don't let them paint locked groups */
1654                         dw->weight = neww;
1655                 }
1656         }
1657         clamp_weights(dv);
1658
1659         enforce_locks(&dv_test, dv, wpi->defbase_tot, wpi->defbase_sel, wpi->lock_flags, wpi->vgroup_validmap, wpi->do_auto_normalize, wpi->do_multipaint);
1660
1661         if (wpi->do_auto_normalize) {
1662                 /* XXX - should we pass the active group? - currently '-1' */
1663                 do_weight_paint_normalize_all(dv, wpi->defbase_tot, wpi->vgroup_validmap);
1664         }
1665
1666         if (oldChange && wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1667                 if (tdw->weight != oldw) {
1668                         if (neww > oldw) {
1669                                 if (tdw->weight <= oldw) {
1670                                         MEM_freeN(dv_test.dw);
1671                                         return TRUE;
1672                                 }
1673                         }
1674                         else {
1675                                 if (tdw->weight >= oldw) {
1676                                         MEM_freeN(dv_test.dw);
1677                                         return TRUE;
1678                                 }
1679                         }
1680                 }
1681         }
1682         MEM_freeN(dv_test.dw);
1683         return FALSE;
1684 }
1685
1686 /* within the current dvert index, get the dw that is selected and has a weight
1687  * above 0, this helps multi-paint */
1688 static int get_first_selected_nonzero_weight(MDeformVert *dvert, const int defbase_tot, const char *defbase_sel)
1689 {
1690         int i;
1691         MDeformWeight *dw = dvert->dw;
1692         for (i = 0; i < dvert->totweight; i++, dw++) {
1693                 if (dw->def_nr < defbase_tot) {
1694                         if (defbase_sel[dw->def_nr] && dw->weight > 0.0f) {
1695                                 return i;
1696                         }
1697                 }
1698         }
1699         return -1;
1700 }
1701
1702 static void do_weight_paint_vertex(
1703         /* vars which remain the same for every vert */
1704         VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
1705         /* vars which change on each stroke */
1706         const unsigned int index, float alpha, float paintweight
1707         )
1708 {
1709         Mesh *me = ob->data;
1710         MDeformVert *dv = &me->dvert[index];
1711         
1712         MDeformWeight *dw, *dw_prev;
1713
1714         /* mirror vars */
1715         int index_mirr;
1716         int vgroup_mirr;
1717
1718         MDeformVert *dv_mirr;
1719         MDeformWeight *dw_mirr;
1720
1721         const short do_multipaint_totsel = (wpi->do_multipaint && wpi->defbase_tot_sel > 1);
1722
1723         if (wp->flag & VP_ONLYVGROUP) {
1724                 dw = defvert_find_index(dv, wpi->vgroup_active);
1725                 dw_prev = defvert_find_index(wp->wpaint_prev + index, wpi->vgroup_active);
1726         }
1727         else {
1728                 dw = defvert_verify_index(dv, wpi->vgroup_active);
1729                 dw_prev = defvert_verify_index(wp->wpaint_prev + index, wpi->vgroup_active);
1730         }
1731
1732         if (dw == NULL || dw_prev == NULL) {
1733                 return;
1734         }
1735
1736
1737         /* from now on we can check if mirrors enabled if this var is -1 and not bother with the flag */
1738         if (me->editflag & ME_EDIT_MIRROR_X) {
1739                 index_mirr = mesh_get_x_mirror_vert(ob, index);
1740                 vgroup_mirr = (wpi->vgroup_mirror != -1) ? wpi->vgroup_mirror : wpi->vgroup_active;
1741
1742                 /* another possible error - mirror group _and_ active group are the same (which is fine),
1743                  * but we also are painting onto a center vertex - this would paint the same weight twice */
1744                 if (index_mirr == index && vgroup_mirr == wpi->vgroup_active) {
1745                         index_mirr = vgroup_mirr = -1;
1746                 }
1747         }
1748         else {
1749                 index_mirr = vgroup_mirr = -1;
1750         }
1751
1752
1753         /* get the mirror def vars */
1754         if (index_mirr != -1) {
1755                 dv_mirr = &me->dvert[index_mirr];
1756                 if (wp->flag & VP_ONLYVGROUP) {
1757                         dw_mirr = defvert_find_index(dv_mirr, vgroup_mirr);
1758
1759                         if (dw_mirr == NULL) {
1760                                 index_mirr = vgroup_mirr = -1;
1761                                 dv_mirr = NULL;
1762                         }
1763                 }
1764                 else {
1765                         if (index != index_mirr) {
1766                                 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
1767                         }
1768                         else {
1769                                 /* dv and dv_mirr are the same */
1770                                 int totweight_prev = dv_mirr->totweight;
1771                                 int dw_offset = (int)(dw - dv_mirr->dw);
1772                                 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
1773
1774                                 /* if we added another, get our old one back */
1775                                 if (totweight_prev != dv_mirr->totweight) {
1776                                         dw = &dv_mirr->dw[dw_offset];
1777                                 }
1778                         }
1779                 }
1780         }
1781         else {
1782                 dv_mirr = NULL;
1783                 dw_mirr = NULL;
1784         }
1785
1786
1787         /* TODO: De-duplicate the simple weight paint - jason */
1788         /* ... or not, since its <10 SLOC - campbell */
1789
1790         /* If there are no locks or multipaint,
1791          * then there is no need to run the more complicated checks */
1792         if ((do_multipaint_totsel == FALSE) &&
1793             (wpi->lock_flags == NULL || has_locked_group(dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags) == FALSE))
1794         {
1795                 dw->weight = wpaint_blend(wp, dw->weight, dw_prev->weight, alpha, paintweight,
1796                                           wpi->brush_alpha_value, wpi->do_flip, FALSE);
1797
1798                 /* WATCH IT: take care of the ordering of applying mirror -> normalize,
1799                  * can give wrong results [#26193], least confusing if normalize is done last */
1800
1801                 /* apply mirror */
1802                 if (index_mirr != -1) {
1803                         /* copy, not paint again */
1804                         dw_mirr->weight = dw->weight;
1805                 }
1806
1807                 /* apply normalize */
1808                 if (wpi->do_auto_normalize) {
1809                         /* note on normalize - this used to be applied after painting and normalize all weights,
1810                          * in some ways this is good because there is feedback where the more weights involved would
1811                          * 'resist' so you couldn't instantly zero out other weights by painting 1.0 on the active.
1812                          *
1813                          * However this gave a problem since applying mirror, then normalize both verts
1814                          * the resulting weight wont match on both sides.
1815                          *
1816                          * If this 'resisting', slower normalize is nicer, we could call
1817                          * do_weight_paint_normalize_all() and only use...
1818                          * do_weight_paint_normalize_all_active() when normalizing the mirror vertex.
1819                          * - campbell
1820                          */
1821                         do_weight_paint_normalize_all_active(dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->vgroup_active);
1822
1823                         if (index_mirr != -1) {
1824                                 /* only normalize if this is not a center vertex, else we get a conflict, normalizing twice */
1825                                 if (index != index_mirr) {
1826                                         do_weight_paint_normalize_all_active(dv_mirr, wpi->defbase_tot, wpi->vgroup_validmap, vgroup_mirr);
1827                                 }
1828                                 else {
1829                                         /* this case accounts for...
1830                                          * - painting onto a center vertex of a mesh
1831                                          * - x mirror is enabled
1832                                          * - auto normalize is enabled
1833                                          * - the group you are painting onto has a L / R version
1834                                          *
1835                                          * We want L/R vgroups to have the same weight but this cant be if both are over 0.5,
1836                                          * We _could_ have special check for that, but this would need its own normalize function which
1837                                          * holds 2 groups from changing at once.
1838                                          *
1839                                          * So! just balance out the 2 weights, it keeps them equal and everything normalized.
1840                                          *
1841                                          * While it wont hit the desired weight immediately as the user waggles their mouse,
1842                                          * constant painting and re-normalizing will get there. this is also just simpler logic.
1843                                          * - campbell */
1844                                         dw_mirr->weight = dw->weight = (dw_mirr->weight + dw->weight) * 0.5f;
1845                                 }
1846                         }
1847                 }
1848         }
1849         else {
1850                 /* use locks and/or multipaint */
1851                 float oldw;
1852                 float neww;
1853                 /* float testw = 0; */ /* UNUSED */
1854                 float observedChange = 0;
1855                 float change = 0;
1856                 float oldChange = 0;
1857                 int i;
1858                 MDeformWeight *tdw = NULL, *tdw_prev;
1859                 MDeformVert dv_copy = {NULL};
1860
1861                 oldw = dw->weight;
1862                 neww = wpaint_blend(wp, dw->weight, dw_prev->weight, alpha, paintweight,
1863                                     wpi->brush_alpha_value, wpi->do_flip, do_multipaint_totsel);
1864                 
1865                 /* setup multi-paint */
1866                 observedChange = neww - oldw;
1867                 if (do_multipaint_totsel && observedChange) {
1868                         dv_copy.dw = MEM_dupallocN(dv->dw);
1869                         dv_copy.flag = dv->flag;
1870                         dv_copy.totweight = dv->totweight;
1871                         tdw = dw;
1872                         tdw_prev = dw_prev;
1873                         change = get_mp_change(&wp->wpaint_prev[index], wpi->defbase_tot, wpi->defbase_sel, observedChange);
1874                         if (change) {
1875                                 if (!tdw->weight) {
1876                                         i = get_first_selected_nonzero_weight(dv, wpi->defbase_tot, wpi->defbase_sel);
1877                                         if (i >= 0) {
1878                                                 tdw = &(dv->dw[i]);
1879                                                 tdw_prev = defvert_verify_index(&wp->wpaint_prev[index], tdw->def_nr);
1880                                         }
1881                                         else {
1882                                                 change = 0;
1883                                         }
1884                                 }
1885                                 if (change && tdw_prev->weight && tdw_prev->weight * change) {
1886                                         if (tdw->weight != tdw_prev->weight) {
1887                                                 oldChange = tdw->weight / tdw_prev->weight;
1888                                                 /* testw = tdw_prev->weight * change; */ /* UNUSED */
1889                                                 if (observedChange > 0) {
1890                                                         if (change > oldChange) {
1891                                                                 /* reset the weights and use the new change */
1892                                                                 defvert_reset_to_prev(wp->wpaint_prev + index, dv);
1893                                                         }
1894                                                         else {
1895                                                                 /* the old change was more significant, so set
1896                                                                  * the change to 0 so that it will not do another multi-paint */
1897                                                                 change = 0;
1898                                                         }
1899                                                 }
1900                                                 else {
1901                                                         if (change < oldChange) {
1902                                                                 defvert_reset_to_prev(wp->wpaint_prev + index, dv);
1903                                                         }
1904                                                         else {
1905                                                                 change = 0;
1906                                                         }
1907                                                 }
1908                                         }
1909                                 }
1910                                 else {
1911                                         change = 0;
1912                                 }
1913                         }
1914                 }
1915                 
1916                 if (apply_mp_locks_normalize(me, wpi, index, dw, tdw, change, oldChange, oldw, neww)) {
1917                         defvert_reset_to_prev(&dv_copy, dv);
1918                         change = 0;
1919                         oldChange = 0;
1920                 }
1921                 if (dv_copy.dw) {
1922                         MEM_freeN(dv_copy.dw);
1923                 }
1924 #if 0
1925                 /* dv may have been altered greatly */
1926                 dw = defvert_find_index(dv, vgroup);
1927 #else
1928                 dw = NULL; /* UNUSED after assignment, set to NULL to ensure we don't
1929                             * use again, we thats needed un-ifdef the line above */
1930                 (void)dw;  /* quiet warnigns */
1931 #endif
1932
1933                 /* x mirror painting */
1934                 if (index_mirr != -1) {
1935                         /* copy, not paint again */
1936
1937                         /* dw_mirr->weight = dw->weight; */  /* TODO, explain the logic in not assigning weight! - campbell */
1938                         apply_mp_locks_normalize(me, wpi, index_mirr, dw_mirr, tdw, change, oldChange, oldw, neww);
1939                 }
1940         }
1941 }
1942
1943
1944 /* *************** set wpaint operator ****************** */
1945
1946 static int set_wpaint(bContext *C, wmOperator *UNUSED(op))  /* toggle */
1947 {               
1948         Object *ob = CTX_data_active_object(C);
1949         Scene *scene = CTX_data_scene(C);
1950         VPaint *wp = scene->toolsettings->wpaint;
1951         Mesh *me;
1952         
1953         me = BKE_mesh_from_object(ob);
1954         if (ob->id.lib || me == NULL) return OPERATOR_PASS_THROUGH;
1955         
1956         if (ob->mode & OB_MODE_WEIGHT_PAINT) ob->mode &= ~OB_MODE_WEIGHT_PAINT;
1957         else ob->mode |= OB_MODE_WEIGHT_PAINT;
1958         
1959         
1960         /* Weightpaint works by overriding colors in mesh,
1961          * so need to make sure we recalc on enter and
1962          * exit (exit needs doing regardless because we
1963          * should redeform).
1964          */
1965         DAG_id_tag_update(&me->id, 0);
1966         
1967         if (ob->mode & OB_MODE_WEIGHT_PAINT) {
1968                 Object *par;
1969                 
1970                 if (wp == NULL)
1971                         wp = scene->toolsettings->wpaint = new_vpaint(1);
1972
1973                 BKE_paint_init(&wp->paint, PAINT_CURSOR_WEIGHT_PAINT);
1974                 paint_cursor_start(C, weight_paint_poll);
1975                 
1976                 mesh_octree_table(ob, NULL, NULL, 's');
1977                 
1978                 /* verify if active weight group is also active bone */
1979                 par = modifiers_isDeformedByArmature(ob);
1980                 if (par && (par->mode & OB_MODE_POSE)) {
1981                         bArmature *arm = par->data;
1982
1983                         if (arm->act_bone)
1984                                 ED_vgroup_select_by_name(ob, arm->act_bone->name);
1985                 }
1986         }
1987         else {
1988                 mesh_octree_table(NULL, NULL, NULL, 'e');
1989                 mesh_mirrtopo_table(NULL, 'e');
1990         }
1991         
1992         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
1993         
1994         return OPERATOR_FINISHED;
1995 }
1996
1997 /* for switching to/from mode */
1998 static int paint_poll_test(bContext *C)
1999 {
2000         Object *ob = CTX_data_active_object(C);
2001         if (CTX_data_edit_object(C))
2002                 return 0;
2003         if (CTX_data_active_object(C) == NULL)
2004                 return 0;
2005         if (!ob->data || ((ID *)ob->data)->lib)
2006                 return 0;
2007         return 1;
2008 }
2009
2010 void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
2011 {
2012         
2013         /* identifiers */
2014         ot->name = "Weight Paint Mode";
2015         ot->idname = "PAINT_OT_weight_paint_toggle";
2016         ot->description = "Toggle weight paint mode in 3D view";
2017         
2018         /* api callbacks */
2019         ot->exec = set_wpaint;
2020         ot->poll = paint_poll_test;
2021         
2022         /* flags */
2023         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2024         
2025 }
2026
2027 /* ************ weight paint operator ********** */
2028
2029 struct WPaintData {
2030         ViewContext vc;
2031         int *indexar;
2032         int vgroup_active;
2033         int vgroup_mirror;
2034         float *vertexcosnos;
2035         float wpimat[3][3];
2036         
2037         /* variables for auto normalize */
2038         const char *vgroup_validmap; /* stores if vgroups tie to deforming bones or not */
2039         const char *lock_flags;
2040         int defbase_tot;
2041 };
2042
2043 static int wpaint_stroke_test_start(bContext *C, wmOperator *op, const float UNUSED(mouse[2]))
2044 {
2045         Scene *scene = CTX_data_scene(C);
2046         struct PaintStroke *stroke = op->customdata;
2047         ToolSettings *ts = scene->toolsettings;
2048         VPaint *wp = ts->wpaint;
2049         Object *ob = CTX_data_active_object(C);
2050         struct WPaintData *wpd;
2051         Mesh *me;
2052         bDeformGroup *dg;
2053
2054         float mat[4][4], imat[4][4];
2055         
2056         if (scene->obedit) {
2057                 return FALSE;
2058         }
2059         
2060         me = BKE_mesh_from_object(ob);
2061         if (me == NULL || me->totpoly == 0) return OPERATOR_PASS_THROUGH;
2062         
2063         /* if nothing was added yet, we make dverts and a vertex deform group */
2064         if (!me->dvert) {
2065                 ED_vgroup_data_create(&me->id);
2066                 WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
2067         }
2068
2069         /* this happens on a Bone select, when no vgroup existed yet */
2070         if (ob->actdef <= 0) {
2071                 Object *modob;
2072                 if ((modob = modifiers_isDeformedByArmature(ob))) {
2073                         Bone *actbone = ((bArmature *)modob->data)->act_bone;
2074                         if (actbone) {
2075                                 bPoseChannel *pchan = BKE_pose_channel_find_name(modob->pose, actbone->name);
2076
2077                                 if (pchan) {
2078                                         bDeformGroup *dg = defgroup_find_name(ob, pchan->name);
2079                                         if (dg == NULL) {
2080                                                 dg = ED_vgroup_add_name(ob, pchan->name);  /* sets actdef */
2081                                         }
2082                                         else {
2083                                                 int actdef = 1 + BLI_findindex(&ob->defbase, dg);
2084                                                 BLI_assert(actdef >= 0);
2085                                                 ob->actdef = actdef;
2086                                         }
2087                                 }
2088                         }
2089                 }
2090         }
2091         if (ob->defbase.first == NULL) {
2092                 ED_vgroup_add(ob);
2093         }
2094
2095         /* ensure we don't try paint onto an invalid group */
2096         if (ob->actdef <= 0) {
2097                 BKE_report(op->reports, RPT_WARNING, "No active vertex group for painting, aborting");
2098                 return FALSE;
2099         }
2100
2101         /* check if we are attempting to paint onto a locked vertex group,
2102          * and other options disallow it from doing anything useful */
2103         dg = BLI_findlink(&ob->defbase, (ob->actdef - 1));
2104         if (dg->flag & DG_LOCK_WEIGHT) {
2105                 BKE_report(op->reports, RPT_WARNING, "Active group is locked, aborting");
2106                 return FALSE;
2107         }
2108
2109         /* ALLOCATIONS! no return after this line */
2110         /* make mode data storage */
2111         wpd = MEM_callocN(sizeof(struct WPaintData), "WPaintData");
2112         paint_stroke_set_mode_data(stroke, wpd);
2113         view3d_set_viewcontext(C, &wpd->vc);
2114
2115         wpd->vgroup_active = ob->actdef - 1;
2116         wpd->vgroup_mirror = -1;
2117
2118         /* set up auto-normalize, and generate map for detecting which
2119          * vgroups affect deform bones */
2120         wpd->defbase_tot = BLI_countlist(&ob->defbase);
2121         wpd->lock_flags = BKE_objdef_lock_flags_get(ob, wpd->defbase_tot);
2122         if (ts->auto_normalize || ts->multipaint || wpd->lock_flags) {
2123                 wpd->vgroup_validmap = BKE_objdef_validmap_get(ob, wpd->defbase_tot);
2124         }
2125
2126         /* painting on subsurfs should give correct points too, this returns me->totvert amount */
2127         wpd->vertexcosnos = mesh_get_mapped_verts_nors(scene, ob);
2128         wpd->indexar = get_indexarray(me);
2129         copy_wpaint_prev(wp, me->dvert, me->totvert);
2130
2131         /* imat for normals */
2132         mult_m4_m4m4(mat, wpd->vc.rv3d->viewmat, ob->obmat);
2133         invert_m4_m4(imat, mat);
2134         copy_m3_m4(wpd->wpimat, imat);
2135
2136         /* if mirror painting, find the other group */
2137         if (me->editflag & ME_EDIT_MIRROR_X) {
2138                 wpd->vgroup_mirror = wpaint_mirror_vgroup_ensure(ob, wpd->vgroup_active);
2139         }
2140         
2141         return TRUE;
2142 }
2143
2144 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2145 {
2146         Scene *scene = CTX_data_scene(C);
2147         ToolSettings *ts = CTX_data_tool_settings(C);
2148         VPaint *wp = ts->wpaint;
2149         Brush *brush = paint_brush(&wp->paint);
2150         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2151         ViewContext *vc;
2152         Object *ob;
2153         Mesh *me;
2154         float mat[4][4];
2155         float paintweight;
2156         int *indexar;
2157         float totw;
2158         unsigned int index, totindex;
2159         float alpha;
2160         float mval[2];
2161         int use_vert_sel;
2162
2163         const float pressure = RNA_float_get(itemptr, "pressure");
2164         const float brush_size_pressure = BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2165         const float brush_alpha_value = BKE_brush_alpha_get(scene, brush);
2166         const float brush_alpha_pressure = brush_alpha_value * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2167
2168         /* intentionally don't initialize as NULL, make sure we initialize all members below */
2169         WeightPaintInfo wpi;
2170
2171         /* cannot paint if there is no stroke data */
2172         if (wpd == NULL) {
2173                 /* XXX: force a redraw here, since even though we can't paint,
2174                  * at least view won't freeze until stroke ends */
2175                 ED_region_tag_redraw(CTX_wm_region(C));
2176                 return;
2177         }
2178                 
2179         vc = &wpd->vc;
2180         ob = vc->obact;
2181         me = ob->data;
2182         indexar = wpd->indexar;
2183         
2184         view3d_operator_needs_opengl(C);
2185                 
2186         /* load projection matrix */
2187         mult_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2188
2189         RNA_float_get_array(itemptr, "mouse", mval);
2190         mval[0] -= vc->ar->winrct.xmin;
2191         mval[1] -= vc->ar->winrct.ymin;
2192
2193
2194
2195
2196         /* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
2197         wpi.defbase_tot =        wpd->defbase_tot;
2198         wpi.defbase_sel = BKE_objdef_selected_get(ob, wpi.defbase_tot, &wpi.defbase_tot_sel);
2199         if (wpi.defbase_tot_sel == 0 && ob->actdef > 0) {
2200                 wpi.defbase_tot_sel = 1;
2201         }
2202
2203         wpi.defbase_tot_unsel =  wpi.defbase_tot - wpi.defbase_tot_sel;
2204         wpi.vgroup_active =      wpd->vgroup_active;
2205         wpi.vgroup_mirror =      wpd->vgroup_mirror;
2206         wpi.lock_flags =         wpd->lock_flags;
2207         wpi.vgroup_validmap =    wpd->vgroup_validmap;
2208         wpi.do_flip =            RNA_boolean_get(itemptr, "pen_flip");
2209         wpi.do_multipaint =      (ts->multipaint != 0);
2210         wpi.do_auto_normalize =  ((ts->auto_normalize != 0) && (wpi.vgroup_validmap != NULL));
2211         wpi.brush_alpha_value =  brush_alpha_value;
2212         /* *** done setting up WeightPaintInfo *** */
2213
2214
2215
2216         swap_m4m4(wpd->vc.rv3d->persmat, mat);
2217
2218         use_vert_sel = (me->editflag & ME_EDIT_VERT_SEL) != 0;
2219
2220         /* which faces are involved */
2221         if (wp->flag & VP_AREA) {
2222                 /* Ugly hack, to avoid drawing vertex index when getting the face index buffer - campbell */
2223                 me->editflag &= ~ME_EDIT_VERT_SEL;
2224                 totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2225                 me->editflag |= use_vert_sel ? ME_EDIT_VERT_SEL : 0;
2226         }
2227         else {
2228                 indexar[0] = view3d_sample_backbuf(vc, mval[0], mval[1]);
2229                 if (indexar[0]) totindex = 1;
2230                 else totindex = 0;
2231         }
2232
2233         if ((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
2234                 for (index = 0; index < totindex; index++) {
2235                         if (indexar[index] && indexar[index] <= me->totpoly) {
2236                                 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2237                                                 
2238                                 if ((mpoly->flag & ME_FACE_SEL) == 0) {
2239                                         indexar[index] = 0;
2240                                 }
2241                         }
2242                 }
2243         }
2244
2245         /* make sure each vertex gets treated only once */
2246         /* and calculate filter weight */
2247         totw = 0.0f;
2248         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR)
2249                 paintweight = 0.0f;
2250         else
2251                 paintweight = BKE_brush_weight_get(scene, brush);
2252                         
2253         for (index = 0; index < totindex; index++) {
2254                 if (indexar[index] && indexar[index] <= me->totpoly) {
2255                         MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2256                         MLoop *ml = me->mloop + mpoly->loopstart;
2257                         int i;
2258
2259                         if (use_vert_sel) {
2260                                 for (i = 0; i < mpoly->totloop; i++, ml++) {
2261                                         me->dvert[ml->v].flag = (me->mvert[ml->v].flag & SELECT);
2262                                 }
2263                         }
2264                         else {
2265                                 for (i = 0; i < mpoly->totloop; i++, ml++) {
2266                                         me->dvert[ml->v].flag = 1;
2267                                 }
2268                         }
2269                                         
2270                         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2271                                 MDeformWeight *dw, *(*dw_func)(MDeformVert *, const int);
2272                                                 
2273                                 if (wp->flag & VP_ONLYVGROUP)
2274                                         dw_func = (MDeformWeight *(*)(MDeformVert *, const int))defvert_find_index;
2275                                 else
2276                                         dw_func = defvert_verify_index;
2277                                                 
2278                                 ml = me->mloop + mpoly->loopstart;
2279                                 for (i = 0; i < mpoly->totloop; i++, ml++) {
2280                                         unsigned int vidx = ml->v;
2281                                         const float fac = calc_vp_strength_dl(wp, vc, wpd->vertexcosnos + 6 * vidx, mval, brush_size_pressure);
2282                                         if (fac > 0.0f) {
2283                                                 dw = dw_func(&me->dvert[vidx], wpi.vgroup_active);
2284                                                 paintweight += dw ? (dw->weight * fac) : 0.0f;
2285                                                 totw += fac;
2286                                         }
2287                                 }
2288                         }
2289                 }
2290         }
2291                         
2292         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2293                 paintweight /= totw;
2294         }
2295
2296         for (index = 0; index < totindex; index++) {
2297
2298                 if (indexar[index] && indexar[index] <= me->totpoly) {
2299                         MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2300                         MLoop *ml = me->mloop + mpoly->loopstart;
2301                         int i;
2302
2303                         for (i = 0; i < mpoly->totloop; i++, ml++) {
2304                                 unsigned int vidx = ml->v;
2305
2306                                 if (me->dvert[vidx].flag) {
2307                                         alpha = calc_vp_alpha_dl(wp, vc, wpd->wpimat, wpd->vertexcosnos + 6 * vidx,
2308                                                                  mval, brush_size_pressure, brush_alpha_pressure);
2309                                         if (alpha) {
2310                                                 do_weight_paint_vertex(wp, ob, &wpi, vidx, alpha, paintweight);
2311                                         }
2312                                         me->dvert[vidx].flag = 0;
2313                                 }
2314                         }
2315                 }
2316         }
2317
2318
2319         /* *** free wpi members */
2320         MEM_freeN((void *)wpi.defbase_sel);
2321         /* *** don't freeing wpi members */
2322
2323
2324         swap_m4m4(vc->rv3d->persmat, mat);
2325                         
2326         DAG_id_tag_update(ob->data, 0);
2327         ED_region_tag_redraw(vc->ar);
2328 }
2329
2330 static void wpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2331 {
2332         ToolSettings *ts = CTX_data_tool_settings(C);
2333         Object *ob = CTX_data_active_object(C);
2334         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2335         
2336         if (wpd) {
2337                 if (wpd->vertexcosnos)
2338                         MEM_freeN(wpd->vertexcosnos);
2339                 MEM_freeN(wpd->indexar);
2340                 
2341                 if (wpd->vgroup_validmap)
2342                         MEM_freeN((void *)wpd->vgroup_validmap);
2343                 if (wpd->lock_flags)
2344                         MEM_freeN((void *)wpd->lock_flags);
2345
2346                 MEM_freeN(wpd);
2347         }
2348         
2349         /* frees prev buffer */
2350         copy_wpaint_prev(ts->wpaint, NULL, 0);
2351         
2352         /* and particles too */
2353         if (ob->particlesystem.first) {
2354                 ParticleSystem *psys;
2355                 int i;
2356                 
2357                 for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2358                         for (i = 0; i < PSYS_TOT_VG; i++) {
2359                                 if (psys->vgroup[i] == ob->actdef) {
2360                                         psys->recalc |= PSYS_RECALC_RESET;
2361                                         break;
2362                                 }
2363                         }
2364                 }
2365         }
2366         
2367         DAG_id_tag_update(ob->data, 0);
2368
2369         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2370 }
2371
2372
2373 static int wpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2374 {
2375         
2376         op->customdata = paint_stroke_new(C, NULL, wpaint_stroke_test_start,
2377                                           wpaint_stroke_update_step,
2378                                           wpaint_stroke_done, event->type);
2379         
2380         /* add modal handler */
2381         WM_event_add_modal_handler(C, op);
2382
2383         op->type->modal(C, op, event);
2384         
2385         return OPERATOR_RUNNING_MODAL;
2386 }
2387
2388 static int wpaint_cancel(bContext *C, wmOperator *op)
2389 {
2390         paint_stroke_cancel(C, op);
2391
2392         return OPERATOR_CANCELLED;
2393 }
2394
2395 void PAINT_OT_weight_paint(wmOperatorType *ot)
2396 {
2397         
2398         /* identifiers */
2399         ot->name = "Weight Paint";
2400         ot->idname = "PAINT_OT_weight_paint";
2401         ot->description = "Paint a stroke in the current vertex group's weights";
2402         
2403         /* api callbacks */
2404         ot->invoke = wpaint_invoke;
2405         ot->modal = paint_stroke_modal;
2406         /* ot->exec = vpaint_exec; <-- needs stroke property */
2407         ot->poll = weight_paint_poll;
2408         ot->cancel = wpaint_cancel;
2409         
2410         /* flags */
2411         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
2412
2413         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2414 }
2415
2416 static int weight_paint_set_exec(bContext *C, wmOperator *UNUSED(op))
2417 {
2418         struct Scene *scene = CTX_data_scene(C);
2419         Object *obact = CTX_data_active_object(C);
2420         ToolSettings *ts = CTX_data_tool_settings(C);
2421         Brush *brush = paint_brush(&ts->wpaint->paint);
2422         float vgroup_weight = BKE_brush_weight_get(scene, brush);
2423
2424         wpaint_fill(scene->toolsettings->wpaint, obact, vgroup_weight);
2425         ED_region_tag_redraw(CTX_wm_region(C)); /* XXX - should redraw all 3D views */
2426         return OPERATOR_FINISHED;
2427 }
2428
2429 void PAINT_OT_weight_set(wmOperatorType *ot)
2430 {
2431         /* identifiers */
2432         ot->name = "Set Weight";
2433         ot->idname = "PAINT_OT_weight_set";
2434         ot->description = "Fill the active vertex group with the current paint weight";
2435
2436         /* api callbacks */
2437         ot->exec = weight_paint_set_exec;
2438         ot->poll = mask_paint_poll; /* it was facemask_paint_poll */
2439
2440         /* flags */
2441         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2442 }
2443
2444 /* ************ set / clear vertex paint mode ********** */
2445
2446
2447 static int set_vpaint(bContext *C, wmOperator *op)  /* toggle */
2448 {       
2449         Object *ob = CTX_data_active_object(C);
2450         Scene *scene = CTX_data_scene(C);
2451         VPaint *vp = scene->toolsettings->vpaint;
2452         Mesh *me;
2453         
2454         me = BKE_mesh_from_object(ob);
2455         
2456         if (me == NULL || BKE_object_obdata_is_libdata(ob)) {
2457                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2458                 return OPERATOR_PASS_THROUGH;
2459         }
2460         
2461         if (me && me->mloopcol == NULL) {
2462                 make_vertexcol(ob);
2463         }
2464         
2465         /* toggle: end vpaint */
2466         if (ob->mode & OB_MODE_VERTEX_PAINT) {
2467                 
2468                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2469         }
2470         else {
2471                 ob->mode |= OB_MODE_VERTEX_PAINT;
2472                 /* Turn off weight painting */
2473                 if (ob->mode & OB_MODE_WEIGHT_PAINT)
2474                         set_wpaint(C, op);
2475                 
2476                 if (vp == NULL)
2477                         vp = scene->toolsettings->vpaint = new_vpaint(0);
2478                 
2479                 paint_cursor_start(C, vertex_paint_poll);
2480
2481                 BKE_paint_init(&vp->paint, PAINT_CURSOR_VERTEX_PAINT);
2482         }
2483         
2484         if (me)
2485                 /* update modifier stack for mapping requirements */
2486                 DAG_id_tag_update(&me->id, 0);
2487         
2488         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
2489         
2490         return OPERATOR_FINISHED;
2491 }
2492
2493 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2494 {
2495         
2496         /* identifiers */
2497         ot->name = "Vertex Paint Mode";
2498         ot->idname = "PAINT_OT_vertex_paint_toggle";
2499         ot->description = "Toggle the vertex paint mode in 3D view";
2500         
2501         /* api callbacks */
2502         ot->exec = set_vpaint;
2503         ot->poll = paint_poll_test;
2504         
2505         /* flags */
2506         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2507 }
2508
2509
2510
2511 /* ********************** vertex paint operator ******************* */
2512
2513 /* Implementation notes:
2514  *
2515  * Operator->invoke()
2516  * - validate context (add mcol)
2517  * - create customdata storage
2518  * - call paint once (mouse click)
2519  * - add modal handler 
2520  *
2521  * Operator->modal()
2522  * - for every mousemove, apply vertex paint
2523  * - exit on mouse release, free customdata
2524  *   (return OPERATOR_FINISHED also removes handler and operator)
2525  *
2526  * For future:
2527  * - implement a stroke event (or mousemove with past positons)
2528  * - revise whether op->customdata should be added in object, in set_vpaint
2529  */
2530
2531 typedef struct PolyFaceMap {
2532         struct PolyFaceMap *next, *prev;
2533         int facenr;
2534 } PolyFaceMap;
2535
2536 typedef struct VPaintData {
2537         ViewContext vc;
2538         unsigned int paintcol;
2539         int *indexar;
2540         float *vertexcosnos;
2541         float vpimat[3][3];
2542
2543         /* modify 'me->mcol' directly, since the derived mesh is drawing from this array,
2544          * otherwise we need to refresh the modifier stack */
2545         int use_fast_update;
2546
2547         /* mpoly -> mface mapping */
2548         MemArena *polyfacemap_arena;
2549         ListBase *polyfacemap;
2550 } VPaintData;
2551
2552 static void vpaint_build_poly_facemap(struct VPaintData *vd, Mesh *me)
2553 {
2554         MFace *mf;
2555         PolyFaceMap *e;
2556         int *origIndex;
2557         int i;
2558
2559         vd->polyfacemap_arena = BLI_memarena_new(1 << 13, "vpaint tmp");
2560         BLI_memarena_use_calloc(vd->polyfacemap_arena);
2561
2562         vd->polyfacemap = BLI_memarena_alloc(vd->polyfacemap_arena, sizeof(ListBase) * me->totpoly);
2563
2564         origIndex = CustomData_get_layer(&me->fdata, CD_POLYINDEX);
2565         mf = me->mface;
2566
2567         if (!origIndex)
2568                 return;
2569
2570         for (i = 0; i < me->totface; i++, mf++, origIndex++) {
2571                 if (*origIndex == ORIGINDEX_NONE)
2572                         continue;
2573
2574                 e = BLI_memarena_alloc(vd->polyfacemap_arena, sizeof(PolyFaceMap));
2575                 e->facenr = i;
2576                 
2577                 BLI_addtail(&vd->polyfacemap[*origIndex], e);
2578         }
2579 }
2580
2581 static int vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const float UNUSED(mouse[2]))
2582 {
2583         ToolSettings *ts = CTX_data_tool_settings(C);
2584         struct PaintStroke *stroke = op->customdata;
2585         VPaint *vp = ts->vpaint;
2586         struct VPaintData *vpd;
2587         Object *ob = CTX_data_active_object(C);
2588         Mesh *me;
2589         float mat[4][4], imat[4][4];
2590
2591         /* context checks could be a poll() */
2592         me = BKE_mesh_from_object(ob);
2593         if (me == NULL || me->totpoly == 0)
2594                 return OPERATOR_PASS_THROUGH;
2595         
2596         if (me->mloopcol == NULL)
2597                 make_vertexcol(ob);
2598         if (me->mloopcol == NULL)
2599                 return OPERATOR_CANCELLED;
2600         
2601         /* make mode data storage */
2602         vpd = MEM_callocN(sizeof(struct VPaintData), "VPaintData");
2603         paint_stroke_set_mode_data(stroke, vpd);
2604         view3d_set_viewcontext(C, &vpd->vc);
2605         
2606         vpd->vertexcosnos = mesh_get_mapped_verts_nors(vpd->vc.scene, ob);
2607         vpd->indexar = get_indexarray(me);
2608         vpd->paintcol = vpaint_get_current_col(vp);
2609
2610
2611         /* are we painting onto a modified mesh?,
2612          * if not we can skip face map trickyness */
2613         if (vertex_paint_use_fast_update_check(ob)) {
2614                 vpaint_build_poly_facemap(vpd, me);
2615                 vpd->use_fast_update = TRUE;
2616         }
2617         else {
2618                 vpd->use_fast_update = FALSE;
2619         }
2620
2621         /* for filtering */
2622         copy_vpaint_prev(vp, (unsigned int *)me->mloopcol, me->totloop);
2623         
2624         /* some old cruft to sort out later */
2625         mult_m4_m4m4(mat, vpd->vc.rv3d->viewmat, ob->obmat);
2626         invert_m4_m4(imat, mat);
2627         copy_m3_m4(vpd->vpimat, imat);
2628
2629         return 1;
2630 }
2631
2632 static void copy_lcol_to_mcol(MCol *mcol, const MLoopCol *lcol)
2633 {
2634         mcol->a = lcol->a;
2635         mcol->r = lcol->r;
2636         mcol->g = lcol->g;
2637         mcol->b = lcol->b;
2638 }
2639
2640 static void vpaint_paint_poly(VPaint *vp, VPaintData *vpd, Object *ob,
2641                               const unsigned int index, const float mval[2],
2642                               const float brush_size_pressure, const float brush_alpha_pressure)
2643 {
2644         ViewContext *vc = &vpd->vc;
2645         Brush *brush = paint_brush(&vp->paint);
2646         Mesh *me = BKE_mesh_from_object(ob);
2647         MPoly *mpoly = &me->mpoly[index];
2648         MFace *mf;
2649         MCol *mc;
2650         MLoop *ml;
2651         MLoopCol *mlc;
2652         PolyFaceMap *e;
2653         unsigned int *lcol = ((unsigned int *)me->mloopcol) + mpoly->loopstart;
2654         unsigned int *lcolorig = ((unsigned int *)vp->vpaint_prev) + mpoly->loopstart;
2655         float alpha;
2656         int i, j;
2657
2658         int brush_alpha_pressure_i = (int)(brush_alpha_pressure * 255.0f);
2659
2660         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2661                 unsigned int blend[4] = {0};
2662                 unsigned int tcol;
2663                 char *col;
2664
2665                 for (j = 0; j < mpoly->totloop; j++) {
2666                         col = (char *)(lcol + j);
2667                         blend[0] += col[0];
2668                         blend[1] += col[1];
2669                         blend[2] += col[2];
2670                         blend[3] += col[3];
2671                 }
2672
2673                 blend[0] /= mpoly->totloop;
2674                 blend[1] /= mpoly->totloop;
2675                 blend[2] /= mpoly->totloop;
2676                 blend[3] /= mpoly->totloop;
2677                 col = (char *)&tcol;
2678                 col[0] = blend[0];
2679                 col[1] = blend[1];
2680                 col[2] = blend[2];
2681                 col[3] = blend[3];
2682
2683                 vpd->paintcol = *((unsigned int *)col);
2684         }
2685
2686         ml = me->mloop + mpoly->loopstart;
2687         for (i = 0; i < mpoly->totloop; i++, ml++) {
2688                 alpha = calc_vp_alpha_dl(vp, vc, vpd->vpimat,
2689                                          vpd->vertexcosnos + 6 * ml->v, mval,
2690                                          brush_size_pressure, brush_alpha_pressure);
2691                 if (alpha > 0.0f) {
2692                         const int alpha_i = (int)(alpha * 255.0f);
2693                         lcol[i] = vpaint_blend(vp, lcol[i], lcolorig[i], vpd->paintcol, alpha_i, brush_alpha_pressure_i);
2694                 }
2695         }
2696
2697         if (vpd->use_fast_update) {
2698                 /* update vertex colors for tessellations incrementally,
2699                  * rather then regenerating the tessellation altogether */
2700                 for (e = vpd->polyfacemap[index].first; e; e = e->next) {
2701                         mf = &me->mface[e->facenr];
2702                         mc = &me->mcol[e->facenr * 4];
2703
2704                         ml = me->mloop + mpoly->loopstart;
2705                         mlc = me->mloopcol + mpoly->loopstart;
2706                         for (j = 0; j < mpoly->totloop; j++, ml++, mlc++) {
2707                                 if      (ml->v == mf->v1)            copy_lcol_to_mcol(mc + 0, mlc);
2708                                 else if (ml->v == mf->v2)            copy_lcol_to_mcol(mc + 1, mlc);
2709                                 else if (ml->v == mf->v3)            copy_lcol_to_mcol(mc + 2, mlc);
2710                                 else if (mf->v4 && ml->v == mf->v4)  copy_lcol_to_mcol(mc + 3, mlc);
2711
2712                         }
2713                 }
2714         }
2715
2716 }
2717
2718 static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2719 {
2720         Scene *scene = CTX_data_scene(C);
2721         ToolSettings *ts = CTX_data_tool_settings(C);
2722         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2723         VPaint *vp = ts->vpaint;
2724         Brush *brush = paint_brush(&vp->paint);
2725         ViewContext *vc = &vpd->vc;
2726         Object *ob = vc->obact;
2727         Mesh *me = ob->data;
2728         float mat[4][4];
2729         int *indexar = vpd->indexar;
2730         int totindex, index;
2731         float mval[2];
2732
2733         const float pressure = RNA_float_get(itemptr, "pressure");
2734         const float brush_size_pressure = BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2735         const float brush_alpha_pressure = BKE_brush_alpha_get(scene, brush) * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2736
2737         RNA_float_get_array(itemptr, "mouse", mval);
2738
2739         view3d_operator_needs_opengl(C);
2740                         
2741         /* load projection matrix */
2742         mult_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2743
2744         mval[0] -= vc->ar->winrct.xmin;
2745         mval[1] -= vc->ar->winrct.ymin;
2746
2747
2748         /* which faces are involved */
2749         if (vp->flag & VP_AREA) {
2750                 totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2751         }
2752         else {
2753                 indexar[0] = view3d_sample_backbuf(vc, mval[0], mval[1]);
2754                 if (indexar[0]) totindex = 1;
2755                 else totindex = 0;
2756         }
2757
2758         if ((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
2759                 for (index = 0; index < totindex; index++) {
2760                         if (indexar[index] && indexar[index] <= me->totpoly) {
2761                                 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2762                                                 
2763                                 if ((mpoly->flag & ME_FACE_SEL) == 0)
2764                                         indexar[index] = 0;
2765                         }
2766                 }
2767         }
2768         
2769         swap_m4m4(vc->rv3d->persmat, mat);
2770
2771         for (index = 0; index < totindex; index++) {
2772                 if (indexar[index] && indexar[index] <= me->totpoly) {
2773                         vpaint_paint_poly(vp, vpd, ob, indexar[index] - 1, mval, brush_size_pressure, brush_alpha_pressure);
2774                 }
2775         }
2776                 
2777         swap_m4m4(vc->rv3d->persmat, mat);
2778
2779         /* was disabled because it is slow, but necessary for blur */
2780         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2781                 int do_tessface = vpd->use_fast_update;
2782                 do_shared_vertexcol(me, do_tessface);
2783         }
2784
2785         ED_region_tag_redraw(vc->ar);
2786
2787         if (vpd->use_fast_update == FALSE) {
2788                 /* recalculate modifier stack to get new colors, slow,
2789                  * avoid this if we can! */
2790                 DAG_id_tag_update(ob->data, 0);
2791         }
2792 }
2793
2794 static void vpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2795 {
2796         ToolSettings *ts = CTX_data_tool_settings(C);
2797         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2798         ViewContext *vc = &vpd->vc;
2799         Object *ob = vc->obact;
2800         
2801         if (vpd->vertexcosnos)
2802                 MEM_freeN(vpd->vertexcosnos);
2803         MEM_freeN(vpd->indexar);
2804         
2805         /* frees prev buffer */
2806         copy_vpaint_prev(ts->vpaint, NULL, 0);
2807
2808         if (vpd->polyfacemap_arena) {
2809                 BLI_memarena_free(vpd->polyfacemap_arena);
2810         }
2811
2812         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2813
2814         MEM_freeN(vpd);
2815 }
2816
2817 static int vpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2818 {
2819         
2820         op->customdata = paint_stroke_new(C, NULL, vpaint_stroke_test_start,
2821                                           vpaint_stroke_update_step,
2822                                           vpaint_stroke_done, event->type);
2823         
2824         /* add modal handler */
2825         WM_event_add_modal_handler(C, op);
2826
2827         op->type->modal(C, op, event);
2828         
2829         return OPERATOR_RUNNING_MODAL;
2830 }
2831
2832 static int vpaint_cancel(bContext *C, wmOperator *op)
2833 {
2834         paint_stroke_cancel(C, op);
2835
2836         return OPERATOR_CANCELLED;
2837 }
2838
2839 void PAINT_OT_vertex_paint(wmOperatorType *ot)
2840 {
2841         /* identifiers */
2842         ot->name = "Vertex Paint";
2843         ot->idname = "PAINT_OT_vertex_paint";
2844         ot->description = "Paint a stroke in the active vertex color layer";
2845         
2846         /* api callbacks */
2847         ot->invoke = vpaint_invoke;
2848         ot->modal = paint_stroke_modal;
2849         /* ot->exec = vpaint_exec; <-- needs stroke property */
2850         ot->poll = vertex_paint_poll;
2851         ot->cancel = vpaint_cancel;
2852         
2853         /* flags */
2854         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
2855
2856         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2857 }
2858
2859 /* ********************** weight from bones operator ******************* */
2860
2861 static int weight_from_bones_poll(bContext *C)
2862 {
2863         Object *ob = CTX_data_active_object(C);
2864
2865         return (ob && (ob->mode & OB_MODE_WEIGHT_PAINT) && modifiers_isDeformedByArmature(ob));
2866 }
2867
2868 static int weight_from_bones_exec(bContext *C, wmOperator *op)
2869 {
2870         Scene *scene = CTX_data_scene(C);
2871         Object *ob = CTX_data_active_object(C);
2872         Object *armob = modifiers_isDeformedByArmature(ob);
2873         Mesh *me = ob->data;
2874         int type = RNA_enum_get(op->ptr, "type");
2875
2876         create_vgroups_from_armature(op->reports, scene, ob, armob, type, (me->editflag & ME_EDIT_MIRROR_X));
2877
2878         DAG_id_tag_update(&me->id, 0);
2879         WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
2880
2881         return OPERATOR_FINISHED;
2882 }
2883
2884 void PAINT_OT_weight_from_bones(wmOperatorType *ot)
2885 {
2886         static EnumPropertyItem type_items[] = {
2887                 {ARM_GROUPS_AUTO, "AUTOMATIC", 0, "Automatic", "Automatic weights from bones"},
2888                 {ARM_GROUPS_ENVELOPE, "ENVELOPES", 0, "From Envelopes", "Weights from envelopes with user defined radius"},
2889                 {0, NULL, 0, NULL, NULL}};
2890
2891         /* identifiers */
2892         ot->name = "Weight from Bones";
2893         ot->idname = "PAINT_OT_weight_from_bones";
2894         ot->description = "Set the weights of the groups matching the attached armature's selected bones, "
2895                           "using the distance between the vertices and the bones";
2896         
2897         /* api callbacks */
2898         ot->exec = weight_from_bones_exec;
2899         ot->invoke = WM_menu_invoke;
2900         ot->poll = weight_from_bones_poll;
2901         
2902         /* flags */
2903         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2904
2905         /* properties */
2906         ot->prop = RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "Method to use for assigning weights");
2907 }