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