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