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