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