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