code cleanup: function naming, use BKE_*type* prefix.
[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 = get_mesh(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 = get_mesh(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         MLoop *ml = me->mloop;
263         MLoopCol *lcol = me->mloopcol;
264         MPoly *mp;
265         float (*scol)[4];
266         int i, j, has_shared = 0;
267
268         /* if no mloopcol: do not do */
269         /* if mtexpoly: only the involved faces, otherwise all */
270
271         if (me->mloopcol == 0 || me->totvert == 0 || me->totpoly == 0) return;
272
273         scol = MEM_callocN(sizeof(float) * me->totvert * 5, "scol");
274
275         for (i = 0, mp = me->mpoly; i < me->totpoly; i++, mp++) {
276                 if ((use_face_sel == FALSE) || (mp->flag & ME_FACE_SEL)) {
277                         ml = me->mloop + mp->loopstart;
278                         lcol = me->mloopcol + mp->loopstart;
279                         for (j = 0; j < mp->totloop; j++, ml++, lcol++) {
280                                 scol[ml->v][0] += lcol->r;
281                                 scol[ml->v][1] += lcol->g;
282                                 scol[ml->v][2] += lcol->b;
283                                 scol[ml->v][3] += 1.0f;
284                                 has_shared = 1;
285                         }
286                 }
287         }
288
289         if (has_shared) {
290                 for (i = 0; i < me->totvert; i++) {
291                         if (scol[i][3] != 0.0f) {
292                                 mul_v3_fl(scol[i], 1.0f / scol[i][3]);
293                         }
294                 }
295
296                 for (i = 0, mp = me->mpoly; i < me->totpoly; i++, mp++) {
297                         if ((use_face_sel == FALSE) || (mp->flag & ME_FACE_SEL)) {
298                                 ml = me->mloop + mp->loopstart;
299                                 lcol = me->mloopcol + mp->loopstart;
300                                 for (j = 0; j < mp->totloop; j++, ml++, lcol++) {
301                                         lcol->r = scol[ml->v][0];
302                                         lcol->g = scol[ml->v][1];
303                                         lcol->b = scol[ml->v][2];
304                                 }
305                         }
306                 }
307         }
308
309         MEM_freeN(scol);
310
311         if (has_shared && do_tessface) {
312                 do_shared_vertex_tesscol(me);
313         }
314 }
315
316 static void make_vertexcol(Object *ob)  /* single ob */
317 {
318         Mesh *me;
319         if (!ob || ob->id.lib) return;
320         me = get_mesh(ob);
321         if (me == NULL) return;
322         if (me->edit_btmesh) return;
323
324         /* copies from shadedisplist to mcol */
325         if (!me->mloopcol) {
326                 if (!me->mcol) {
327                         CustomData_add_layer(&me->fdata, CD_MCOL, CD_DEFAULT, NULL, me->totface);
328                 }
329                 if (!me->mloopcol) {
330                         CustomData_add_layer(&me->ldata, CD_MLOOPCOL, CD_DEFAULT, NULL, me->totloop);   
331                 }
332                 mesh_update_customdata_pointers(me, TRUE);
333         }
334
335         if (vertex_paint_use_tessface_check(ob)) {
336                 /* assume if these exist, that they are up to date & valid */
337                 if (!me->mcol || !me->mface) {
338                         /* should always be true */
339                         if (me->mcol) {
340                                 memset(me->mcol, 255, 4 * sizeof(MCol) * me->totface);
341                         }
342
343                         /* create tessfaces because they will be used for drawing & fast updates */
344                         BKE_mesh_tessface_calc(me); /* does own call to update pointers */
345                 }
346         }
347         else {
348                 if (me->totface) {
349                         /* this wont be used, theres no need to keep it */
350                         BKE_mesh_tessface_clear(me);
351                 }
352         }
353
354         //if (shade)
355         //      shadeMeshMCol(scene, ob, me);
356         //else
357         
358         DAG_id_tag_update(&me->id, 0);
359         
360 }
361
362 /* mirror_vgroup is set to -1 when invalid */
363 static int wpaint_mirror_vgroup_ensure(Object *ob, const int vgroup_active)
364 {
365         bDeformGroup *defgroup = BLI_findlink(&ob->defbase, vgroup_active);
366
367         if (defgroup) {
368                 bDeformGroup *curdef;
369                 int mirrdef;
370                 char name[MAXBONENAME];
371
372                 flip_side_name(name, defgroup->name, FALSE);
373
374                 if (strcmp(name, defgroup->name) != 0) {
375                         for (curdef = ob->defbase.first, mirrdef = 0; curdef; curdef = curdef->next, mirrdef++) {
376                                 if (!strcmp(curdef->name, name)) {
377                                         break;
378                                 }
379                         }
380
381                         if (curdef == NULL) {
382                                 int olddef = ob->actdef;  /* tsk, ED_vgroup_add sets the active defgroup */
383                                 curdef = ED_vgroup_add_name(ob, name);
384                                 ob->actdef = olddef;
385                         }
386
387                         /* curdef should never be NULL unless this is
388                          * a  lamp and ED_vgroup_add_name fails */
389                         if (curdef) {
390                                 return mirrdef;
391                         }
392                 }
393         }
394
395         return -1;
396 }
397
398 static void copy_vpaint_prev(VPaint *vp, unsigned int *lcol, int tot)
399 {
400         if (vp->vpaint_prev) {
401                 MEM_freeN(vp->vpaint_prev);
402                 vp->vpaint_prev = NULL;
403         }
404         vp->tot = tot;
405         
406         if (lcol == NULL || tot == 0) return;
407         
408         vp->vpaint_prev = MEM_mallocN(sizeof(int) * tot, "vpaint_prev");
409         memcpy(vp->vpaint_prev, lcol, sizeof(int) * tot);
410         
411 }
412
413 static void copy_wpaint_prev(VPaint *wp, MDeformVert *dverts, int dcount)
414 {
415         if (wp->wpaint_prev) {
416                 free_dverts(wp->wpaint_prev, wp->tot);
417                 wp->wpaint_prev = NULL;
418         }
419         
420         if (dverts && dcount) {
421                 
422                 wp->wpaint_prev = MEM_mallocN(sizeof(MDeformVert) * dcount, "wpaint prev");
423                 wp->tot = dcount;
424                 copy_dverts(wp->wpaint_prev, dverts, dcount);
425         }
426 }
427
428
429 void vpaint_fill(Object *ob, unsigned int paintcol)
430 {
431         Mesh *me;
432         MPoly *mp;
433         MLoopCol *lcol;
434         int i, j, selected;
435
436         me = get_mesh(ob);
437         if (me == NULL || me->totpoly == 0) return;
438
439         if (!me->mloopcol) make_vertexcol(ob);
440         if (!me->mloopcol) return;  /* possible we can't make mcol's */
441
442
443         selected = (me->editflag & ME_EDIT_PAINT_MASK);
444
445         mp = me->mpoly;
446         for (i = 0; i < me->totpoly; i++, mp++) {
447                 if (!(!selected || mp->flag & ME_FACE_SEL))
448                         continue;
449
450                 lcol = me->mloopcol + mp->loopstart;
451                 for (j = 0; j < mp->totloop; j++, lcol++) {
452                         *(int *)lcol = paintcol;
453                 }
454         }
455         
456         /* remove stale me->mcol, will be added later */
457         BKE_mesh_tessface_clear(me);
458
459         DAG_id_tag_update(&me->id, 0);
460 }
461
462
463 /* fills in the selected faces with the current weight and vertex group */
464 void wpaint_fill(VPaint *wp, Object *ob, float paintweight)
465 {
466         Mesh *me = ob->data;
467         MPoly *mp;
468         MDeformWeight *dw, *dw_prev;
469         int vgroup_active, vgroup_mirror = -1;
470         unsigned int index;
471
472         /* mutually exclusive, could be made into a */
473         const short paint_selmode = ME_EDIT_PAINT_SEL_MODE(me);
474
475         if (me->totpoly == 0 || me->dvert == NULL || !me->mpoly) return;
476         
477         vgroup_active = ob->actdef - 1;
478
479         /* if mirror painting, find the other group */
480         if (me->editflag & ME_EDIT_MIRROR_X) {
481                 vgroup_mirror = wpaint_mirror_vgroup_ensure(ob, vgroup_active);
482         }
483         
484         copy_wpaint_prev(wp, me->dvert, me->totvert);
485         
486         for (index = 0, mp = me->mpoly; index < me->totpoly; index++, mp++) {
487                 unsigned int fidx = mp->totloop - 1;
488
489                 if ((paint_selmode == SCE_SELECT_FACE) && !(mp->flag & ME_FACE_SEL)) {
490                         continue;
491                 }
492
493                 do {
494                         unsigned int vidx = me->mloop[mp->loopstart + fidx].v;
495
496                         if (!me->dvert[vidx].flag) {
497                                 if ((paint_selmode == SCE_SELECT_VERTEX) && !(me->mvert[vidx].flag & SELECT)) {
498                                         continue;
499                                 }
500
501                                 dw = defvert_verify_index(&me->dvert[vidx], vgroup_active);
502                                 if (dw) {
503                                         dw_prev = defvert_verify_index(wp->wpaint_prev + vidx, vgroup_active);
504                                         dw_prev->weight = dw->weight; /* set the undo weight */
505                                         dw->weight = paintweight;
506
507                                         if (me->editflag & ME_EDIT_MIRROR_X) {  /* x mirror painting */
508                                                 int j = mesh_get_x_mirror_vert(ob, vidx);
509                                                 if (j >= 0) {
510                                                         /* copy, not paint again */
511                                                         if (vgroup_mirror != -1) {
512                                                                 dw = defvert_verify_index(me->dvert + j, vgroup_mirror);
513                                                                 dw_prev = defvert_verify_index(wp->wpaint_prev + j, vgroup_mirror);
514                                                         }
515                                                         else {
516                                                                 dw = defvert_verify_index(me->dvert + j, vgroup_active);
517                                                                 dw_prev = defvert_verify_index(wp->wpaint_prev + j, vgroup_active);
518                                                         }
519                                                         dw_prev->weight = dw->weight; /* set the undo weight */
520                                                         dw->weight = paintweight;
521                                                 }
522                                         }
523                                 }
524                                 me->dvert[vidx].flag = 1;
525                         }
526
527                 } while (fidx--);
528         }
529
530         {
531                 MDeformVert *dv = me->dvert;
532                 for (index = me->totvert; index != 0; index--, dv++) {
533                         dv->flag = 0;
534                 }
535         }
536
537         copy_wpaint_prev(wp, NULL, 0);
538
539         DAG_id_tag_update(&me->id, 0);
540 }
541
542 /* XXX: should be re-implemented as a vertex/weight paint 'color correct' operator */
543 #if 0
544 void vpaint_dogamma(Scene *scene)
545 {
546         VPaint *vp = scene->toolsettings->vpaint;
547         Mesh *me;
548         Object *ob;
549         float igam, fac;
550         int a, temp;
551         unsigned char *cp, gamtab[256];
552
553         ob = OBACT;
554         me = get_mesh(ob);
555
556         if (!(ob->mode & OB_MODE_VERTEX_PAINT)) return;
557         if (me == 0 || me->mcol == 0 || me->totface == 0) return;
558
559         igam = 1.0 / vp->gamma;
560         for (a = 0; a < 256; a++) {
561
562                 fac = ((float)a) / 255.0;
563                 fac = vp->mul * pow(fac, igam);
564
565                 temp = 255.9 * fac;
566
567                 if (temp <= 0) gamtab[a] = 0;
568                 else if (temp >= 255) gamtab[a] = 255;
569                 else gamtab[a] = temp;
570         }
571
572         a = 4 * me->totface;
573         cp = (unsigned char *)me->mcol;
574         while (a--) {
575
576                 cp[1] = gamtab[cp[1]];
577                 cp[2] = gamtab[cp[2]];
578                 cp[3] = gamtab[cp[3]];
579
580                 cp += 4;
581         }
582 }
583 #endif
584
585 BLI_INLINE unsigned int mcol_blend(unsigned int col1, unsigned int col2, int fac)
586 {
587         unsigned char *cp1, *cp2, *cp;
588         int mfac;
589         unsigned int col = 0;
590
591         if (fac == 0) {
592                 return col1;
593         }
594
595         if (fac >= 255) {
596                 return col2;
597         }
598
599         mfac = 255 - fac;
600
601         cp1 = (unsigned char *)&col1;
602         cp2 = (unsigned char *)&col2;
603         cp  = (unsigned char *)&col;
604
605         cp[0] = (mfac * cp1[0] + fac * cp2[0]) / 255;
606         cp[1] = (mfac * cp1[1] + fac * cp2[1]) / 255;
607         cp[2] = (mfac * cp1[2] + fac * cp2[2]) / 255;
608         cp[3] = 255;
609
610         return col;
611 }
612
613 BLI_INLINE unsigned int mcol_add(unsigned int col1, unsigned int col2, int fac)
614 {
615         unsigned char *cp1, *cp2, *cp;
616         int temp;
617         unsigned int col = 0;
618
619         if (fac == 0) {
620                 return col1;
621         }
622
623         cp1 = (unsigned char *)&col1;
624         cp2 = (unsigned char *)&col2;
625         cp  = (unsigned char *)&col;
626
627         temp = cp1[0] + ((fac * cp2[0]) / 255);
628         cp[0] = (temp > 254) ? 255 : temp;
629         temp = cp1[1] + ((fac * cp2[1]) / 255);
630         cp[1] = (temp > 254) ? 255 : temp;
631         temp = cp1[2] + ((fac * cp2[2]) / 255);
632         cp[2] = (temp > 254) ? 255 : temp;
633         cp[3] = 255;
634         
635         return col;
636 }
637
638 BLI_INLINE unsigned int mcol_sub(unsigned int col1, unsigned int col2, int fac)
639 {
640         unsigned char *cp1, *cp2, *cp;
641         int temp;
642         unsigned int col = 0;
643
644         if (fac == 0) {
645                 return col1;
646         }
647
648         cp1 = (unsigned char *)&col1;
649         cp2 = (unsigned char *)&col2;
650         cp  = (unsigned char *)&col;
651
652         temp = cp1[0] - ((fac * cp2[0]) / 255);
653         cp1[0] = (temp < 0) ? 0 : temp;
654         temp = cp1[1] - ((fac * cp2[1]) / 255);
655         cp1[1] = (temp < 0) ? 0 : temp;
656         temp = cp1[2] - ((fac * cp2[2]) / 255);
657         cp1[2] = (temp < 0) ? 0 : temp;
658         cp[3] = 255;
659
660         return col;
661 }
662
663 BLI_INLINE unsigned int mcol_mul(unsigned int col1, unsigned int col2, int fac)
664 {
665         unsigned char *cp1, *cp2, *cp;
666         int mfac;
667         unsigned int col = 0;
668
669         if (fac == 0) {
670                 return col1;
671         }
672
673         mfac = 255 - fac;
674
675         cp1 = (unsigned char *)&col1;
676         cp2 = (unsigned char *)&col2;
677         cp  = (unsigned char *)&col;
678
679         /* first mul, then blend the fac */
680         cp[0] = (mfac * cp1[0] + fac * ((cp2[0] * cp1[0]) / 255)) / 255;
681         cp[1] = (mfac * cp1[1] + fac * ((cp2[1] * cp1[1]) / 255)) / 255;
682         cp[2] = (mfac * cp1[2] + fac * ((cp2[2] * cp1[2]) / 255)) / 255;
683         cp[3] = 255;
684
685         return col;
686 }
687
688 BLI_INLINE unsigned int mcol_lighten(unsigned int col1, unsigned int col2, int fac)
689 {
690         unsigned char *cp1, *cp2, *cp;
691         int mfac;
692         unsigned int col = 0;
693
694         if (fac == 0) {
695                 return col1;
696         }
697         else if (fac >= 255) {
698                 return col2;
699         }
700
701         mfac = 255 - fac;
702
703         cp1 = (unsigned char *)&col1;
704         cp2 = (unsigned char *)&col2;
705         cp  = (unsigned char *)&col;
706
707         /* See if are lighter, if so mix, else don't do anything.
708          * if the paint col is darker then the original, then ignore */
709         if (rgb_to_grayscale_byte(cp1) > rgb_to_grayscale_byte(cp2)) {
710                 return col1;
711         }
712
713         cp[0] = (mfac * cp1[0] + fac * cp2[0]) / 255;
714         cp[1] = (mfac * cp1[1] + fac * cp2[1]) / 255;
715         cp[2] = (mfac * cp1[2] + fac * cp2[2]) / 255;
716         cp[3] = 255;
717
718         return col;
719 }
720
721 BLI_INLINE unsigned int mcol_darken(unsigned int col1, unsigned int col2, int fac)
722 {
723         unsigned char *cp1, *cp2, *cp;
724         int mfac;
725         unsigned int col = 0;
726
727         if (fac == 0) {
728                 return col1;
729         }
730         else if (fac >= 255) {
731                 return col2;
732         }
733
734         mfac = 255 - fac;
735
736         cp1 = (unsigned char *)&col1;
737         cp2 = (unsigned char *)&col2;
738         cp  = (unsigned char *)&col;
739
740         /* See if were darker, if so mix, else don't do anything.
741          * if the paint col is brighter then the original, then ignore */
742         if (rgb_to_grayscale_byte(cp1) < rgb_to_grayscale_byte(cp2)) {
743                 return col1;
744         }
745
746         cp[0] = (mfac * cp1[0] + fac * cp2[0]) / 255;
747         cp[1] = (mfac * cp1[1] + fac * cp2[1]) / 255;
748         cp[2] = (mfac * cp1[2] + fac * cp2[2]) / 255;
749         cp[3] = 255;
750         return col;
751 }
752
753 /* wpaint has 'wpaint_blend_tool' */
754 static unsigned int vpaint_blend_tool(const int tool, const unsigned int col,
755                                       const unsigned int paintcol, const int alpha_i)
756 {
757         switch (tool) {
758                 case PAINT_BLEND_MIX:
759                 case PAINT_BLEND_BLUR:     return mcol_blend(col, paintcol, alpha_i);
760                 case PAINT_BLEND_ADD:      return mcol_add(col, paintcol, alpha_i);
761                 case PAINT_BLEND_SUB:      return mcol_sub(col, paintcol, alpha_i);
762                 case PAINT_BLEND_MUL:      return mcol_mul(col, paintcol, alpha_i);
763                 case PAINT_BLEND_LIGHTEN:  return mcol_lighten(col, paintcol, alpha_i);
764                 case PAINT_BLEND_DARKEN:   return mcol_darken(col, paintcol, alpha_i);
765                 default:
766                         BLI_assert(0);
767                         return 0;
768         }
769 }
770
771 /* wpaint has 'wpaint_blend' */
772 static unsigned int vpaint_blend(VPaint *vp, unsigned int col, unsigned int colorig, const
773                                  unsigned int paintcol, const int alpha_i,
774                                  /* pre scaled from [0-1] --> [0-255] */
775                                  const int brush_alpha_value_i)
776 {
777         Brush *brush = paint_brush(&vp->paint);
778         const int tool = brush->vertexpaint_tool;
779
780         col = vpaint_blend_tool(tool, col, paintcol, alpha_i);
781
782         /* if no spray, clip color adding with colorig & orig alpha */
783         if ((vp->flag & VP_SPRAY) == 0) {
784                 unsigned int testcol, a;
785                 char *cp, *ct, *co;
786                 
787                 testcol = vpaint_blend_tool(tool, colorig, paintcol, brush_alpha_value_i);
788                 
789                 cp = (char *)&col;
790                 ct = (char *)&testcol;
791                 co = (char *)&colorig;
792                 
793                 for (a = 0; a < 4; a++) {
794                         if (ct[a] < co[a]) {
795                                 if (cp[a] < ct[a]) cp[a] = ct[a];
796                                 else if (cp[a] > co[a]) cp[a] = co[a];
797                         }
798                         else {
799                                 if (cp[a] < co[a]) cp[a] = co[a];
800                                 else if (cp[a] > ct[a]) cp[a] = ct[a];
801                         }
802                 }
803         }
804
805         return col;
806 }
807
808
809 static int sample_backbuf_area(ViewContext *vc, int *indexar, int totface, int x, int y, float size)
810 {
811         struct ImBuf *ibuf;
812         int a, tot = 0, index;
813         
814         /* brecht: disabled this because it obviously fails for
815          * brushes with size > 64, why is this here? */
816         /*if (size > 64.0) size = 64.0;*/
817         
818         ibuf = view3d_read_backbuf(vc, x - size, y - size, x + size, y + size);
819         if (ibuf) {
820                 unsigned int *rt = ibuf->rect;
821
822                 memset(indexar, 0, sizeof(int) * (totface + 1));
823                 
824                 size = ibuf->x * ibuf->y;
825                 while (size--) {
826                                 
827                         if (*rt) {
828                                 index = WM_framebuffer_to_index(*rt);
829                                 if (index > 0 && index <= totface)
830                                         indexar[index] = 1;
831                         }
832                 
833                         rt++;
834                 }
835                 
836                 for (a = 1; a <= totface; a++) {
837                         if (indexar[a]) indexar[tot++] = a;
838                 }
839
840                 IMB_freeImBuf(ibuf);
841         }
842         
843         return tot;
844 }
845
846 /* whats _dl mean? */
847 static float calc_vp_strength_dl(VPaint *vp, ViewContext *vc, const float *vert_nor,
848                                  const float mval[2], const float brush_size_pressure)
849 {
850         Brush *brush = paint_brush(&vp->paint);
851         float dist_squared;
852         float vertco[2], delta[2];
853
854         project_float_noclip(vc->ar, vert_nor, vertco);
855         sub_v2_v2v2(delta, mval, vertco);
856         dist_squared = dot_v2v2(delta, delta); /* len squared */
857         if (dist_squared > brush_size_pressure * brush_size_pressure) {
858                 return 0.0f;
859         }
860         else {
861                 const float dist = sqrtf(dist_squared);
862                 return BKE_brush_curve_strength_clamp(brush, dist, brush_size_pressure);
863         }
864 }
865
866 static float calc_vp_alpha_dl(VPaint *vp, ViewContext *vc,
867                               float vpimat[][3], const float *vert_nor,
868                               const float mval[2],
869                               const float brush_size_pressure, const float brush_alpha_pressure)
870 {
871         float strength = calc_vp_strength_dl(vp, vc, vert_nor, mval, brush_size_pressure);
872
873         if (strength > 0.0f) {
874                 float alpha = brush_alpha_pressure * strength;
875
876                 if (vp->flag & VP_NORMALS) {
877                         float dvec[3];
878                         const float *no = vert_nor + 3;
879
880                         /* transpose ! */
881                         dvec[2] = dot_v3v3(vpimat[2], no);
882                         if (dvec[2] > 0.0f) {
883                                 dvec[0] = dot_v3v3(vpimat[0], no);
884                                 dvec[1] = dot_v3v3(vpimat[1], no);
885
886                                 alpha *= dvec[2] / len_v3(dvec);
887                         }
888                         else {
889                                 return 0.0f;
890                         }
891                 }
892
893                 return alpha;
894         }
895
896         return 0.0f;
897 }
898
899
900 BLI_INLINE float wval_blend(const float weight, const float paintval, const float alpha)
901 {
902         return (paintval * alpha) + (weight * (1.0f - alpha));
903 }
904 BLI_INLINE float wval_add(const float weight, const float paintval, const float alpha)
905 {
906         return weight + (paintval * alpha);
907 }
908 BLI_INLINE float wval_sub(const float weight, const float paintval, const float alpha)
909 {
910         return weight - (paintval * alpha);
911 }
912 BLI_INLINE float wval_mul(const float weight, const float paintval, const float alpha)
913 {   /* first mul, then blend the fac */
914         return ((1.0f - alpha) + (alpha * paintval)) * weight;
915 }
916 BLI_INLINE float wval_lighten(const float weight, const float paintval, const float alpha)
917 {
918         return (weight < paintval) ? wval_blend(weight, paintval, alpha) : weight;
919 }
920 BLI_INLINE float wval_darken(const float weight, const float paintval, const float alpha)
921 {
922         return (weight > paintval) ? wval_blend(weight, paintval, alpha) : weight;
923 }
924
925
926 /* vpaint has 'vpaint_blend_tool' */
927 /* result is not clamped from [0-1] */
928 static float wpaint_blend_tool(const int tool,
929                                /* dw->weight */
930                                const float weight,
931                                const float paintval, const float alpha)
932 {
933         switch (tool) {
934                 case PAINT_BLEND_MIX:
935                 case PAINT_BLEND_BLUR:     return wval_blend(weight, paintval, alpha);
936                 case PAINT_BLEND_ADD:      return wval_add(weight, paintval, alpha);
937                 case PAINT_BLEND_SUB:      return wval_sub(weight, paintval, alpha);
938                 case PAINT_BLEND_MUL:      return wval_mul(weight, paintval, alpha);
939                 case PAINT_BLEND_LIGHTEN:  return wval_lighten(weight, paintval, alpha);
940                 case PAINT_BLEND_DARKEN:   return wval_darken(weight, paintval, alpha);
941                 default:
942                         BLI_assert(0);
943                         return 0.0f;
944         }
945 }
946
947 /* vpaint has 'vpaint_blend' */
948 static float wpaint_blend(VPaint *wp, float weight, float weight_prev,
949                           const float alpha, float paintval,
950                           const float brush_alpha_value,
951                           const short do_flip, const short do_multipaint_totsel)
952 {
953         Brush *brush = paint_brush(&wp->paint);
954         int tool = brush->vertexpaint_tool;
955
956         if (do_flip) {
957                 switch (tool) {
958                         case PAINT_BLEND_MIX:
959                                 paintval = 1.f - paintval; break;
960                         case PAINT_BLEND_ADD:
961                                 tool = PAINT_BLEND_SUB; break;
962                         case PAINT_BLEND_SUB:
963                                 tool = PAINT_BLEND_ADD; break;
964                         case PAINT_BLEND_LIGHTEN:
965                                 tool = PAINT_BLEND_DARKEN; break;
966                         case PAINT_BLEND_DARKEN:
967                                 tool = PAINT_BLEND_LIGHTEN; break;
968                 }
969         }
970         
971         weight = wpaint_blend_tool(tool, weight, paintval, alpha);
972
973         /* delay clamping until the end so multi-paint can function when the active group is at the limits */
974         if (do_multipaint_totsel == FALSE) {
975                 CLAMP(weight, 0.0f, 1.0f);
976         }
977         
978         /* if no spray, clip result with orig weight & orig alpha */
979         if ((wp->flag & VP_SPRAY) == 0) {
980                 if (do_multipaint_totsel == FALSE) {
981                         float testw = wpaint_blend_tool(tool, weight_prev, paintval, brush_alpha_value);
982
983                         CLAMP(testw, 0.0f, 1.0f);
984                         if (testw < weight_prev) {
985                                 if (weight < testw) weight = testw;
986                                 else if (weight > weight_prev) weight = weight_prev;
987                         }
988                         else {
989                                 if (weight > testw) weight = testw;
990                                 else if (weight < weight_prev) weight = weight_prev;
991                         }
992                 }
993         }
994
995         return weight;
996 }
997
998 /* ----------------------------------------------------- */
999
1000
1001 /* sets wp->weight to the closest weight value to vertex */
1002 /* note: we cant sample frontbuf, weight colors are interpolated too unpredictable */
1003 static int weight_sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
1004 {
1005         ViewContext vc;
1006         Mesh *me;
1007         short change = FALSE;
1008
1009         view3d_set_viewcontext(C, &vc);
1010         me = get_mesh(vc.obact);
1011
1012         if (me && me->dvert && vc.v3d && vc.rv3d) {
1013                 int index;
1014
1015                 view3d_operator_needs_opengl(C);
1016
1017                 index = view3d_sample_backbuf(&vc, event->mval[0], event->mval[1]);
1018
1019                 if (index && index <= me->totpoly) {
1020                         DerivedMesh *dm = mesh_get_derived_final(vc.scene, vc.obact, CD_MASK_BAREMESH);
1021
1022                         if (dm->getVertCo == NULL) {
1023                                 BKE_report(op->reports, RPT_WARNING, "The modifier used does not support deformed locations");
1024                         }
1025                         else {
1026                                 MPoly *mp = ((MPoly *)me->mpoly) + (index - 1);
1027                                 const int vgroup_active = vc.obact->actdef - 1;
1028                                 Scene *scene = vc.scene;
1029                                 ToolSettings *ts = vc.scene->toolsettings;
1030                                 Brush *brush = paint_brush(&ts->wpaint->paint);
1031                                 float mval_f[2];
1032                                 int v_idx_best = -1;
1033                                 int fidx;
1034                                 float len_best = FLT_MAX;
1035
1036                                 mval_f[0] = (float)event->mval[0];
1037                                 mval_f[1] = (float)event->mval[1];
1038
1039                                 fidx = mp->totloop - 1;
1040                                 do {
1041                                         float co[3], sco[3], len;
1042                                         const int v_idx = me->mloop[mp->loopstart + fidx].v;
1043                                         dm->getVertCo(dm, v_idx, co);
1044                                         project_float_noclip(vc.ar, co, sco);
1045                                         len = len_squared_v2v2(mval_f, sco);
1046                                         if (len < len_best) {
1047                                                 len_best = len;
1048                                                 v_idx_best = v_idx;
1049                                         }
1050                                 } while (fidx--);
1051
1052                                 if (v_idx_best != -1) { /* should always be valid */
1053                                         float vgroup_weight = defvert_find_weight(&me->dvert[v_idx_best], vgroup_active);
1054                                         BKE_brush_weight_set(scene, brush, vgroup_weight);
1055                                         change = TRUE;
1056                                 }
1057                         }
1058                         dm->release(dm);
1059                 }
1060         }
1061
1062         if (change) {
1063                 /* not really correct since the brush didnt change, but redraws the toolbar */
1064                 WM_main_add_notifier(NC_BRUSH | NA_EDITED, NULL); /* ts->wpaint->paint.brush */
1065
1066                 return OPERATOR_FINISHED;
1067         }
1068         else {
1069                 return OPERATOR_CANCELLED;
1070         }
1071 }
1072
1073 void PAINT_OT_weight_sample(wmOperatorType *ot)
1074 {
1075         /* identifiers */
1076         ot->name = "Weight Paint Sample Weight";
1077         ot->idname = "PAINT_OT_weight_sample";
1078
1079         /* api callbacks */
1080         ot->invoke = weight_sample_invoke;
1081         ot->poll = weight_paint_mode_poll;
1082
1083         /* flags */
1084         ot->flag = OPTYPE_UNDO;
1085 }
1086
1087 /* samples cursor location, and gives menu with vertex groups to activate */
1088 static EnumPropertyItem *weight_paint_sample_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), int *free)
1089 {
1090         if (C) {
1091                 wmWindow *win = CTX_wm_window(C);
1092                 if (win && win->eventstate) {
1093                         ViewContext vc;
1094                         Mesh *me;
1095
1096                         view3d_set_viewcontext(C, &vc);
1097                         me = get_mesh(vc.obact);
1098
1099                         if (me && me->dvert && vc.v3d && vc.rv3d) {
1100                                 int index;
1101
1102                                 view3d_operator_needs_opengl(C);
1103
1104                                 index = view3d_sample_backbuf(&vc, win->eventstate->x - vc.ar->winrct.xmin, win->eventstate->y - vc.ar->winrct.ymin);
1105
1106                                 if (index && index <= me->totpoly) {
1107                                         const int defbase_tot = BLI_countlist(&vc.obact->defbase);
1108                                         if (defbase_tot) {
1109                                                 MPoly *mp = ((MPoly *)me->mpoly) + (index - 1);
1110                                                 unsigned int fidx = mp->totloop - 1;
1111                                                 int *groups = MEM_callocN(defbase_tot * sizeof(int), "groups");
1112                                                 int found = FALSE;
1113
1114                                                 do {
1115                                                         MDeformVert *dvert = me->dvert + me->mloop[mp->loopstart + fidx].v;
1116                                                         int i = dvert->totweight;
1117                                                         MDeformWeight *dw;
1118                                                         for (dw = dvert->dw; i > 0; dw++, i--) {
1119                                                                 if (dw->def_nr < defbase_tot) {
1120                                                                         groups[dw->def_nr] = TRUE;
1121                                                                         found = TRUE;
1122                                                                 }
1123                                                         }
1124                                                 } while (fidx--);
1125
1126                                                 if (found == FALSE) {
1127                                                         MEM_freeN(groups);
1128                                                 }
1129                                                 else {
1130                                                         EnumPropertyItem *item = NULL, item_tmp = {0};
1131                                                         int totitem = 0;
1132                                                         int i = 0;
1133                                                         bDeformGroup *dg;
1134                                                         for (dg = vc.obact->defbase.first; dg && i < defbase_tot; i++, dg = dg->next) {
1135                                                                 if (groups[i]) {
1136                                                                         item_tmp.identifier = item_tmp.name = dg->name;
1137                                                                         item_tmp.value = i;
1138                                                                         RNA_enum_item_add(&item, &totitem, &item_tmp);
1139                                                                 }
1140                                                         }
1141
1142                                                         RNA_enum_item_end(&item, &totitem);
1143                                                         *free = 1;
1144
1145                                                         MEM_freeN(groups);
1146                                                         return item;
1147                                                 }
1148                                         }
1149                                 }
1150                         }
1151                 }
1152         }
1153
1154         return DummyRNA_NULL_items;
1155 }
1156
1157 static int weight_sample_group_exec(bContext *C, wmOperator *op)
1158 {
1159         int type = RNA_enum_get(op->ptr, "group");
1160         ViewContext vc;
1161         view3d_set_viewcontext(C, &vc);
1162
1163         BLI_assert(type + 1 >= 0);
1164         vc.obact->actdef = type + 1;
1165
1166         DAG_id_tag_update(&vc.obact->id, OB_RECALC_DATA);
1167         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, vc.obact);
1168         return OPERATOR_FINISHED;
1169 }
1170
1171 /* TODO, we could make this a menu into OBJECT_OT_vertex_group_set_active rather than its own operator */
1172 void PAINT_OT_weight_sample_group(wmOperatorType *ot)
1173 {
1174         PropertyRNA *prop = NULL;
1175
1176         /* identifiers */
1177         ot->name = "Weight Paint Sample Group";
1178         ot->idname = "PAINT_OT_weight_sample_group";
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 immediatelty 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 ensuyre 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 = get_mesh(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         
2042         /* api callbacks */
2043         ot->exec = set_wpaint;
2044         ot->poll = paint_poll_test;
2045         
2046         /* flags */
2047         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2048         
2049 }
2050
2051 /* ************ weight paint operator ********** */
2052
2053 struct WPaintData {
2054         ViewContext vc;
2055         int *indexar;
2056         int vgroup_active;
2057         int vgroup_mirror;
2058         float *vertexcosnos;
2059         float wpimat[3][3];
2060         
2061         /* variables for auto normalize */
2062         const char *vgroup_validmap; /* stores if vgroups tie to deforming bones or not */
2063         const char *lock_flags;
2064         int defbase_tot;
2065 };
2066
2067 static char *wpaint_make_validmap(Object *ob)
2068 {
2069         bDeformGroup *dg;
2070         ModifierData *md;
2071         char *vgroup_validmap;
2072         GHash *gh;
2073         int i, step1 = 1;
2074
2075         if (ob->defbase.first == NULL) {
2076                 return NULL;
2077         }
2078
2079         gh = BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp, "wpaint_make_validmap gh");
2080
2081         /* add all names to a hash table */
2082         for (dg = ob->defbase.first; dg; dg = dg->next) {
2083                 BLI_ghash_insert(gh, dg->name, NULL);
2084         }
2085
2086         /* now loop through the armature modifiers and identify deform bones */
2087         for (md = ob->modifiers.first; md; md = !md->next && step1 ? (step1 = 0), modifiers_getVirtualModifierList(ob) : md->next) {
2088                 if (!(md->mode & (eModifierMode_Realtime | eModifierMode_Virtual)))
2089                         continue;
2090
2091                 if (md->type == eModifierType_Armature) {
2092                         ArmatureModifierData *amd = (ArmatureModifierData *) md;
2093
2094                         if (amd->object && amd->object->pose) {
2095                                 bPose *pose = amd->object->pose;
2096                                 bPoseChannel *chan;
2097                                 
2098                                 for (chan = pose->chanbase.first; chan; chan = chan->next) {
2099                                         if (chan->bone->flag & BONE_NO_DEFORM)
2100                                                 continue;
2101
2102                                         if (BLI_ghash_haskey(gh, chan->name)) {
2103                                                 BLI_ghash_remove(gh, chan->name, NULL, NULL);
2104                                                 BLI_ghash_insert(gh, chan->name, SET_INT_IN_POINTER(1));
2105                                         }
2106                                 }
2107                         }
2108                 }
2109         }
2110
2111         vgroup_validmap = MEM_mallocN(BLI_ghash_size(gh), "wpaint valid map");
2112
2113         /* add all names to a hash table */
2114         for (dg = ob->defbase.first, i = 0; dg; dg = dg->next, i++) {
2115                 vgroup_validmap[i] = (BLI_ghash_lookup(gh, dg->name) != NULL);
2116         }
2117
2118         BLI_assert(i == BLI_ghash_size(gh));
2119
2120         BLI_ghash_free(gh, NULL, NULL);
2121
2122         return vgroup_validmap;
2123 }
2124
2125 static int wpaint_stroke_test_start(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2126 {
2127         Scene *scene = CTX_data_scene(C);
2128         struct PaintStroke *stroke = op->customdata;
2129         ToolSettings *ts = scene->toolsettings;
2130         VPaint *wp = ts->wpaint;
2131         Object *ob = CTX_data_active_object(C);
2132         struct WPaintData *wpd;
2133         Mesh *me;
2134         bDeformGroup *dg;
2135
2136         float mat[4][4], imat[4][4];
2137         
2138         if (scene->obedit) {
2139                 return FALSE;
2140         }
2141         
2142         me = get_mesh(ob);
2143         if (me == NULL || me->totpoly == 0) return OPERATOR_PASS_THROUGH;
2144         
2145         /* if nothing was added yet, we make dverts and a vertex deform group */
2146         if (!me->dvert) {
2147                 ED_vgroup_data_create(&me->id);
2148                 WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
2149         }
2150
2151         /* this happens on a Bone select, when no vgroup existed yet */
2152         if (ob->actdef <= 0) {
2153                 Object *modob;
2154                 if ((modob = modifiers_isDeformedByArmature(ob))) {
2155                         Bone *actbone = ((bArmature *)modob->data)->act_bone;
2156                         if (actbone) {
2157                                 bPoseChannel *pchan = get_pose_channel(modob->pose, actbone->name);
2158
2159                                 if (pchan) {
2160                                         bDeformGroup *dg = defgroup_find_name(ob, pchan->name);
2161                                         if (dg == NULL) {
2162                                                 dg = ED_vgroup_add_name(ob, pchan->name);  /* sets actdef */
2163                                         }
2164                                         else {
2165                                                 int actdef = 1 + BLI_findindex(&ob->defbase, dg);
2166                                                 BLI_assert(actdef >= 0);
2167                                                 ob->actdef = actdef;
2168                                         }
2169                                 }
2170                         }
2171                 }
2172         }
2173         if (ob->defbase.first == NULL) {
2174                 ED_vgroup_add(ob);
2175         }
2176
2177         /* ensure we don't try paint onto an invalid group */
2178         if (ob->actdef <= 0) {
2179                 BKE_report(op->reports, RPT_WARNING, "No active vertex group for painting, aborting");
2180                 return FALSE;
2181         }
2182
2183         /* check if we are attempting to paint onto a locked vertex group,
2184          * and other options disallow it from doing anything useful */
2185         dg = BLI_findlink(&ob->defbase, (ob->actdef - 1));
2186         if (dg->flag & DG_LOCK_WEIGHT) {
2187                 BKE_report(op->reports, RPT_WARNING, "Active group is locked, aborting");
2188                 return FALSE;
2189         }
2190
2191         /* ALLOCATIONS! no return after this line */
2192         /* make mode data storage */
2193         wpd = MEM_callocN(sizeof(struct WPaintData), "WPaintData");
2194         paint_stroke_set_mode_data(stroke, wpd);
2195         view3d_set_viewcontext(C, &wpd->vc);
2196
2197         wpd->vgroup_active = ob->actdef - 1;
2198         wpd->vgroup_mirror = -1;
2199
2200         /* set up auto-normalize, and generate map for detecting which
2201          * vgroups affect deform bones */
2202         wpd->defbase_tot = BLI_countlist(&ob->defbase);
2203         wpd->lock_flags = gen_lock_flags(ob, wpd->defbase_tot);
2204         if (ts->auto_normalize || ts->multipaint || wpd->lock_flags) {
2205                 wpd->vgroup_validmap = wpaint_make_validmap(ob);
2206         }
2207
2208         /* painting on subsurfs should give correct points too, this returns me->totvert amount */
2209         wpd->vertexcosnos = mesh_get_mapped_verts_nors(scene, ob);
2210         wpd->indexar = get_indexarray(me);
2211         copy_wpaint_prev(wp, me->dvert, me->totvert);
2212
2213         /* imat for normals */
2214         mult_m4_m4m4(mat, wpd->vc.rv3d->viewmat, ob->obmat);
2215         invert_m4_m4(imat, mat);
2216         copy_m3_m4(wpd->wpimat, imat);
2217
2218         /* if mirror painting, find the other group */
2219         if (me->editflag & ME_EDIT_MIRROR_X) {
2220                 wpd->vgroup_mirror = wpaint_mirror_vgroup_ensure(ob, wpd->vgroup_active);
2221         }
2222         
2223         return TRUE;
2224 }
2225
2226 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2227 {
2228         Scene *scene = CTX_data_scene(C);
2229         ToolSettings *ts = CTX_data_tool_settings(C);
2230         VPaint *wp = ts->wpaint;
2231         Brush *brush = paint_brush(&wp->paint);
2232         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2233         ViewContext *vc;
2234         Object *ob;
2235         Mesh *me;
2236         float mat[4][4];
2237         float paintweight;
2238         int *indexar;
2239         float totw;
2240         unsigned int index, totindex;
2241         float alpha;
2242         float mval[2];
2243         int use_vert_sel;
2244         char *defbase_sel;
2245
2246         const float pressure = RNA_float_get(itemptr, "pressure");
2247         const float brush_size_pressure = BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2248         const float brush_alpha_value = BKE_brush_alpha_get(scene, brush);
2249         const float brush_alpha_pressure = brush_alpha_value * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2250
2251         /* intentionally don't initialize as NULL, make sure we initialize all members below */
2252         WeightPaintInfo wpi;
2253
2254         /* cannot paint if there is no stroke data */
2255         if (wpd == NULL) {
2256                 /* XXX: force a redraw here, since even though we can't paint,
2257                  * at least view won't freeze until stroke ends */
2258                 ED_region_tag_redraw(CTX_wm_region(C));
2259                 return;
2260         }
2261                 
2262         vc = &wpd->vc;
2263         ob = vc->obact;
2264         me = ob->data;
2265         indexar = wpd->indexar;
2266         
2267         view3d_operator_needs_opengl(C);
2268                 
2269         /* load projection matrix */
2270         mult_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2271
2272         RNA_float_get_array(itemptr, "mouse", mval);
2273         mval[0] -= vc->ar->winrct.xmin;
2274         mval[1] -= vc->ar->winrct.ymin;
2275
2276
2277
2278         /* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
2279         wpi.defbase_tot =        wpd->defbase_tot;
2280         defbase_sel =            MEM_mallocN(wpi.defbase_tot * sizeof(char), "wpi.defbase_sel");
2281         wpi.defbase_tot_sel =    get_selected_defgroups(ob, defbase_sel, wpi.defbase_tot);
2282         wpi.defbase_sel =        defbase_sel; /* so we can stay const */
2283         if (wpi.defbase_tot_sel == 0 && ob->actdef > 0) wpi.defbase_tot_sel = 1;
2284
2285         wpi.defbase_tot_unsel =  wpi.defbase_tot - wpi.defbase_tot_sel;
2286         wpi.vgroup_active =      wpd->vgroup_active;
2287         wpi.vgroup_mirror =      wpd->vgroup_mirror;
2288         wpi.lock_flags =         wpd->lock_flags;
2289         wpi.vgroup_validmap =    wpd->vgroup_validmap;
2290         wpi.do_flip =            RNA_boolean_get(itemptr, "pen_flip");
2291         wpi.do_multipaint =      (ts->multipaint != 0);
2292         wpi.do_auto_normalize =  ((ts->auto_normalize != 0) && (wpi.vgroup_validmap != NULL));
2293         wpi.brush_alpha_value =  brush_alpha_value;
2294         /* *** done setting up WeightPaintInfo *** */
2295
2296
2297
2298         swap_m4m4(wpd->vc.rv3d->persmat, mat);
2299
2300         use_vert_sel = (me->editflag & ME_EDIT_VERT_SEL) != 0;
2301
2302         /* which faces are involved */
2303         if (wp->flag & VP_AREA) {
2304                 /* Ugly hack, to avoid drawing vertex index when getting the face index buffer - campbell */
2305                 me->editflag &= ~ME_EDIT_VERT_SEL;
2306                 totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2307                 me->editflag |= use_vert_sel ? ME_EDIT_VERT_SEL : 0;
2308         }
2309         else {
2310                 indexar[0] = view3d_sample_backbuf(vc, mval[0], mval[1]);
2311                 if (indexar[0]) totindex = 1;
2312                 else totindex = 0;
2313         }
2314                         
2315         if (wp->flag & VP_COLINDEX) {
2316                 for (index = 0; index < totindex; index++) {
2317                         if (indexar[index] && indexar[index] <= me->totpoly) {
2318                                 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2319                                                 
2320                                 if (mpoly->mat_nr != ob->actcol - 1) {
2321                                         indexar[index] = 0;
2322                                 }
2323                         }
2324                 }
2325         }
2326                         
2327         if ((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
2328                 for (index = 0; index < totindex; index++) {
2329                         if (indexar[index] && indexar[index] <= me->totpoly) {
2330                                 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2331                                                 
2332                                 if ((mpoly->flag & ME_FACE_SEL) == 0) {
2333                                         indexar[index] = 0;
2334                                 }
2335                         }
2336                 }
2337         }
2338
2339         /* make sure each vertex gets treated only once */
2340         /* and calculate filter weight */
2341         totw = 0.0f;
2342         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR)
2343                 paintweight = 0.0f;
2344         else
2345                 paintweight = BKE_brush_weight_get(scene, brush);
2346                         
2347         for (index = 0; index < totindex; index++) {
2348                 if (indexar[index] && indexar[index] <= me->totpoly) {
2349                         MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2350                         MLoop *ml = me->mloop + mpoly->loopstart;
2351                         int i;
2352
2353                         if (use_vert_sel) {
2354                                 for (i = 0; i < mpoly->totloop; i++, ml++) {
2355                                         me->dvert[ml->v].flag = (me->mvert[ml->v].flag & SELECT);
2356                                 }
2357                         }
2358                         else {
2359                                 for (i = 0; i < mpoly->totloop; i++, ml++) {
2360                                         me->dvert[ml->v].flag = 1;
2361                                 }
2362                         }
2363                                         
2364                         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2365                                 MDeformWeight *dw, *(*dw_func)(MDeformVert *, const int);
2366                                                 
2367                                 if (wp->flag & VP_ONLYVGROUP)
2368                                         dw_func = (MDeformWeight *(*)(MDeformVert *, const int))defvert_find_index;
2369                                 else
2370                                         dw_func = defvert_verify_index;
2371                                                 
2372                                 ml = me->mloop + mpoly->loopstart;
2373                                 for (i = 0; i < mpoly->totloop; i++, ml++) {
2374                                         unsigned int vidx = ml->v;
2375                                         const float fac = calc_vp_strength_dl(wp, vc, wpd->vertexcosnos + 6 * vidx, mval, brush_size_pressure);
2376                                         if (fac > 0.0f) {
2377                                                 dw = dw_func(&me->dvert[vidx], wpi.vgroup_active);
2378                                                 paintweight += dw ? (dw->weight * fac) : 0.0f;
2379                                                 totw += fac;
2380                                         }
2381                                 }
2382                         }
2383                 }
2384         }
2385                         
2386         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2387                 paintweight /= totw;
2388         }
2389
2390         for (index = 0; index < totindex; index++) {
2391
2392                 if (indexar[index] && indexar[index] <= me->totpoly) {
2393                         MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2394                         MLoop *ml = me->mloop + mpoly->loopstart;
2395                         int i;
2396
2397                         for (i = 0; i < mpoly->totloop; i++, ml++) {
2398                                 unsigned int vidx = ml->v;
2399
2400                                 if (me->dvert[vidx].flag) {
2401                                         alpha = calc_vp_alpha_dl(wp, vc, wpd->wpimat, wpd->vertexcosnos + 6 * vidx,
2402                                                                  mval, brush_size_pressure, brush_alpha_pressure);
2403                                         if (alpha) {
2404                                                 do_weight_paint_vertex(wp, ob, &wpi, vidx, alpha, paintweight);
2405                                         }
2406                                         me->dvert[vidx].flag = 0;
2407                                 }
2408                         }
2409                 }
2410         }
2411
2412
2413         /* *** free wpi members */
2414         MEM_freeN((void *)wpi.defbase_sel);
2415         /* *** don't freeing wpi members */
2416
2417
2418         swap_m4m4(vc->rv3d->persmat, mat);
2419                         
2420         DAG_id_tag_update(ob->data, 0);
2421         ED_region_tag_redraw(vc->ar);
2422 }
2423
2424 static void wpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2425 {
2426         ToolSettings *ts = CTX_data_tool_settings(C);
2427         Object *ob = CTX_data_active_object(C);
2428         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2429         
2430         if (wpd) {
2431                 if (wpd->vertexcosnos)
2432                         MEM_freeN(wpd->vertexcosnos);
2433                 MEM_freeN(wpd->indexar);
2434                 
2435                 if (wpd->vgroup_validmap)
2436                         MEM_freeN((void *)wpd->vgroup_validmap);
2437                 if (wpd->lock_flags)
2438                         MEM_freeN((void *)wpd->lock_flags);
2439
2440                 MEM_freeN(wpd);
2441         }
2442         
2443         /* frees prev buffer */
2444         copy_wpaint_prev(ts->wpaint, NULL, 0);
2445         
2446         /* and particles too */
2447         if (ob->particlesystem.first) {
2448                 ParticleSystem *psys;
2449                 int i;
2450                 
2451                 for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2452                         for (i = 0; i < PSYS_TOT_VG; i++) {
2453                                 if (psys->vgroup[i] == ob->actdef) {
2454                                         psys->recalc |= PSYS_RECALC_RESET;
2455                                         break;
2456                                 }
2457                         }
2458                 }
2459         }
2460         
2461         DAG_id_tag_update(ob->data, 0);
2462 }
2463
2464
2465 static int wpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2466 {
2467         
2468         op->customdata = paint_stroke_new(C, NULL, wpaint_stroke_test_start,
2469                                           wpaint_stroke_update_step,
2470                                           wpaint_stroke_done, event->type);
2471         
2472         /* add modal handler */
2473         WM_event_add_modal_handler(C, op);
2474
2475         op->type->modal(C, op, event);
2476         
2477         return OPERATOR_RUNNING_MODAL;
2478 }
2479
2480 static int wpaint_cancel(bContext *C, wmOperator *op)
2481 {
2482         paint_stroke_cancel(C, op);
2483
2484         return OPERATOR_CANCELLED;
2485 }
2486
2487 void PAINT_OT_weight_paint(wmOperatorType *ot)
2488 {
2489         
2490         /* identifiers */
2491         ot->name = "Weight Paint";
2492         ot->idname = "PAINT_OT_weight_paint";
2493         
2494         /* api callbacks */
2495         ot->invoke = wpaint_invoke;
2496         ot->modal = paint_stroke_modal;
2497         /* ot->exec = vpaint_exec; <-- needs stroke property */
2498         ot->poll = weight_paint_poll;
2499         ot->cancel = wpaint_cancel;
2500         
2501         /* flags */
2502         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
2503
2504         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2505 }
2506
2507 static int weight_paint_set_exec(bContext *C, wmOperator *UNUSED(op))
2508 {
2509         struct Scene *scene = CTX_data_scene(C);
2510         Object *obact = CTX_data_active_object(C);
2511         ToolSettings *ts = CTX_data_tool_settings(C);
2512         Brush *brush = paint_brush(&ts->wpaint->paint);
2513         float vgroup_weight = BKE_brush_weight_get(scene, brush);
2514
2515         wpaint_fill(scene->toolsettings->wpaint, obact, vgroup_weight);
2516         ED_region_tag_redraw(CTX_wm_region(C)); /* XXX - should redraw all 3D views */
2517         return OPERATOR_FINISHED;
2518 }
2519
2520 void PAINT_OT_weight_set(wmOperatorType *ot)
2521 {
2522         /* identifiers */
2523         ot->name = "Set Weight";
2524         ot->idname = "PAINT_OT_weight_set";
2525
2526         /* api callbacks */
2527         ot->exec = weight_paint_set_exec;
2528         ot->poll = mask_paint_poll; /* it was facemask_paint_poll */
2529
2530         /* flags */
2531         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2532 }
2533
2534 /* ************ set / clear vertex paint mode ********** */
2535
2536
2537 static int set_vpaint(bContext *C, wmOperator *op)  /* toggle */
2538 {       
2539         Object *ob = CTX_data_active_object(C);
2540         Scene *scene = CTX_data_scene(C);
2541         VPaint *vp = scene->toolsettings->vpaint;
2542         Mesh *me;
2543         
2544         me = get_mesh(ob);
2545         
2546         if (me == NULL || BKE_object_obdata_is_libdata(ob)) {
2547                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2548                 return OPERATOR_PASS_THROUGH;
2549         }
2550         
2551         if (me && me->mloopcol == NULL) {
2552                 make_vertexcol(ob);
2553         }
2554         
2555         /* toggle: end vpaint */
2556         if (ob->mode & OB_MODE_VERTEX_PAINT) {
2557                 
2558                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2559         }
2560         else {
2561                 ob->mode |= OB_MODE_VERTEX_PAINT;
2562                 /* Turn off weight painting */
2563                 if (ob->mode & OB_MODE_WEIGHT_PAINT)
2564                         set_wpaint(C, op);
2565                 
2566                 if (vp == NULL)
2567                         vp = scene->toolsettings->vpaint = new_vpaint(0);
2568                 
2569                 paint_cursor_start(C, vertex_paint_poll);
2570
2571                 paint_init(&vp->paint, PAINT_CURSOR_VERTEX_PAINT);
2572         }
2573         
2574         if (me)
2575                 /* update modifier stack for mapping requirements */
2576                 DAG_id_tag_update(&me->id, 0);
2577         
2578         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
2579         
2580         return OPERATOR_FINISHED;
2581 }
2582
2583 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2584 {
2585         
2586         /* identifiers */
2587         ot->name = "Vertex Paint Mode";
2588         ot->idname = "PAINT_OT_vertex_paint_toggle";
2589         
2590         /* api callbacks */
2591         ot->exec = set_vpaint;
2592         ot->poll = paint_poll_test;
2593         
2594         /* flags */
2595         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2596 }
2597
2598
2599
2600 /* ********************** vertex paint operator ******************* */
2601
2602 /* Implementation notes:
2603  *
2604  * Operator->invoke()
2605  * - validate context (add mcol)
2606  * - create customdata storage
2607  * - call paint once (mouse click)
2608  * - add modal handler 
2609  *
2610  * Operator->modal()
2611  * - for every mousemove, apply vertex paint
2612  * - exit on mouse release, free customdata
2613  *   (return OPERATOR_FINISHED also removes handler and operator)
2614  *
2615  * For future:
2616  * - implement a stroke event (or mousemove with past positons)
2617  * - revise whether op->customdata should be added in object, in set_vpaint
2618  */
2619
2620 typedef struct polyfacemap_e {
2621         struct polyfacemap_e *next, *prev;
2622         int facenr;
2623 } polyfacemap_e;
2624
2625 typedef struct VPaintData {
2626         ViewContext vc;
2627         unsigned int paintcol;
2628         int *indexar;
2629         float *vertexcosnos;
2630         float vpimat[3][3];
2631
2632         /* modify 'me->mcol' directly, since the derived mesh is drawing from this array,
2633          * otherwise we need to refresh the modifier stack */
2634         int use_fast_update;
2635
2636         /* mpoly -> mface mapping */
2637         MemArena *polyfacemap_arena;
2638         ListBase *polyfacemap;
2639 } VPaintData;
2640
2641 static void vpaint_build_poly_facemap(struct VPaintData *vd, Mesh *me)
2642 {
2643         MFace *mf;
2644         polyfacemap_e *e;
2645         int *origIndex;
2646         int i;
2647
2648         vd->polyfacemap_arena = BLI_memarena_new(1 << 13, "vpaint tmp");
2649         BLI_memarena_use_calloc(vd->polyfacemap_arena);
2650
2651         vd->polyfacemap = BLI_memarena_alloc(vd->polyfacemap_arena, sizeof(ListBase) * me->totpoly);
2652
2653         origIndex = CustomData_get_layer(&me->fdata, CD_POLYINDEX);
2654         mf = me->mface;
2655
2656         if (!origIndex)
2657                 return;
2658
2659         for (i = 0; i < me->totface; i++, mf++, origIndex++) {
2660                 if (*origIndex == ORIGINDEX_NONE)
2661                         continue;
2662
2663                 e = BLI_memarena_alloc(vd->polyfacemap_arena, sizeof(polyfacemap_e));
2664                 e->facenr = i;
2665                 
2666                 BLI_addtail(&vd->polyfacemap[*origIndex], e);
2667         }
2668 }
2669
2670 static int vpaint_stroke_test_start(bContext *C, struct wmOperator *op, wmEvent *UNUSED(event))
2671 {
2672         ToolSettings *ts = CTX_data_tool_settings(C);
2673         struct PaintStroke *stroke = op->customdata;
2674         VPaint *vp = ts->vpaint;
2675         struct VPaintData *vpd;
2676         Object *ob = CTX_data_active_object(C);
2677         Mesh *me;
2678         float mat[4][4], imat[4][4];
2679
2680         /* context checks could be a poll() */
2681         me = get_mesh(ob);
2682         if (me == NULL || me->totpoly == 0)
2683                 return OPERATOR_PASS_THROUGH;
2684         
2685         if (me->mloopcol == NULL)
2686                 make_vertexcol(ob);
2687         if (me->mloopcol == NULL)
2688                 return OPERATOR_CANCELLED;
2689         
2690         /* make mode data storage */
2691         vpd = MEM_callocN(sizeof(struct VPaintData), "VPaintData");
2692         paint_stroke_set_mode_data(stroke, vpd);
2693         view3d_set_viewcontext(C, &vpd->vc);
2694         
2695         vpd->vertexcosnos = mesh_get_mapped_verts_nors(vpd->vc.scene, ob);
2696         vpd->indexar = get_indexarray(me);
2697         vpd->paintcol = vpaint_get_current_col(vp);
2698
2699
2700         /* are we painting onto a modified mesh?,
2701          * if not we can skip face map trickyness */
2702         if (vertex_paint_use_fast_update_check(ob)) {
2703                 vpaint_build_poly_facemap(vpd, me);
2704                 vpd->use_fast_update = TRUE;
2705         }
2706         else {
2707                 vpd->use_fast_update = FALSE;
2708         }
2709
2710         /* for filtering */
2711         copy_vpaint_prev(vp, (unsigned int *)me->mloopcol, me->totloop);
2712         
2713         /* some old cruft to sort out later */
2714         mult_m4_m4m4(mat, vpd->vc.rv3d->viewmat, ob->obmat);
2715         invert_m4_m4(imat, mat);
2716         copy_m3_m4(vpd->vpimat, imat);
2717
2718         return 1;
2719 }
2720
2721 #if 0
2722 static void vpaint_paint_face(VPaint *vp, VPaintData *vpd, Object *ob,
2723                               const unsigned int index, const float mval[2],
2724                               const float brush_size_pressure, const float brush_alpha_pressure,
2725                               int UNUSED(flip))
2726 {
2727         ViewContext *vc = &vpd->vc;
2728         Brush *brush = paint_brush(&vp->paint);
2729         Mesh *me = get_mesh(ob);
2730         MFace *mface = &me->mface[index];
2731         unsigned int *mcol = ((unsigned int *)me->mcol) + 4 * index;
2732         unsigned int *mcolorig = ((unsigned int *)vp->vpaint_prev) + 4 * index;
2733         float alpha;
2734         int i;
2735
2736         int brush_alpha_pressure_i;
2737         
2738         if ((vp->flag & VP_COLINDEX && mface->mat_nr != ob->actcol - 1) ||
2739             ((me->editflag & ME_EDIT_PAINT_MASK) && !(mface->flag & ME_FACE_SEL)))
2740                 return;
2741
2742         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2743                 unsigned int fcol1 = mcol_blend(mcol[0], mcol[1], 128);
2744                 if (mface->v4) {
2745                         unsigned int fcol2 = mcol_blend(mcol[2], mcol[3], 128);
2746                         vpd->paintcol = mcol_blend(fcol1, fcol2, 128);
2747                 }
2748                 else {
2749                         vpd->paintcol = mcol_blend(mcol[2], fcol1, 170);
2750                 }
2751         }
2752
2753         brush_alpha_pressure_i = (int)(brush_alpha_pressure * 255.0f);
2754
2755         for (i = 0; i < (mface->v4 ? 4 : 3); ++i) {
2756                 alpha = calc_vp_alpha_dl(vp, vc, vpd->vpimat, vpd->vertexcosnos + 6 * (&mface->v1)[i],
2757                                          mval, brush_size_pressure, brush_alpha_pressure);
2758                 if (alpha) {
2759                         const int alpha_i = (int)(alpha * 255.0f);
2760                         mcol[i] = vpaint_blend(vp, mcol[i], mcolorig[i], vpd->paintcol, alpha_i, brush_alpha_pressure_i);
2761                 }
2762         }
2763 }
2764 #endif
2765
2766 /* BMESH version of vpaint_paint_face (commented above) */
2767
2768 static void vpaint_paint_poly(VPaint *vp, VPaintData *vpd, Object *ob,
2769                               const unsigned int index, const float mval[2],
2770                               const float brush_size_pressure, const float brush_alpha_pressure)
2771 {
2772         ViewContext *vc = &vpd->vc;
2773         Brush *brush = paint_brush(&vp->paint);
2774         Mesh *me = get_mesh(ob);
2775         MPoly *mpoly = &me->mpoly[index];
2776         MFace *mf;
2777         MCol *mc;
2778         MLoop *ml;
2779         MLoopCol *mlc;
2780         polyfacemap_e *e;
2781         unsigned int *lcol = ((unsigned int *)me->mloopcol) + mpoly->loopstart;
2782         unsigned int *lcolorig = ((unsigned int *)vp->vpaint_prev) + mpoly->loopstart;
2783         float alpha;
2784         int i, j;
2785
2786         int brush_alpha_pressure_i = (int)(brush_alpha_pressure * 255.0f);
2787
2788         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2789                 unsigned int blend[4] = {0};
2790                 unsigned int tcol;
2791                 char *col;
2792
2793                 for (j = 0; j < mpoly->totloop; j++) {
2794                         col = (char *)(lcol + j);
2795                         blend[0] += col[0];
2796                         blend[1] += col[1];
2797                         blend[2] += col[2];
2798                         blend[3] += col[3];
2799                 }
2800
2801                 blend[0] /= mpoly->totloop;
2802                 blend[1] /= mpoly->totloop;
2803                 blend[2] /= mpoly->totloop;
2804                 blend[3] /= mpoly->totloop;
2805                 col = (char *)&tcol;
2806                 col[0] = blend[0];
2807                 col[1] = blend[1];
2808                 col[2] = blend[2];
2809                 col[3] = blend[3];
2810
2811                 vpd->paintcol = *((unsigned int *)col);
2812         }
2813
2814         ml = me->mloop + mpoly->loopstart;
2815         for (i = 0; i < mpoly->totloop; i++, ml++) {
2816                 alpha = calc_vp_alpha_dl(vp, vc, vpd->vpimat,
2817                                          vpd->vertexcosnos + 6 * ml->v, mval,
2818                                          brush_size_pressure, brush_alpha_pressure);
2819                 if (alpha > 0.0f) {
2820                         const int alpha_i = (int)(alpha * 255.0f);
2821                         lcol[i] = vpaint_blend(vp, lcol[i], lcolorig[i], vpd->paintcol, alpha_i, brush_alpha_pressure_i);
2822                 }
2823         }
2824
2825         if (vpd->use_fast_update) {
2826
2827 #ifdef CPYCOL
2828 #  undef CPYCOL
2829 #endif
2830 #define CPYCOL(c, l) (c)->a = (l)->a, (c)->r = (l)->r, (c)->g = (l)->g, (c)->b = (l)->b
2831
2832                 /* update vertex colors for tessellations incrementally,
2833                  * rather then regenerating the tessellation altogether */
2834                 for (e = vpd->polyfacemap[index].first; e; e = e->next) {
2835                         mf = me->mface + e->facenr;
2836                         mc = me->mcol + e->facenr * 4;
2837
2838                         ml = me->mloop + mpoly->loopstart;
2839                         mlc = me->mloopcol + mpoly->loopstart;
2840                         for (j = 0; j < mpoly->totloop; j++, ml++, mlc++) {
2841                                 if (ml->v == mf->v1)
2842                                         CPYCOL(mc, mlc);
2843                                 else if (ml->v == mf->v2)
2844                                         CPYCOL(mc + 1, mlc);
2845                                 else if (ml->v == mf->v3)
2846                                         CPYCOL(mc + 2, mlc);
2847                                 else if (mf->v4 && ml->v == mf->v4)
2848                                         CPYCOL(mc + 3, mlc);
2849
2850                         }
2851                 }
2852 #undef CPYCOL
2853         }
2854
2855 }
2856
2857 static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2858 {
2859         Scene *scene = CTX_data_scene(C);
2860         ToolSettings *ts = CTX_data_tool_settings(C);
2861         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2862         VPaint *vp = ts->vpaint;
2863         Brush *brush = paint_brush(&vp->paint);
2864         ViewContext *vc = &vpd->vc;
2865         Object *ob = vc->obact;
2866         Mesh *me = ob->data;
2867         float mat[4][4];
2868         int *indexar = vpd->indexar;
2869         int totindex, index;
2870         float mval[2];
2871
2872         const float pressure = RNA_float_get(itemptr, "pressure");
2873         const float brush_size_pressure = BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2874         const float brush_alpha_pressure = BKE_brush_alpha_get(scene, brush) * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2875
2876         RNA_float_get_array(itemptr, "mouse", mval);
2877
2878         view3d_operator_needs_opengl(C);
2879                         
2880         /* load projection matrix */
2881         mult_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2882
2883         mval[0] -= vc->ar->winrct.xmin;
2884         mval[1] -= vc->ar->winrct.ymin;
2885
2886                         
2887         /* which faces are involved */
2888         if (vp->flag & VP_AREA) {
2889                 totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2890         }
2891         else {
2892                 indexar[0] = view3d_sample_backbuf(vc, mval[0], mval[1]);
2893                 if (indexar[0]) totindex = 1;
2894                 else totindex = 0;
2895         }
2896                         
2897                         
2898         if (vp->flag & VP_COLINDEX) {
2899                 for (index = 0; index < totindex; index++) {
2900                         if (indexar[index] && indexar[index] <= me->totpoly) {
2901                                 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2902                                                 
2903                                 if (mpoly->mat_nr != ob->actcol - 1) {
2904                                         indexar[index] = 0;
2905                                 }
2906                         }
2907                 }
2908         }
2909
2910         if ((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
2911                 for (index = 0; index < totindex; index++) {
2912                         if (indexar[index] && indexar[index] <= me->totpoly) {
2913                                 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2914                                                 
2915                                 if ((mpoly->flag & ME_FACE_SEL) == 0)
2916                                         indexar[index] = 0;
2917                         }                                       
2918                 }
2919         }
2920         
2921         swap_m4m4(vc->rv3d->persmat, mat);
2922
2923                         
2924         for (index = 0; index < totindex; index++) {
2925                                 
2926                 if (indexar[index] && indexar[index] <= me->totpoly) {
2927                         vpaint_paint_poly(vp, vpd, ob, indexar[index] - 1, mval, brush_size_pressure, brush_alpha_pressure);
2928                 }
2929         }
2930                 
2931         swap_m4m4(vc->rv3d->persmat, mat);
2932
2933         /* was disabled because it is slow, but necessary for blur */
2934         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2935                 int do_tessface = vpd->use_fast_update;
2936                 do_shared_vertexcol(me, do_tessface);
2937         }
2938
2939         ED_region_tag_redraw(vc->ar);
2940
2941         if (vpd->use_fast_update == FALSE) {
2942                 /* recalculate modifier stack to get new colors, slow,
2943                  * avoid this if we can! */
2944                 DAG_id_tag_update(ob->data, 0);
2945         }
2946 }
2947
2948 static void vpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2949 {
2950         ToolSettings *ts = CTX_data_tool_settings(C);
2951         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2952         
2953         if (vpd->vertexcosnos)
2954                 MEM_freeN(vpd->vertexcosnos);
2955         MEM_freeN(vpd->indexar);
2956         
2957         /* frees prev buffer */
2958         copy_vpaint_prev(ts->vpaint, NULL, 0);
2959
2960         if (vpd->polyfacemap_arena) {
2961                 BLI_memarena_free(vpd->polyfacemap_arena);
2962         }
2963
2964         MEM_freeN(vpd);
2965 }
2966
2967 static int vpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2968 {
2969         
2970         op->customdata = paint_stroke_new(C, NULL, vpaint_stroke_test_start,
2971                                           vpaint_stroke_update_step,
2972                                           vpaint_stroke_done, event->type);
2973         
2974         /* add modal handler */
2975         WM_event_add_modal_handler(C, op);
2976
2977         op->type->modal(C, op, event);
2978         
2979         return OPERATOR_RUNNING_MODAL;
2980 }
2981
2982 static int vpaint_cancel(bContext *C, wmOperator *op)
2983 {
2984         paint_stroke_cancel(C, op);
2985
2986         return OPERATOR_CANCELLED;
2987 }
2988
2989 void PAINT_OT_vertex_paint(wmOperatorType *ot)
2990 {
2991         /* identifiers */
2992         ot->name = "Vertex Paint";
2993         ot->idname = "PAINT_OT_vertex_paint";
2994         
2995         /* api callbacks */
2996         ot->invoke = vpaint_invoke;
2997         ot->modal = paint_stroke_modal;
2998         /* ot->exec = vpaint_exec; <-- needs stroke property */
2999         ot->poll = vertex_paint_poll;
3000         ot->cancel = vpaint_cancel;
3001         
3002         /* flags */
3003         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
3004
3005         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
3006 }
3007
3008 /* ********************** weight from bones operator ******************* */
3009
3010 static int weight_from_bones_poll(bContext *C)
3011 {
3012         Object *ob = CTX_data_active_object(C);
3013
3014         return (ob && (ob->mode & OB_MODE_WEIGHT_PAINT) && modifiers_isDeformedByArmature(ob));
3015 }
3016
3017 static int weight_from_bones_exec(bContext *C, wmOperator *op)
3018 {
3019         Scene *scene = CTX_data_scene(C);
3020         Object *ob = CTX_data_active_object(C);
3021         Object *armob = modifiers_isDeformedByArmature(ob);
3022         Mesh *me = ob->data;
3023         int type = RNA_enum_get(op->ptr, "type");
3024
3025         create_vgroups_from_armature(op->reports, scene, ob, armob, type, (me->editflag & ME_EDIT_MIRROR_X));
3026
3027         DAG_id_tag_update(&me->id, 0);