c5c08a94ae533c3e452d15800af8f0114b5d9b3e
[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_haskey(gh, chan->name)) {
2104                                                 BLI_ghash_remove(gh, chan->name, NULL, NULL);
2105                                                 BLI_ghash_insert(gh, chan->name, SET_INT_IN_POINTER(1));
2106                                         }
2107                                 }
2108                         }
2109                 }
2110         }
2111
2112         vgroup_validmap = MEM_mallocN(BLI_ghash_size(gh), "wpaint valid map");
2113
2114         /* add all names to a hash table */
2115         for (dg = ob->defbase.first, i = 0; dg; dg = dg->next, i++) {
2116                 vgroup_validmap[i] = (BLI_ghash_lookup(gh, dg->name) != NULL);
2117         }
2118
2119         BLI_assert(i == BLI_ghash_size(gh));
2120
2121         BLI_ghash_free(gh, NULL, NULL);
2122
2123         return vgroup_validmap;
2124 }
2125
2126 static int wpaint_stroke_test_start(bContext *C, wmOperator *op, const float UNUSED(mouse[2]))
2127 {
2128         Scene *scene = CTX_data_scene(C);
2129         struct PaintStroke *stroke = op->customdata;
2130         ToolSettings *ts = scene->toolsettings;
2131         VPaint *wp = ts->wpaint;
2132         Object *ob = CTX_data_active_object(C);
2133         struct WPaintData *wpd;
2134         Mesh *me;
2135         bDeformGroup *dg;
2136
2137         float mat[4][4], imat[4][4];
2138         
2139         if (scene->obedit) {
2140                 return FALSE;
2141         }
2142         
2143         me = BKE_mesh_from_object(ob);
2144         if (me == NULL || me->totpoly == 0) return OPERATOR_PASS_THROUGH;
2145         
2146         /* if nothing was added yet, we make dverts and a vertex deform group */
2147         if (!me->dvert) {
2148                 ED_vgroup_data_create(&me->id);
2149                 WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
2150         }
2151
2152         /* this happens on a Bone select, when no vgroup existed yet */
2153         if (ob->actdef <= 0) {
2154                 Object *modob;
2155                 if ((modob = modifiers_isDeformedByArmature(ob))) {
2156                         Bone *actbone = ((bArmature *)modob->data)->act_bone;
2157                         if (actbone) {
2158                                 bPoseChannel *pchan = BKE_pose_channel_find_name(modob->pose, actbone->name);
2159
2160                                 if (pchan) {
2161                                         bDeformGroup *dg = defgroup_find_name(ob, pchan->name);
2162                                         if (dg == NULL) {
2163                                                 dg = ED_vgroup_add_name(ob, pchan->name);  /* sets actdef */
2164                                         }
2165                                         else {
2166                                                 int actdef = 1 + BLI_findindex(&ob->defbase, dg);
2167                                                 BLI_assert(actdef >= 0);
2168                                                 ob->actdef = actdef;
2169                                         }
2170                                 }
2171                         }
2172                 }
2173         }
2174         if (ob->defbase.first == NULL) {
2175                 ED_vgroup_add(ob);
2176         }
2177
2178         /* ensure we don't try paint onto an invalid group */
2179         if (ob->actdef <= 0) {
2180                 BKE_report(op->reports, RPT_WARNING, "No active vertex group for painting, aborting");
2181                 return FALSE;
2182         }
2183
2184         /* check if we are attempting to paint onto a locked vertex group,
2185          * and other options disallow it from doing anything useful */
2186         dg = BLI_findlink(&ob->defbase, (ob->actdef - 1));
2187         if (dg->flag & DG_LOCK_WEIGHT) {
2188                 BKE_report(op->reports, RPT_WARNING, "Active group is locked, aborting");
2189                 return FALSE;
2190         }
2191
2192         /* ALLOCATIONS! no return after this line */
2193         /* make mode data storage */
2194         wpd = MEM_callocN(sizeof(struct WPaintData), "WPaintData");
2195         paint_stroke_set_mode_data(stroke, wpd);
2196         view3d_set_viewcontext(C, &wpd->vc);
2197
2198         wpd->vgroup_active = ob->actdef - 1;
2199         wpd->vgroup_mirror = -1;
2200
2201         /* set up auto-normalize, and generate map for detecting which
2202          * vgroups affect deform bones */
2203         wpd->defbase_tot = BLI_countlist(&ob->defbase);
2204         wpd->lock_flags = gen_lock_flags(ob, wpd->defbase_tot);
2205         if (ts->auto_normalize || ts->multipaint || wpd->lock_flags) {
2206                 wpd->vgroup_validmap = wpaint_make_validmap(ob);
2207         }
2208
2209         /* painting on subsurfs should give correct points too, this returns me->totvert amount */
2210         wpd->vertexcosnos = mesh_get_mapped_verts_nors(scene, ob);
2211         wpd->indexar = get_indexarray(me);
2212         copy_wpaint_prev(wp, me->dvert, me->totvert);
2213
2214         /* imat for normals */
2215         mult_m4_m4m4(mat, wpd->vc.rv3d->viewmat, ob->obmat);
2216         invert_m4_m4(imat, mat);
2217         copy_m3_m4(wpd->wpimat, imat);
2218
2219         /* if mirror painting, find the other group */
2220         if (me->editflag & ME_EDIT_MIRROR_X) {
2221                 wpd->vgroup_mirror = wpaint_mirror_vgroup_ensure(ob, wpd->vgroup_active);
2222         }
2223         
2224         return TRUE;
2225 }
2226
2227 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2228 {
2229         Scene *scene = CTX_data_scene(C);
2230         ToolSettings *ts = CTX_data_tool_settings(C);
2231         VPaint *wp = ts->wpaint;
2232         Brush *brush = paint_brush(&wp->paint);
2233         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2234         ViewContext *vc;
2235         Object *ob;
2236         Mesh *me;
2237         float mat[4][4];
2238         float paintweight;
2239         int *indexar;
2240         float totw;
2241         unsigned int index, totindex;
2242         float alpha;
2243         float mval[2];
2244         int use_vert_sel;
2245         char *defbase_sel;
2246
2247         const float pressure = RNA_float_get(itemptr, "pressure");
2248         const float brush_size_pressure = BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2249         const float brush_alpha_value = BKE_brush_alpha_get(scene, brush);
2250         const float brush_alpha_pressure = brush_alpha_value * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2251
2252         /* intentionally don't initialize as NULL, make sure we initialize all members below */
2253         WeightPaintInfo wpi;
2254
2255         /* cannot paint if there is no stroke data */
2256         if (wpd == NULL) {
2257                 /* XXX: force a redraw here, since even though we can't paint,
2258                  * at least view won't freeze until stroke ends */
2259                 ED_region_tag_redraw(CTX_wm_region(C));
2260                 return;
2261         }
2262                 
2263         vc = &wpd->vc;
2264         ob = vc->obact;
2265         me = ob->data;
2266         indexar = wpd->indexar;
2267         
2268         view3d_operator_needs_opengl(C);
2269                 
2270         /* load projection matrix */
2271         mult_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2272
2273         RNA_float_get_array(itemptr, "mouse", mval);
2274         mval[0] -= vc->ar->winrct.xmin;
2275         mval[1] -= vc->ar->winrct.ymin;
2276
2277
2278
2279         /* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
2280         wpi.defbase_tot =        wpd->defbase_tot;
2281         defbase_sel =            MEM_mallocN(wpi.defbase_tot * sizeof(char), "wpi.defbase_sel");
2282         wpi.defbase_tot_sel =    get_selected_defgroups(ob, defbase_sel, wpi.defbase_tot);
2283         wpi.defbase_sel =        defbase_sel; /* so we can stay const */
2284         if (wpi.defbase_tot_sel == 0 && ob->actdef > 0) wpi.defbase_tot_sel = 1;
2285
2286         wpi.defbase_tot_unsel =  wpi.defbase_tot - wpi.defbase_tot_sel;
2287         wpi.vgroup_active =      wpd->vgroup_active;
2288         wpi.vgroup_mirror =      wpd->vgroup_mirror;
2289         wpi.lock_flags =         wpd->lock_flags;
2290         wpi.vgroup_validmap =    wpd->vgroup_validmap;
2291         wpi.do_flip =            RNA_boolean_get(itemptr, "pen_flip");
2292         wpi.do_multipaint =      (ts->multipaint != 0);
2293         wpi.do_auto_normalize =  ((ts->auto_normalize != 0) && (wpi.vgroup_validmap != NULL));
2294         wpi.brush_alpha_value =  brush_alpha_value;
2295         /* *** done setting up WeightPaintInfo *** */
2296
2297
2298
2299         swap_m4m4(wpd->vc.rv3d->persmat, mat);
2300
2301         use_vert_sel = (me->editflag & ME_EDIT_VERT_SEL) != 0;
2302
2303         /* which faces are involved */
2304         if (wp->flag & VP_AREA) {
2305                 /* Ugly hack, to avoid drawing vertex index when getting the face index buffer - campbell */
2306                 me->editflag &= ~ME_EDIT_VERT_SEL;
2307                 totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2308                 me->editflag |= use_vert_sel ? ME_EDIT_VERT_SEL : 0;
2309         }
2310         else {
2311                 indexar[0] = view3d_sample_backbuf(vc, mval[0], mval[1]);
2312                 if (indexar[0]) totindex = 1;
2313                 else totindex = 0;
2314         }
2315                         
2316         if (wp->flag & VP_COLINDEX) {
2317                 for (index = 0; index < totindex; index++) {
2318                         if (indexar[index] && indexar[index] <= me->totpoly) {
2319                                 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2320                                                 
2321                                 if (mpoly->mat_nr != ob->actcol - 1) {
2322                                         indexar[index] = 0;
2323                                 }
2324                         }
2325                 }
2326         }
2327                         
2328         if ((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
2329                 for (index = 0; index < totindex; index++) {
2330                         if (indexar[index] && indexar[index] <= me->totpoly) {
2331                                 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2332                                                 
2333                                 if ((mpoly->flag & ME_FACE_SEL) == 0) {
2334                                         indexar[index] = 0;
2335                                 }
2336                         }
2337                 }
2338         }
2339
2340         /* make sure each vertex gets treated only once */
2341         /* and calculate filter weight */
2342         totw = 0.0f;
2343         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR)
2344                 paintweight = 0.0f;
2345         else
2346                 paintweight = BKE_brush_weight_get(scene, brush);
2347                         
2348         for (index = 0; index < totindex; index++) {
2349                 if (indexar[index] && indexar[index] <= me->totpoly) {
2350                         MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2351                         MLoop *ml = me->mloop + mpoly->loopstart;
2352                         int i;
2353
2354                         if (use_vert_sel) {
2355                                 for (i = 0; i < mpoly->totloop; i++, ml++) {
2356                                         me->dvert[ml->v].flag = (me->mvert[ml->v].flag & SELECT);
2357                                 }
2358                         }
2359                         else {
2360                                 for (i = 0; i < mpoly->totloop; i++, ml++) {
2361                                         me->dvert[ml->v].flag = 1;
2362                                 }
2363                         }
2364                                         
2365                         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2366                                 MDeformWeight *dw, *(*dw_func)(MDeformVert *, const int);
2367                                                 
2368                                 if (wp->flag & VP_ONLYVGROUP)
2369                                         dw_func = (MDeformWeight *(*)(MDeformVert *, const int))defvert_find_index;
2370                                 else
2371                                         dw_func = defvert_verify_index;
2372                                                 
2373                                 ml = me->mloop + mpoly->loopstart;
2374                                 for (i = 0; i < mpoly->totloop; i++, ml++) {
2375                                         unsigned int vidx = ml->v;
2376                                         const float fac = calc_vp_strength_dl(wp, vc, wpd->vertexcosnos + 6 * vidx, mval, brush_size_pressure);
2377                                         if (fac > 0.0f) {
2378                                                 dw = dw_func(&me->dvert[vidx], wpi.vgroup_active);
2379                                                 paintweight += dw ? (dw->weight * fac) : 0.0f;
2380                                                 totw += fac;
2381                                         }
2382                                 }
2383                         }
2384                 }
2385         }
2386                         
2387         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2388                 paintweight /= totw;
2389         }
2390
2391         for (index = 0; index < totindex; index++) {
2392
2393                 if (indexar[index] && indexar[index] <= me->totpoly) {
2394                         MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2395                         MLoop *ml = me->mloop + mpoly->loopstart;
2396                         int i;
2397
2398                         for (i = 0; i < mpoly->totloop; i++, ml++) {
2399                                 unsigned int vidx = ml->v;
2400
2401                                 if (me->dvert[vidx].flag) {
2402                                         alpha = calc_vp_alpha_dl(wp, vc, wpd->wpimat, wpd->vertexcosnos + 6 * vidx,
2403                                                                  mval, brush_size_pressure, brush_alpha_pressure);
2404                                         if (alpha) {
2405                                                 do_weight_paint_vertex(wp, ob, &wpi, vidx, alpha, paintweight);
2406                                         }
2407                                         me->dvert[vidx].flag = 0;
2408                                 }
2409                         }
2410                 }
2411         }
2412
2413
2414         /* *** free wpi members */
2415         MEM_freeN((void *)wpi.defbase_sel);
2416         /* *** don't freeing wpi members */
2417
2418
2419         swap_m4m4(vc->rv3d->persmat, mat);
2420                         
2421         DAG_id_tag_update(ob->data, 0);
2422         ED_region_tag_redraw(vc->ar);
2423 }
2424
2425 static void wpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2426 {
2427         ToolSettings *ts = CTX_data_tool_settings(C);
2428         Object *ob = CTX_data_active_object(C);
2429         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2430         
2431         if (wpd) {
2432                 if (wpd->vertexcosnos)
2433                         MEM_freeN(wpd->vertexcosnos);
2434                 MEM_freeN(wpd->indexar);
2435                 
2436                 if (wpd->vgroup_validmap)
2437                         MEM_freeN((void *)wpd->vgroup_validmap);
2438                 if (wpd->lock_flags)
2439                         MEM_freeN((void *)wpd->lock_flags);
2440
2441                 MEM_freeN(wpd);
2442         }
2443         
2444         /* frees prev buffer */
2445         copy_wpaint_prev(ts->wpaint, NULL, 0);
2446         
2447         /* and particles too */
2448         if (ob->particlesystem.first) {
2449                 ParticleSystem *psys;
2450                 int i;
2451                 
2452                 for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2453                         for (i = 0; i < PSYS_TOT_VG; i++) {
2454                                 if (psys->vgroup[i] == ob->actdef) {
2455                                         psys->recalc |= PSYS_RECALC_RESET;
2456                                         break;
2457                                 }
2458                         }
2459                 }
2460         }
2461         
2462         DAG_id_tag_update(ob->data, 0);
2463 }
2464
2465
2466 static int wpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2467 {
2468         
2469         op->customdata = paint_stroke_new(C, NULL, wpaint_stroke_test_start,
2470                                           wpaint_stroke_update_step,
2471                                           wpaint_stroke_done, event->type);
2472         
2473         /* add modal handler */
2474         WM_event_add_modal_handler(C, op);
2475
2476         op->type->modal(C, op, event);
2477         
2478         return OPERATOR_RUNNING_MODAL;
2479 }
2480
2481 static int wpaint_cancel(bContext *C, wmOperator *op)
2482 {
2483         paint_stroke_cancel(C, op);
2484
2485         return OPERATOR_CANCELLED;
2486 }
2487
2488 void PAINT_OT_weight_paint(wmOperatorType *ot)
2489 {
2490         
2491         /* identifiers */
2492         ot->name = "Weight Paint";
2493         ot->idname = "PAINT_OT_weight_paint";
2494         ot->description = "Paint a stroke in the current vertex group's weights";
2495         
2496         /* api callbacks */
2497         ot->invoke = wpaint_invoke;
2498         ot->modal = paint_stroke_modal;
2499         /* ot->exec = vpaint_exec; <-- needs stroke property */
2500         ot->poll = weight_paint_poll;
2501         ot->cancel = wpaint_cancel;
2502         
2503         /* flags */
2504         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
2505
2506         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2507 }
2508
2509 static int weight_paint_set_exec(bContext *C, wmOperator *UNUSED(op))
2510 {
2511         struct Scene *scene = CTX_data_scene(C);
2512         Object *obact = CTX_data_active_object(C);
2513         ToolSettings *ts = CTX_data_tool_settings(C);
2514         Brush *brush = paint_brush(&ts->wpaint->paint);
2515         float vgroup_weight = BKE_brush_weight_get(scene, brush);
2516
2517         wpaint_fill(scene->toolsettings->wpaint, obact, vgroup_weight);
2518         ED_region_tag_redraw(CTX_wm_region(C)); /* XXX - should redraw all 3D views */
2519         return OPERATOR_FINISHED;
2520 }
2521
2522 void PAINT_OT_weight_set(wmOperatorType *ot)
2523 {
2524         /* identifiers */
2525         ot->name = "Set Weight";
2526         ot->idname = "PAINT_OT_weight_set";
2527         ot->description = "Fill the active vertex group with the current paint weight";
2528
2529         /* api callbacks */
2530         ot->exec = weight_paint_set_exec;
2531         ot->poll = mask_paint_poll; /* it was facemask_paint_poll */
2532
2533         /* flags */
2534         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2535 }
2536
2537 /* ************ set / clear vertex paint mode ********** */
2538
2539
2540 static int set_vpaint(bContext *C, wmOperator *op)  /* toggle */
2541 {       
2542         Object *ob = CTX_data_active_object(C);
2543         Scene *scene = CTX_data_scene(C);
2544         VPaint *vp = scene->toolsettings->vpaint;
2545         Mesh *me;
2546         
2547         me = BKE_mesh_from_object(ob);
2548         
2549         if (me == NULL || BKE_object_obdata_is_libdata(ob)) {
2550                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2551                 return OPERATOR_PASS_THROUGH;
2552         }
2553         
2554         if (me && me->mloopcol == NULL) {
2555                 make_vertexcol(ob);
2556         }
2557         
2558         /* toggle: end vpaint */
2559         if (ob->mode & OB_MODE_VERTEX_PAINT) {
2560                 
2561                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2562         }
2563         else {
2564                 ob->mode |= OB_MODE_VERTEX_PAINT;
2565                 /* Turn off weight painting */
2566                 if (ob->mode & OB_MODE_WEIGHT_PAINT)
2567                         set_wpaint(C, op);
2568                 
2569                 if (vp == NULL)
2570                         vp = scene->toolsettings->vpaint = new_vpaint(0);
2571                 
2572                 paint_cursor_start(C, vertex_paint_poll);
2573
2574                 paint_init(&vp->paint, PAINT_CURSOR_VERTEX_PAINT);
2575         }
2576         
2577         if (me)
2578                 /* update modifier stack for mapping requirements */
2579                 DAG_id_tag_update(&me->id, 0);
2580         
2581         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
2582         
2583         return OPERATOR_FINISHED;
2584 }
2585
2586 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2587 {
2588         
2589         /* identifiers */
2590         ot->name = "Vertex Paint Mode";
2591         ot->idname = "PAINT_OT_vertex_paint_toggle";
2592         ot->description = "Toggle the vertex paint mode in 3D view";
2593         
2594         /* api callbacks */
2595         ot->exec = set_vpaint;
2596         ot->poll = paint_poll_test;
2597         
2598         /* flags */
2599         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2600 }
2601
2602
2603
2604 /* ********************** vertex paint operator ******************* */
2605
2606 /* Implementation notes:
2607  *
2608  * Operator->invoke()
2609  * - validate context (add mcol)
2610  * - create customdata storage
2611  * - call paint once (mouse click)
2612  * - add modal handler 
2613  *
2614  * Operator->modal()
2615  * - for every mousemove, apply vertex paint
2616  * - exit on mouse release, free customdata
2617  *   (return OPERATOR_FINISHED also removes handler and operator)
2618  *
2619  * For future:
2620  * - implement a stroke event (or mousemove with past positons)
2621  * - revise whether op->customdata should be added in object, in set_vpaint
2622  */
2623
2624 typedef struct polyfacemap_e {
2625         struct polyfacemap_e *next, *prev;
2626         int facenr;
2627 } polyfacemap_e;
2628
2629 typedef struct VPaintData {
2630         ViewContext vc;
2631         unsigned int paintcol;
2632         int *indexar;
2633         float *vertexcosnos;
2634         float vpimat[3][3];
2635
2636         /* modify 'me->mcol' directly, since the derived mesh is drawing from this array,
2637          * otherwise we need to refresh the modifier stack */
2638         int use_fast_update;
2639
2640         /* mpoly -> mface mapping */
2641         MemArena *polyfacemap_arena;
2642         ListBase *polyfacemap;
2643 } VPaintData;
2644
2645 static void vpaint_build_poly_facemap(struct VPaintData *vd, Mesh *me)
2646 {
2647         MFace *mf;
2648         polyfacemap_e *e;
2649         int *origIndex;
2650         int i;
2651
2652         vd->polyfacemap_arena = BLI_memarena_new(1 << 13, "vpaint tmp");
2653         BLI_memarena_use_calloc(vd->polyfacemap_arena);
2654
2655         vd->polyfacemap = BLI_memarena_alloc(vd->polyfacemap_arena, sizeof(ListBase) * me->totpoly);
2656
2657         origIndex = CustomData_get_layer(&me->fdata, CD_POLYINDEX);
2658         mf = me->mface;
2659
2660         if (!origIndex)
2661                 return;
2662
2663         for (i = 0; i < me->totface; i++, mf++, origIndex++) {
2664                 if (*origIndex == ORIGINDEX_NONE)
2665                         continue;
2666
2667                 e = BLI_memarena_alloc(vd->polyfacemap_arena, sizeof(polyfacemap_e));
2668                 e->facenr = i;
2669                 
2670                 BLI_addtail(&vd->polyfacemap[*origIndex], e);
2671         }
2672 }
2673
2674 static int vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const float UNUSED(mouse[2]))
2675 {
2676         ToolSettings *ts = CTX_data_tool_settings(C);
2677         struct PaintStroke *stroke = op->customdata;
2678         VPaint *vp = ts->vpaint;
2679         struct VPaintData *vpd;
2680         Object *ob = CTX_data_active_object(C);
2681         Mesh *me;
2682         float mat[4][4], imat[4][4];
2683
2684         /* context checks could be a poll() */
2685         me = BKE_mesh_from_object(ob);
2686         if (me == NULL || me->totpoly == 0)
2687                 return OPERATOR_PASS_THROUGH;
2688         
2689         if (me->mloopcol == NULL)
2690                 make_vertexcol(ob);
2691         if (me->mloopcol == NULL)
2692                 return OPERATOR_CANCELLED;
2693         
2694         /* make mode data storage */
2695         vpd = MEM_callocN(sizeof(struct VPaintData), "VPaintData");
2696         paint_stroke_set_mode_data(stroke, vpd);
2697         view3d_set_viewcontext(C, &vpd->vc);
2698         
2699         vpd->vertexcosnos = mesh_get_mapped_verts_nors(vpd->vc.scene, ob);
2700         vpd->indexar = get_indexarray(me);
2701         vpd->paintcol = vpaint_get_current_col(vp);
2702
2703
2704         /* are we painting onto a modified mesh?,
2705          * if not we can skip face map trickyness */
2706         if (vertex_paint_use_fast_update_check(ob)) {
2707                 vpaint_build_poly_facemap(vpd, me);
2708                 vpd->use_fast_update = TRUE;
2709         }
2710         else {
2711                 vpd->use_fast_update = FALSE;
2712         }
2713
2714         /* for filtering */
2715         copy_vpaint_prev(vp, (unsigned int *)me->mloopcol, me->totloop);
2716         
2717         /* some old cruft to sort out later */
2718         mult_m4_m4m4(mat, vpd->vc.rv3d->viewmat, ob->obmat);
2719         invert_m4_m4(imat, mat);
2720         copy_m3_m4(vpd->vpimat, imat);
2721
2722         return 1;
2723 }
2724
2725 #if 0
2726 static void vpaint_paint_face(VPaint *vp, VPaintData *vpd, Object *ob,
2727                               const unsigned int index, const float mval[2],
2728                               const float brush_size_pressure, const float brush_alpha_pressure,
2729                               int UNUSED(flip))
2730 {
2731         ViewContext *vc = &vpd->vc;
2732         Brush *brush = paint_brush(&vp->paint);
2733         Mesh *me = BKE_mesh_from_object(ob);
2734         MFace *mface = &me->mface[index];
2735         unsigned int *mcol = ((unsigned int *)me->mcol) + 4 * index;
2736         unsigned int *mcolorig = ((unsigned int *)vp->vpaint_prev) + 4 * index;
2737         float alpha;
2738         int i;
2739
2740         int brush_alpha_pressure_i;
2741         
2742         if ((vp->flag & VP_COLINDEX && mface->mat_nr != ob->actcol - 1) ||
2743             ((me->editflag & ME_EDIT_PAINT_MASK) && !(mface->flag & ME_FACE_SEL)))
2744                 return;
2745
2746         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2747                 unsigned int fcol1 = mcol_blend(mcol[0], mcol[1], 128);
2748                 if (mface->v4) {
2749                         unsigned int fcol2 = mcol_blend(mcol[2], mcol[3], 128);
2750                         vpd->paintcol = mcol_blend(fcol1, fcol2, 128);
2751                 }
2752                 else {
2753                         vpd->paintcol = mcol_blend(mcol[2], fcol1, 170);
2754                 }
2755         }
2756
2757         brush_alpha_pressure_i = (int)(brush_alpha_pressure * 255.0f);
2758
2759         for (i = 0; i < (mface->v4 ? 4 : 3); ++i) {
2760                 alpha = calc_vp_alpha_dl(vp, vc, vpd->vpimat, vpd->vertexcosnos + 6 * (&mface->v1)[i],
2761                                          mval, brush_size_pressure, brush_alpha_pressure);
2762                 if (alpha) {
2763                         const int alpha_i = (int)(alpha * 255.0f);
2764                         mcol[i] = vpaint_blend(vp, mcol[i], mcolorig[i], vpd->paintcol, alpha_i, brush_alpha_pressure_i);
2765                 }
2766         }
2767 }
2768 #endif
2769
2770 /* BMESH version of vpaint_paint_face (commented above) */
2771
2772 static void vpaint_paint_poly(VPaint *vp, VPaintData *vpd, Object *ob,
2773                               const unsigned int index, const float mval[2],
2774                               const float brush_size_pressure, const float brush_alpha_pressure)
2775 {
2776         ViewContext *vc = &vpd->vc;
2777         Brush *brush = paint_brush(&vp->paint);
2778         Mesh *me = BKE_mesh_from_object(ob);
2779         MPoly *mpoly = &me->mpoly[index];
2780         MFace *mf;
2781         MCol *mc;
2782         MLoop *ml;
2783         MLoopCol *mlc;
2784         polyfacemap_e *e;
2785         unsigned int *lcol = ((unsigned int *)me->mloopcol) + mpoly->loopstart;
2786         unsigned int *lcolorig = ((unsigned int *)vp->vpaint_prev) + mpoly->loopstart;
2787         float alpha;
2788         int i, j;
2789
2790         int brush_alpha_pressure_i = (int)(brush_alpha_pressure * 255.0f);
2791
2792         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2793                 unsigned int blend[4] = {0};
2794                 unsigned int tcol;
2795                 char *col;
2796
2797                 for (j = 0; j < mpoly->totloop; j++) {
2798                         col = (char *)(lcol + j);
2799                         blend[0] += col[0];
2800                         blend[1] += col[1];
2801                         blend[2] += col[2];
2802                         blend[3] += col[3];
2803                 }
2804
2805                 blend[0] /= mpoly->totloop;
2806                 blend[1] /= mpoly->totloop;
2807                 blend[2] /= mpoly->totloop;
2808                 blend[3] /= mpoly->totloop;
2809                 col = (char *)&tcol;
2810                 col[0] = blend[0];
2811                 col[1] = blend[1];
2812                 col[2] = blend[2];
2813                 col[3] = blend[3];
2814
2815                 vpd->paintcol = *((unsigned int *)col);
2816         }
2817
2818         ml = me->mloop + mpoly->loopstart;
2819         for (i = 0; i < mpoly->totloop; i++, ml++) {
2820                 alpha = calc_vp_alpha_dl(vp, vc, vpd->vpimat,
2821                                          vpd->vertexcosnos + 6 * ml->v, mval,
2822                                          brush_size_pressure, brush_alpha_pressure);
2823                 if (alpha > 0.0f) {
2824                         const int alpha_i = (int)(alpha * 255.0f);
2825                         lcol[i] = vpaint_blend(vp, lcol[i], lcolorig[i], vpd->paintcol, alpha_i, brush_alpha_pressure_i);
2826                 }
2827         }
2828
2829         if (vpd->use_fast_update) {
2830
2831 #ifdef CPYCOL
2832 #  undef CPYCOL
2833 #endif
2834 #define CPYCOL(c, l) (c)->a = (l)->a, (c)->r = (l)->r, (c)->g = (l)->g, (c)->b = (l)->b
2835
2836                 /* update vertex colors for tessellations incrementally,
2837                  * rather then regenerating the tessellation altogether */
2838                 for (e = vpd->polyfacemap[index].first; e; e = e->next) {
2839                         mf = me->mface + e->facenr;
2840                         mc = me->mcol + e->facenr * 4;
2841
2842                         ml = me->mloop + mpoly->loopstart;
2843                         mlc = me->mloopcol + mpoly->loopstart;
2844                         for (j = 0; j < mpoly->totloop; j++, ml++, mlc++) {
2845                                 if (ml->v == mf->v1)
2846                                         CPYCOL(mc, mlc);
2847                                 else if (ml->v == mf->v2)
2848                                         CPYCOL(mc + 1, mlc);
2849                                 else if (ml->v == mf->v3)
2850                                         CPYCOL(mc + 2, mlc);
2851                                 else if (mf->v4 && ml->v == mf->v4)
2852                                         CPYCOL(mc + 3, mlc);
2853
2854                         }
2855                 }
2856 #undef CPYCOL
2857         }
2858
2859 }
2860
2861 static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2862 {
2863         Scene *scene = CTX_data_scene(C);
2864         ToolSettings *ts = CTX_data_tool_settings(C);
2865         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2866         VPaint *vp = ts->vpaint;
2867         Brush *brush = paint_brush(&vp->paint);
2868         ViewContext *vc = &vpd->vc;
2869         Object *ob = vc->obact;
2870         Mesh *me = ob->data;
2871         float mat[4][4];
2872         int *indexar = vpd->indexar;
2873         int totindex, index;
2874         float mval[2];
2875
2876         const float pressure = RNA_float_get(itemptr, "pressure");
2877         const float brush_size_pressure = BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2878         const float brush_alpha_pressure = BKE_brush_alpha_get(scene, brush) * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2879
2880         RNA_float_get_array(itemptr, "mouse", mval);
2881
2882         view3d_operator_needs_opengl(C);
2883                         
2884         /* load projection matrix */
2885         mult_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2886
2887         mval[0] -= vc->ar->winrct.xmin;
2888         mval[1] -= vc->ar->winrct.ymin;
2889
2890                         
2891         /* which faces are involved */
2892         if (vp->flag & VP_AREA) {
2893                 totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2894         }
2895         else {
2896                 indexar[0] = view3d_sample_backbuf(vc, mval[0], mval[1]);
2897                 if (indexar[0]) totindex = 1;
2898                 else totindex = 0;
2899         }
2900                         
2901                         
2902         if (vp->flag & VP_COLINDEX) {
2903                 for (index = 0; index < totindex; index++) {
2904                         if (indexar[index] && indexar[index] <= me->totpoly) {
2905                                 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2906                                                 
2907                                 if (mpoly->mat_nr != ob->actcol - 1) {
2908                                         indexar[index] = 0;
2909                                 }
2910                         }
2911                 }
2912         }
2913
2914         if ((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
2915                 for (index = 0; index < totindex; index++) {
2916                         if (indexar[index] && indexar[index] <= me->totpoly) {
2917                                 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2918                                                 
2919                                 if ((mpoly->flag & ME_FACE_SEL) == 0)
2920                                         indexar[index] = 0;
2921                         }                                       
2922                 }
2923         }
2924         
2925         swap_m4m4(vc->rv3d->persmat, mat);
2926
2927                         
2928         for (index = 0; index < totindex; index++) {
2929                                 
2930                 if (indexar[index] && indexar[index] <= me->totpoly) {
2931                         vpaint_paint_poly(vp, vpd, ob, indexar[index] - 1, mval, brush_size_pressure, brush_alpha_pressure);
2932                 }
2933         }
2934                 
2935         swap_m4m4(vc->rv3d->persmat, mat);
2936
2937         /* was disabled because it is slow, but necessary for blur */
2938         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2939                 int do_tessface = vpd->use_fast_update;
2940                 do_shared_vertexcol(me, do_tessface);
2941         }
2942
2943         ED_region_tag_redraw(vc->ar);
2944
2945         if (vpd->use_fast_update == FALSE) {
2946                 /* recalculate modifier stack to get new colors, slow,
2947                  * avoid this if we can! */
2948                 DAG_id_tag_update(ob->data, 0);
2949         }
2950 }
2951
2952 static void vpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2953 {
2954         ToolSettings *ts = CTX_data_tool_settings(C);
2955         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2956         
2957         if (vpd->vertexcosnos)
2958                 MEM_freeN(vpd->vertexcosnos);
2959         MEM_freeN(vpd->indexar);
2960         
2961         /* frees prev buffer */
2962         copy_vpaint_prev(ts->vpaint, NULL, 0);
2963
2964         if (vpd->polyfacemap_arena) {
2965                 BLI_memarena_free(vpd->polyfacemap_arena);
2966         }
2967
2968         MEM_freeN(vpd);
2969 }
2970
2971 static int vpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2972 {
2973         
2974         op->customdata = paint_stroke_new(C, NULL, vpaint_stroke_test_start,
2975                                           vpaint_stroke_update_step,
2976                                           vpaint_stroke_done, event->type);
2977         
2978         /* add modal handler */
2979         WM_event_add_modal_handler(C, op);
2980
2981         op->type->modal(C, op, event);
2982         
2983         return OPERATOR_RUNNING_MODAL;
2984 }
2985
2986 static int vpaint_cancel(bContext *C, wmOperator *op)
2987 {
2988         paint_stroke_cancel(C, op);
2989
2990         return OPERATOR_CANCELLED;
2991 }
2992
2993 void PAINT_OT_vertex_paint(wmOperatorType *ot)
2994 {
2995         /* identifiers */
2996         ot->name = "Vertex Paint";
2997         ot->idname = "PAINT_OT_vertex_paint";
2998         ot->description = "Paint a stroke in the active vertex color layer";
2999         
3000         /* api callbacks */
3001         ot->invoke = vpaint_invoke;
3002         ot->modal = paint_stroke_modal;
3003         /* ot->exec = vpaint_exec; <-- needs stroke property */
3004         ot->poll = vertex_paint_poll;
3005         ot->cancel = vpaint_cancel;
3006         
3007         /* flags */
3008         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
3009
3010         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
3011 }
3012
3013 /* ********************** weight from bones operator ******************* */
3014
3015 static int weight_from_bones_poll(bContext *C)
3016 {
3017         Object *ob = CTX_data_active_object(C);
3018
3019         return (ob && (ob->mode & OB_MODE_WEIGHT_PAINT) && mo