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