Merged from trunk with revision range 36835-37865,
[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_action.h"
68 #include "BKE_brush.h"
69 #include "BKE_context.h"
70 #include "BKE_depsgraph.h"
71 #include "BKE_deform.h"
72 #include "BKE_mesh.h"
73 #include "BKE_modifier.h"
74 #include "BKE_object.h"
75 #include "BKE_paint.h"
76 #include "BKE_report.h"
77
78
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 /* fills in the selected faces with the current weight and vertex group */
390 void wpaint_fill(VPaint *wp, Object *ob, float paintweight)
391 {
392         Mesh *me;
393         MFace *mface;
394         MDeformWeight *dw, *uw;
395         int *indexar;
396         int index, vgroup;
397         unsigned int faceverts[5]={0,0,0,0,0};
398         unsigned char i;
399         int vgroup_mirror= -1;
400         int selected;
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         indexar= get_indexarray(me);
408
409         if(selected) {
410                 for(index=0, mface=me->mface; index<me->totface; index++, mface++) {
411                         if((mface->flag & ME_FACE_SEL)==0)
412                                 indexar[index]= 0;
413                         else
414                                 indexar[index]= index+1;
415                 }
416         }
417         else {
418                 for(index=0; index<me->totface; index++)
419                         indexar[index]= index+1;
420         }
421         
422         vgroup= ob->actdef-1;
423
424         /* if mirror painting, find the other group */          
425         if(me->editflag & ME_EDIT_MIRROR_X) {
426                 wpaint_mirror_vgroup_ensure(ob, &vgroup_mirror);
427         }
428         
429         copy_wpaint_prev(wp, me->dvert, me->totvert);
430         
431         for(index=0; index<me->totface; index++) {
432                 if(indexar[index] && indexar[index]<=me->totface) {
433                         mface= me->mface + (indexar[index]-1);
434                         /* just so we can loop through the verts */
435                         faceverts[0]= mface->v1;
436                         faceverts[1]= mface->v2;
437                         faceverts[2]= mface->v3;
438                         faceverts[3]= mface->v4;
439                         for (i=0; i<3 || faceverts[i]; i++) {
440                                 if(!((me->dvert+faceverts[i])->flag)) {
441                                         dw= defvert_verify_index(me->dvert+faceverts[i], vgroup);
442                                         if(dw) {
443                                                 uw= defvert_verify_index(wp->wpaint_prev+faceverts[i], vgroup);
444                                                 uw->weight= dw->weight; /* set the undo weight */
445                                                 dw->weight= paintweight;
446                                                 
447                                                 if(me->editflag & ME_EDIT_MIRROR_X) {   /* x mirror painting */
448                                                         int j= mesh_get_x_mirror_vert(ob, faceverts[i]);
449                                                         if(j>=0) {
450                                                                 /* copy, not paint again */
451                                                                 if(vgroup_mirror != -1) {
452                                                                         dw= defvert_verify_index(me->dvert+j, vgroup_mirror);
453                                                                         uw= defvert_verify_index(wp->wpaint_prev+j, vgroup_mirror);
454                                                                 } else {
455                                                                         dw= defvert_verify_index(me->dvert+j, vgroup);
456                                                                         uw= defvert_verify_index(wp->wpaint_prev+j, vgroup);
457                                                                 }
458                                                                 uw->weight= dw->weight; /* set the undo weight */
459                                                                 dw->weight= paintweight;
460                                                         }
461                                                 }
462                                         }
463                                         (me->dvert+faceverts[i])->flag= 1;
464                                 }
465                         }
466                 }
467         }
468         
469         index=0;
470         while (index<me->totvert) {
471                 (me->dvert+index)->flag= 0;
472                 index++;
473         }
474         
475         MEM_freeN(indexar);
476         copy_wpaint_prev(wp, NULL, 0);
477
478         DAG_id_tag_update(&me->id, 0);
479 }
480
481 /* XXX: should be re-implemented as a vertex/weight paint 'color correct' operator
482  
483 void vpaint_dogamma(Scene *scene)
484 {
485         VPaint *vp= scene->toolsettings->vpaint;
486         Mesh *me;
487         Object *ob;
488         float igam, fac;
489         int a, temp;
490         unsigned char *cp, gamtab[256];
491
492         ob= OBACT;
493         me= get_mesh(ob);
494
495         if(!(ob->mode & OB_MODE_VERTEX_PAINT)) return;
496         if(me==0 || me->mcol==0 || me->totface==0) return;
497
498         igam= 1.0/vp->gamma;
499         for(a=0; a<256; a++) {
500                 
501                 fac= ((float)a)/255.0;
502                 fac= vp->mul*pow( fac, igam);
503                 
504                 temp= 255.9*fac;
505                 
506                 if(temp<=0) gamtab[a]= 0;
507                 else if(temp>=255) gamtab[a]= 255;
508                 else gamtab[a]= temp;
509         }
510
511         a= 4*me->totface;
512         cp= (unsigned char *)me->mcol;
513         while(a--) {
514                 
515                 cp[1]= gamtab[ cp[1] ];
516                 cp[2]= gamtab[ cp[2] ];
517                 cp[3]= gamtab[ cp[3] ];
518                 
519                 cp+= 4;
520         }
521 }
522  */
523
524 static unsigned int mcol_blend(unsigned int col1, unsigned int col2, int fac)
525 {
526         char *cp1, *cp2, *cp;
527         int mfac;
528         unsigned int col=0;
529         
530         if(fac==0) return col1;
531         if(fac>=255) return col2;
532
533         mfac= 255-fac;
534         
535         cp1= (char *)&col1;
536         cp2= (char *)&col2;
537         cp=  (char *)&col;
538         
539         cp[0]= 255;
540         cp[1]= (mfac*cp1[1]+fac*cp2[1])/255;
541         cp[2]= (mfac*cp1[2]+fac*cp2[2])/255;
542         cp[3]= (mfac*cp1[3]+fac*cp2[3])/255;
543         
544         return col;
545 }
546
547 static unsigned int mcol_add(unsigned int col1, unsigned int col2, int fac)
548 {
549         char *cp1, *cp2, *cp;
550         int temp;
551         unsigned int col=0;
552         
553         if(fac==0) return col1;
554         
555         cp1= (char *)&col1;
556         cp2= (char *)&col2;
557         cp=  (char *)&col;
558         
559         cp[0]= 255;
560         temp= cp1[1] + ((fac*cp2[1])/255);
561         if(temp>254) cp[1]= 255; else cp[1]= temp;
562         temp= cp1[2] + ((fac*cp2[2])/255);
563         if(temp>254) cp[2]= 255; else cp[2]= temp;
564         temp= cp1[3] + ((fac*cp2[3])/255);
565         if(temp>254) cp[3]= 255; else cp[3]= temp;
566         
567         return col;
568 }
569
570 static unsigned int mcol_sub(unsigned int col1, unsigned int col2, int fac)
571 {
572         char *cp1, *cp2, *cp;
573         int temp;
574         unsigned int col=0;
575         
576         if(fac==0) return col1;
577         
578         cp1= (char *)&col1;
579         cp2= (char *)&col2;
580         cp=  (char *)&col;
581         
582         cp[0]= 255;
583         temp= cp1[1] - ((fac*cp2[1])/255);
584         if(temp<0) cp[1]= 0; else cp[1]= temp;
585         temp= cp1[2] - ((fac*cp2[2])/255);
586         if(temp<0) cp[2]= 0; else cp[2]= temp;
587         temp= cp1[3] - ((fac*cp2[3])/255);
588         if(temp<0) cp[3]= 0; else cp[3]= temp;
589         
590         return col;
591 }
592
593 static unsigned int mcol_mul(unsigned int col1, unsigned int col2, int fac)
594 {
595         char *cp1, *cp2, *cp;
596         int mfac;
597         unsigned int col=0;
598         
599         if(fac==0) return col1;
600
601         mfac= 255-fac;
602         
603         cp1= (char *)&col1;
604         cp2= (char *)&col2;
605         cp=  (char *)&col;
606         
607         /* first mul, then blend the fac */
608         cp[0]= 255;
609         cp[1]= (mfac*cp1[1] + fac*((cp2[1]*cp1[1])/255)  )/255;
610         cp[2]= (mfac*cp1[2] + fac*((cp2[2]*cp1[2])/255)  )/255;
611         cp[3]= (mfac*cp1[3] + fac*((cp2[3]*cp1[3])/255)  )/255;
612
613         
614         return col;
615 }
616
617 static unsigned int mcol_lighten(unsigned int col1, unsigned int col2, int fac)
618 {
619         char *cp1, *cp2, *cp;
620         int mfac;
621         unsigned int col=0;
622         
623         if(fac==0) return col1;
624         if(fac>=255) return col2;
625
626         mfac= 255-fac;
627         
628         cp1= (char *)&col1;
629         cp2= (char *)&col2;
630         cp=  (char *)&col;
631         
632         /* See if are lighter, if so mix, else dont do anything.
633         if the paint col is darker then the original, then ignore */
634         if (cp1[1]+cp1[2]+cp1[3] > cp2[1]+cp2[2]+cp2[3])
635                 return col1;
636         
637         cp[0]= 255;
638         cp[1]= (mfac*cp1[1]+fac*cp2[1])/255;
639         cp[2]= (mfac*cp1[2]+fac*cp2[2])/255;
640         cp[3]= (mfac*cp1[3]+fac*cp2[3])/255;
641         
642         return col;
643 }
644
645 static unsigned int mcol_darken(unsigned int col1, unsigned int col2, int fac)
646 {
647         char *cp1, *cp2, *cp;
648         int mfac;
649         unsigned int col=0;
650         
651         if(fac==0) return col1;
652         if(fac>=255) return col2;
653
654         mfac= 255-fac;
655         
656         cp1= (char *)&col1;
657         cp2= (char *)&col2;
658         cp=  (char *)&col;
659         
660         /* See if were darker, if so mix, else dont do anything.
661         if the paint col is brighter then the original, then ignore */
662         if (cp1[1]+cp1[2]+cp1[3] < cp2[1]+cp2[2]+cp2[3])
663                 return col1;
664         
665         cp[0]= 255;
666         cp[1]= (mfac*cp1[1]+fac*cp2[1])/255;
667         cp[2]= (mfac*cp1[2]+fac*cp2[2])/255;
668         cp[3]= (mfac*cp1[3]+fac*cp2[3])/255;
669         return col;
670 }
671
672 static void vpaint_blend(VPaint *vp, unsigned int *col, unsigned int *colorig, unsigned int paintcol, int alpha)
673 {
674         Brush *brush = paint_brush(&vp->paint);
675
676         if(brush->vertexpaint_tool==VP_MIX || brush->vertexpaint_tool==VP_BLUR) *col= mcol_blend( *col, paintcol, alpha);
677         else if(brush->vertexpaint_tool==VP_ADD) *col= mcol_add( *col, paintcol, alpha);
678         else if(brush->vertexpaint_tool==VP_SUB) *col= mcol_sub( *col, paintcol, alpha);
679         else if(brush->vertexpaint_tool==VP_MUL) *col= mcol_mul( *col, paintcol, alpha);
680         else if(brush->vertexpaint_tool==VP_LIGHTEN) *col= mcol_lighten( *col, paintcol, alpha);
681         else if(brush->vertexpaint_tool==VP_DARKEN) *col= mcol_darken( *col, paintcol, alpha);
682         
683         /* if no spray, clip color adding with colorig & orig alpha */
684         if((vp->flag & VP_SPRAY)==0) {
685                 unsigned int testcol=0, a;
686                 char *cp, *ct, *co;
687                 
688                 alpha= (int)(255.0f*brush_alpha(brush));
689                 
690                 if(brush->vertexpaint_tool==VP_MIX || brush->vertexpaint_tool==VP_BLUR) testcol= mcol_blend( *colorig, paintcol, alpha);
691                 else if(brush->vertexpaint_tool==VP_ADD) testcol= mcol_add( *colorig, paintcol, alpha);
692                 else if(brush->vertexpaint_tool==VP_SUB) testcol= mcol_sub( *colorig, paintcol, alpha);
693                 else if(brush->vertexpaint_tool==VP_MUL) testcol= mcol_mul( *colorig, paintcol, alpha);
694                 else if(brush->vertexpaint_tool==VP_LIGHTEN)  testcol= mcol_lighten( *colorig, paintcol, alpha);
695                 else if(brush->vertexpaint_tool==VP_DARKEN)   testcol= mcol_darken( *colorig, paintcol, alpha);
696                 
697                 cp= (char *)col;
698                 ct= (char *)&testcol;
699                 co= (char *)colorig;
700                 
701                 for(a=0; a<4; a++) {
702                         if( ct[a]<co[a] ) {
703                                 if( cp[a]<ct[a] ) cp[a]= ct[a];
704                                 else if( cp[a]>co[a] ) cp[a]= co[a];
705                         }
706                         else {
707                                 if( cp[a]<co[a] ) cp[a]= co[a];
708                                 else if( cp[a]>ct[a] ) cp[a]= ct[a];
709                         }
710                 }
711         }
712 }
713
714
715 static int sample_backbuf_area(ViewContext *vc, int *indexar, int totface, int x, int y, float size)
716 {
717         struct ImBuf *ibuf;
718         int a, tot=0, index;
719         
720         /* brecht: disabled this because it obviously failes for
721            brushes with size > 64, why is this here? */
722         /*if(size>64.0) size= 64.0;*/
723         
724         ibuf= view3d_read_backbuf(vc, x-size, y-size, x+size, y+size);
725         if(ibuf) {
726                 unsigned int *rt= ibuf->rect;
727
728                 memset(indexar, 0, sizeof(int)*(totface+1));
729                 
730                 size= ibuf->x*ibuf->y;
731                 while(size--) {
732                                 
733                         if(*rt) {
734                                 index= WM_framebuffer_to_index(*rt);
735                                 if(index>0 && index<=totface)
736                                         indexar[index] = 1;
737                         }
738                 
739                         rt++;
740                 }
741                 
742                 for(a=1; a<=totface; a++) {
743                         if(indexar[a]) indexar[tot++]= a;
744                 }
745
746                 IMB_freeImBuf(ibuf);
747         }
748         
749         return tot;
750 }
751
752 static float calc_vp_alpha_dl(VPaint *vp, ViewContext *vc, float vpimat[][3], float *vert_nor, const float mval[2], float pressure)
753 {
754         Brush *brush = paint_brush(&vp->paint);
755         float fac, fac_2, size, dx, dy;
756         float alpha;
757         int vertco[2];
758         const int radius= brush_size(brush);
759
760         project_int_noclip(vc->ar, vert_nor, vertco);
761         dx= mval[0]-vertco[0];
762         dy= mval[1]-vertco[1];
763         
764         if (brush_use_size_pressure(brush))
765                 size = pressure * radius;
766         else
767                 size = radius;
768         
769         fac_2= dx*dx + dy*dy;
770         if(fac_2 > size*size) return 0.f;
771         fac = sqrtf(fac_2);
772         
773         alpha= brush_alpha(brush) * brush_curve_strength_clamp(brush, fac, size);
774         
775         if (brush_use_alpha_pressure(brush))
776                 alpha *= pressure;
777                 
778         if(vp->flag & VP_NORMALS) {
779                 float *no= vert_nor+3;
780                 
781                 /* transpose ! */
782                 fac= vpimat[2][0]*no[0]+vpimat[2][1]*no[1]+vpimat[2][2]*no[2];
783                 if(fac > 0.0f) {
784                         dx= vpimat[0][0]*no[0]+vpimat[0][1]*no[1]+vpimat[0][2]*no[2];
785                         dy= vpimat[1][0]*no[0]+vpimat[1][1]*no[1]+vpimat[1][2]*no[2];
786                         
787                         alpha*= fac/sqrtf(dx*dx + dy*dy + fac*fac);
788                 }
789                 else return 0.f;
790         }
791         
792         return alpha;
793 }
794
795 static void wpaint_blend(VPaint *wp, MDeformWeight *dw, MDeformWeight *uw, float alpha, float paintval, int flip)
796 {
797         Brush *brush = paint_brush(&wp->paint);
798         int tool = brush->vertexpaint_tool;
799         
800         if(dw==NULL || uw==NULL) return;
801         
802         if (flip) {
803                 switch(tool) {
804                         case VP_MIX:
805                                 paintval = 1.f - paintval; break;
806                         case VP_ADD:
807                                 tool= VP_SUB; break;
808                         case VP_SUB:
809                                 tool= VP_ADD; break;
810                         case VP_LIGHTEN:
811                                 tool= VP_DARKEN; break;
812                         case VP_DARKEN:
813                                 tool= VP_LIGHTEN; break;
814                 }
815         }
816         
817         if(tool==VP_MIX || tool==VP_BLUR)
818                 dw->weight = paintval*alpha + dw->weight*(1.0f-alpha);
819         else if(tool==VP_ADD)
820                 dw->weight += paintval*alpha;
821         else if(tool==VP_SUB) 
822                 dw->weight -= paintval*alpha;
823         else if(tool==VP_MUL) 
824                 /* first mul, then blend the fac */
825                 dw->weight = ((1.0f-alpha) + alpha*paintval)*dw->weight;
826         else if(tool==VP_LIGHTEN) {
827                 if (dw->weight < paintval)
828                         dw->weight = paintval*alpha + dw->weight*(1.0f-alpha);
829         } else if(tool==VP_DARKEN) {
830                 if (dw->weight > paintval)
831                         dw->weight = paintval*alpha + dw->weight*(1.0f-alpha);
832         }
833         // Jason delay clamping until the end so multi-paint can function when the active group is at the limits
834         //CLAMP(dw->weight, 0.0f, 1.0f);
835         
836         /* if no spray, clip result with orig weight & orig alpha */
837         if((wp->flag & VP_SPRAY)==0) {
838                 float testw=0.0f;
839                 
840                 alpha= brush_alpha(brush);
841                 if(tool==VP_MIX || tool==VP_BLUR)
842                         testw = paintval*alpha + uw->weight*(1.0f-alpha);
843                 else if(tool==VP_ADD)
844                         testw = uw->weight + paintval*alpha;
845                 else if(tool==VP_SUB) 
846                         testw = uw->weight - paintval*alpha;
847                 else if(tool==VP_MUL) 
848                         /* first mul, then blend the fac */
849                         testw = ((1.0f-alpha) + alpha*paintval)*uw->weight;
850                 else if(tool==VP_LIGHTEN) {
851                         if (uw->weight < paintval)
852                                 testw = paintval*alpha + uw->weight*(1.0f-alpha);
853                         else
854                                 testw = uw->weight;
855                 } else if(tool==VP_DARKEN) {
856                         if (uw->weight > paintval)
857                                 testw = paintval*alpha + uw->weight*(1.0f-alpha);
858                         else
859                                 testw = uw->weight;
860                 }
861                 //CLAMP(testw, 0.0f, 1.0f);
862                 
863                 if( testw<uw->weight ) {
864                         if(dw->weight < testw) dw->weight= testw;
865                         else if(dw->weight > uw->weight) dw->weight= uw->weight;
866                 }
867                 else {
868                         if(dw->weight > testw) dw->weight= testw;
869                         else if(dw->weight < uw->weight) dw->weight= uw->weight;
870                 }
871         }
872         
873 }
874
875 /* ----------------------------------------------------- */
876
877
878 /* sets wp->weight to the closest weight value to vertex */
879 /* note: we cant sample frontbuf, weight colors are interpolated too unpredictable */
880 static int weight_sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
881 {
882         ViewContext vc;
883         Mesh *me;
884         short change= FALSE;
885
886         view3d_set_viewcontext(C, &vc);
887         me= get_mesh(vc.obact);
888
889         if (me && me->dvert && vc.v3d && vc.rv3d) {
890                 int index;
891
892                 view3d_operator_needs_opengl(C);
893
894                 index= view3d_sample_backbuf(&vc, event->mval[0], event->mval[1]);
895
896                 if(index && index<=me->totface) {
897                         DerivedMesh *dm= mesh_get_derived_final(vc.scene, vc.obact, CD_MASK_BAREMESH);
898
899                         if(dm->getVertCo==NULL) {
900                                 BKE_report(op->reports, RPT_WARNING, "The modifier used does not support deformed locations");
901                         }
902                         else {
903                                 MFace *mf= ((MFace *)me->mface) + index-1;
904                                 const int vgroup= vc.obact->actdef - 1;
905                                 ToolSettings *ts= vc.scene->toolsettings;
906                                 float mval_f[2];
907                                 int v_idx_best= -1;
908                                 int fidx;
909                                 float len_best= FLT_MAX;
910
911                                 mval_f[0]= (float)event->mval[0];
912                                 mval_f[1]= (float)event->mval[1];
913
914                                 fidx= mf->v4 ? 3:2;
915                                 do {
916                                         float co[3], sco[3], len;
917                                         const int v_idx= (*(&mf->v1 + fidx));
918                                         dm->getVertCo(dm, v_idx, co);
919                                         project_float_noclip(vc.ar, co, sco);
920                                         len= len_squared_v2v2(mval_f, sco);
921                                         if(len < len_best) {
922                                                 len_best= len;
923                                                 v_idx_best= v_idx;
924                                         }
925                                 } while (fidx--);
926
927                                 if(v_idx_best != -1) { /* should always be valid */
928                                         ts->vgroup_weight= defvert_find_weight(&me->dvert[v_idx_best], vgroup);
929                                         change= TRUE;
930                                 }
931                         }
932                         dm->release(dm);
933                 }
934         }
935
936         if(change) {
937                 /* not really correct since the brush didnt change, but redraws the toolbar */
938                 WM_main_add_notifier(NC_BRUSH|NA_EDITED, NULL); /* ts->wpaint->paint.brush */
939
940                 return OPERATOR_FINISHED;
941         }
942         else {
943                 return OPERATOR_CANCELLED;
944         }
945 }
946
947 void PAINT_OT_weight_sample(wmOperatorType *ot)
948 {
949         /* identifiers */
950         ot->name= "Weight Paint Sample Weight";
951         ot->idname= "PAINT_OT_weight_sample";
952
953         /* api callbacks */
954         ot->invoke= weight_sample_invoke;
955         ot->poll= weight_paint_mode_poll;
956
957         /* flags */
958         ot->flag= OPTYPE_UNDO;
959 }
960
961 /* samples cursor location, and gives menu with vertex groups to activate */
962 static EnumPropertyItem *weight_paint_sample_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), int *free)
963 {
964         if (C) {
965                 wmWindow *win= CTX_wm_window(C);
966                 if(win && win->eventstate) {
967                         ViewContext vc;
968                         Mesh *me;
969
970                         view3d_set_viewcontext(C, &vc);
971                         me= get_mesh(vc.obact);
972
973                         if (me && me->dvert && vc.v3d && vc.rv3d) {
974                                 int index;
975
976                                 view3d_operator_needs_opengl(C);
977
978                                 index= view3d_sample_backbuf(&vc, win->eventstate->x - vc.ar->winrct.xmin, win->eventstate->y - vc.ar->winrct.ymin);
979
980                                 if(index && index<=me->totface) {
981                                         const int totgroup= BLI_countlist(&vc.obact->defbase);
982                                         if(totgroup) {
983                                                 MFace *mf= ((MFace *)me->mface) + index-1;
984                                                 int fidx= mf->v4 ? 3:2;
985                                                 int *groups= MEM_callocN(totgroup*sizeof(int), "groups");
986                                                 int found= FALSE;
987
988                                                 do {
989                                                         MDeformVert *dvert= me->dvert + (*(&mf->v1 + fidx));
990                                                         int i= dvert->totweight;
991                                                         MDeformWeight *dw;
992                                                         for(dw= dvert->dw; i > 0; dw++, i--) {
993                                                                 groups[dw->def_nr]= TRUE;
994                                                                 found= TRUE;
995                                                         }
996                                                 } while (fidx--);
997
998                                                 if(found==FALSE) {
999                                                         MEM_freeN(groups);
1000                                                 }
1001                                                 else {
1002                                                         EnumPropertyItem *item= NULL, item_tmp= {0};
1003                                                         int totitem= 0;
1004                                                         int i= 0;
1005                                                         bDeformGroup *dg;
1006                                                         for(dg= vc.obact->defbase.first; dg && i<totgroup; i++, dg= dg->next) {
1007                                                                 if(groups[i]) {
1008                                                                         item_tmp.identifier= item_tmp.name= dg->name;
1009                                                                         item_tmp.value= i;
1010                                                                         RNA_enum_item_add(&item, &totitem, &item_tmp);
1011                                                                 }
1012                                                         }
1013
1014                                                         RNA_enum_item_end(&item, &totitem);
1015                                                         *free= 1;
1016
1017                                                         MEM_freeN(groups);
1018                                                         return item;
1019                                                 }
1020                                         }
1021                                 }
1022                         }
1023                 }
1024         }
1025
1026         return DummyRNA_NULL_items;
1027 }
1028
1029 static int weight_sample_group_exec(bContext *C, wmOperator *op)
1030 {
1031         int type= RNA_enum_get(op->ptr, "group");
1032         ViewContext vc;
1033         view3d_set_viewcontext(C, &vc);
1034
1035         vc.obact->actdef= type + 1;
1036
1037         DAG_id_tag_update(&vc.obact->id, OB_RECALC_DATA);
1038         WM_event_add_notifier(C, NC_OBJECT|ND_DRAW, vc.obact);
1039         return OPERATOR_FINISHED;
1040 }
1041
1042 /* TODO, we could make this a menu into OBJECT_OT_vertex_group_set_active rather than its own operator */
1043 void PAINT_OT_weight_sample_group(wmOperatorType *ot)
1044 {
1045         PropertyRNA *prop= NULL;
1046
1047         /* identifiers */
1048         ot->name= "Weight Paint Sample Group";
1049         ot->idname= "PAINT_OT_weight_sample_group";
1050
1051         /* api callbacks */
1052         ot->exec= weight_sample_group_exec;
1053         ot->invoke= WM_menu_invoke;
1054         ot->poll= weight_paint_mode_poll;
1055
1056         /* flags */
1057         ot->flag= OPTYPE_UNDO;
1058
1059         /* keyingset to use (dynamic enum) */
1060         prop= RNA_def_enum(ot->srna, "group", DummyRNA_DEFAULT_items, 0, "Keying Set", "The Keying Set to use");
1061         RNA_def_enum_funcs(prop, weight_paint_sample_enum_itemf);
1062         ot->prop= prop;
1063 }
1064
1065
1066 static void do_weight_paint_auto_normalize(MDeformVert *dvert, 
1067                                            int paint_nr, char *map)
1068 {
1069 //      MDeformWeight *dw = dvert->dw;
1070         float sum=0.0f, fac=0.0f, paintw=0.0f;
1071         int i, tot=0;
1072
1073         if (!map)
1074                 return;
1075
1076         for (i=0; i<dvert->totweight; i++) {
1077                 if (dvert->dw[i].def_nr == paint_nr)
1078                         paintw = dvert->dw[i].weight;
1079
1080                 if (map[dvert->dw[i].def_nr]) {
1081                         tot += 1;
1082                         if (dvert->dw[i].def_nr != paint_nr)
1083                                 sum += dvert->dw[i].weight;
1084                 }
1085         }
1086         
1087         if (!tot || sum <= (1.0f - paintw))
1088                 return;
1089
1090         fac = sum / (1.0f - paintw);
1091         fac = fac==0.0f ? 1.0f : 1.0f / fac;
1092
1093         for (i=0; i<dvert->totweight; i++) {
1094                 if (map[dvert->dw[i].def_nr]) {
1095                         if (dvert->dw[i].def_nr != paint_nr)
1096                                 dvert->dw[i].weight *= fac;
1097                 }
1098         }
1099 }
1100 // Jason was here: the active group should be involved in auto normalize
1101 static void do_weight_paint_auto_normalize_all_groups(MDeformVert *dvert, char *map)
1102 {
1103 //      MDeformWeight *dw = dvert->dw;
1104         float sum=0.0f, fac=0.0f;
1105         int i, tot=0;
1106
1107         if (!map)
1108                 return;
1109
1110         for (i=0; i<dvert->totweight; i++) {
1111                 if (map[dvert->dw[i].def_nr]) {
1112                         tot += 1;
1113                         sum += dvert->dw[i].weight;
1114                 }
1115         }
1116         
1117         if (!tot || sum == 1.0f)
1118                 return;
1119
1120         fac = sum;
1121         fac = fac==0.0f ? 1.0f : 1.0f / fac;
1122
1123         for (i=0; i<dvert->totweight; i++) {
1124                 if (map[dvert->dw[i].def_nr]) {
1125                         dvert->dw[i].weight *= fac;
1126                 }
1127         }
1128 }
1129 /* Jason was here */
1130 /*
1131 See if the current deform vertex has a locked group
1132 */
1133 static char has_locked_group(MDeformVert *dvert, char *flags)
1134 {
1135         int i;
1136         for(i = 0; i < dvert->totweight; i++) {
1137                 if(flags[(dvert->dw+i)->def_nr] && (dvert->dw+i)->weight > 0.0f) {
1138                         return TRUE;
1139                 }
1140         }
1141         return FALSE;
1142 }
1143 /*Jason was here
1144 gen_lck_flags gets the status of "flag" for each bDeformGroup
1145 in ob->defbase and returns an array containing them
1146 */
1147 static char* gen_lck_flags(Object* ob, int defcnt, char *map)
1148 {
1149         char is_locked = FALSE;
1150         int i;
1151         //int defcnt = BLI_countlist(&ob->defbase);
1152         char *flags = MEM_mallocN(defcnt*sizeof(char), "defflags");
1153         bDeformGroup *defgroup;
1154         int selected = 0;
1155
1156         for(i = 0, defgroup = ob->defbase.first; i < defcnt && defgroup; defgroup = defgroup->next, i++) {
1157                 flags[i] = defgroup->flag;
1158                 if(flags[i]) {
1159                         is_locked = TRUE;
1160                 }
1161         }
1162         if(is_locked){
1163                 return flags;
1164         }
1165         // don't forget to free it if it is unneeded
1166         MEM_freeN(flags);
1167         return NULL;
1168 }
1169 /* Jason was here */
1170 static int has_locked_group_selected(int defcnt, char *selection, char *flags) {
1171         int i;
1172         for(i = 0; i < defcnt; i++) {
1173                 if(selection[i] && flags[i]) {
1174                         return TRUE;
1175                 }
1176         }
1177         return FALSE;
1178 }
1179
1180 /* Jason was here */
1181 static int has_unselected_unlocked_bone_group(int defcnt, char *selection, int selected, char *flags, char *bone_groups) {
1182         int i;
1183         if(defcnt == selected) {
1184                 return FALSE;
1185         }
1186         for(i = 0; i < defcnt; i++) {
1187                 if(bone_groups[i] && !selection[i] && !flags[i]) {
1188                         return TRUE;
1189                 }
1190         }
1191         return FALSE;
1192 }
1193
1194 /*Jason*/
1195 static void multipaint_selection(MDeformVert *dvert, float change, char *selection, int defcnt) {
1196         int i;
1197         MDeformWeight *dw;
1198         float val;
1199         // make sure they are all at most 1 after the change
1200         for(i = 0; i < defcnt; i++) {
1201                 if(selection[i]) {
1202                         dw = defvert_find_index(dvert, i);
1203                         if(dw && dw->weight) {
1204                                 val = dw->weight * change;
1205                                 if(val > 1) {
1206                                         change = 1.0f/dw->weight;
1207                                 }
1208                         }
1209                 }
1210         }
1211         for(i = 0; i < defcnt; i++) {
1212                 if(selection[i]) {
1213                         dw = defvert_find_index(dvert, i);
1214                         if(dw && dw->weight) {
1215                                 dw->weight = dw->weight * change;
1216                         }
1217                 }
1218         }
1219 }
1220 /*Jason*/
1221 static float redistribute_change(MDeformVert *ndv, char *change_status, int changeme, int changeto, char *validmap, float totchange, float total_valid) {
1222         float was_change;
1223         float change;
1224         float oldval;
1225         MDeformWeight *ndw;
1226         int i;
1227         do {
1228                 was_change = FALSE;
1229                 change = totchange/total_valid;
1230                 for(i = 0; i < ndv->totweight && total_valid && totchange; i++) {
1231                         ndw = (ndv->dw+i);
1232                         if(change_status[ndw->def_nr] == changeme) {
1233                                 oldval = ndw->weight;
1234                                 if(!validmap && ndw->weight + change > 1) {
1235                                         totchange -= 1-ndw->weight;
1236                                         ndw->weight = 1;
1237                                         change_status[ndw->def_nr] = changeto;
1238                                         total_valid--;
1239                                 } else if(ndw->weight + change < 0) {
1240                                         totchange -= ndw->weight;
1241                                         ndw->weight = 0;
1242                                         change_status[ndw->def_nr] = changeto;
1243                                         total_valid--;
1244                                 } else {
1245                                         totchange -= change;
1246                                         ndw->weight += change;
1247                                 }
1248                                 if(oldval != ndw->weight) {
1249                                         was_change = TRUE;
1250                                 }
1251                         }
1252                 }
1253         }while(was_change && total_valid && totchange);
1254         return totchange;
1255 }
1256 /*Jason*/
1257 static void enforce_locks(MDeformVert *odv, MDeformVert *ndv, int defcnt, char *flags, char *bone_groups, char *validmap) {
1258         float totchange = 0.0f;
1259         float totchange_allowed = 0.0f;
1260         float left_over;
1261         float change;
1262         int total_valid = 0;
1263         int total_changed = 0;
1264         int i;
1265         MDeformWeight *ndw;
1266         MDeformWeight *odw;
1267         MDeformWeight *ndw2;
1268         MDeformWeight *odw2;
1269         int designatedw = -1;
1270         int designatedw_changed = FALSE;
1271         float storedw;
1272         char *change_status;
1273         char new_weight_has_zero = FALSE;
1274
1275         if(!flags || !has_locked_group(ndv, flags)) {
1276                 return;
1277         }
1278
1279         change_status = MEM_callocN(sizeof(char)*defcnt, "unlocked_unchanged");
1280
1281         for(i = 0; i < defcnt; i++) {
1282                 ndw = defvert_find_index(ndv, i);
1283                 odw = defvert_find_index(odv, i);
1284                 if(!ndw || !odw) {
1285                         if (!flags[i] && bone_groups[i]){
1286                                 defvert_verify_index(odv, i);
1287                                 defvert_verify_index(ndv, i);
1288                                 total_valid++;
1289                                 change_status[i] = 1; // can be altered while redistributing
1290                         }
1291                         continue;
1292                 }
1293                 if(flags[i]) {
1294                         ndw->weight = odw->weight;
1295                 } else if(ndw->weight != odw->weight) {
1296                         totchange += ndw->weight-odw->weight;
1297                         change_status[i] = 2; // was altered already
1298                         total_changed++;
1299                         if(ndw->weight == 0) {
1300                                 new_weight_has_zero = TRUE;
1301                         } else if(!designatedw){
1302                                 designatedw = i;
1303                         }
1304                 } else if (bone_groups[i]){
1305                         totchange_allowed += ndw->weight;
1306                         total_valid++;
1307                         change_status[i] = 1; // can be altered while redistributing
1308                 }
1309         }
1310         if(total_changed) {
1311                 // auto normalize will allow weights to temporarily go above 1 in redistribution
1312                 if(validmap && total_changed < 0 && total_valid) {
1313                         totchange_allowed = total_valid;
1314                 }
1315                 if(totchange_allowed) {
1316                         if(totchange < 0) {
1317                                 totchange_allowed = total_valid - totchange_allowed;
1318                         } else {
1319                                 totchange_allowed *= -1;
1320                         }
1321                         left_over = 0;
1322                         if(fabs(totchange_allowed) < fabs(totchange)) {
1323                                 left_over = fabs(fabs(totchange)-fabs(totchange_allowed));
1324                                 if(totchange > 0) {
1325                                         left_over *= -1;
1326                                 }
1327                         }else {
1328                                 totchange_allowed = -totchange;
1329                         }
1330                         // move the weight evenly between the allowed groups, move excess back onto the used groups based on the change
1331                         totchange_allowed = redistribute_change(ndv, change_status, 1, -1, validmap, totchange_allowed, total_valid);
1332                         left_over += totchange_allowed;
1333                         if(left_over) {
1334                                 // more than one nonzero weights were changed with the same ratio, so keep them changed that way!
1335                                 if(total_changed > 1 && !new_weight_has_zero) {
1336                                         ndw = defvert_find_index(ndv, designatedw);
1337                                         odw = defvert_find_index(odv, designatedw);
1338                                         storedw = ndw->weight;
1339                                         for(i = 0; i < ndv->totweight; i++) {
1340                                                 if(change_status[ndw->def_nr] == 2) {
1341                                                         odw2 = (odv->dw+i);
1342                                                         ndw2 = (ndv->dw+i);
1343                                                         if(!designatedw_changed) {
1344                                                                 ndw->weight = (totchange_allowed + odw->weight + odw2->weight)/(1 + ndw2->weight/ndw->weight);
1345                                                                 designatedw_changed = TRUE;
1346                                                         }
1347                                                         ndw2->weight = ndw->weight*ndw2->weight/storedw;
1348                                                 }
1349                                         }
1350                                 }
1351                                 // a weight was changed to zero, or only one weight was changed
1352                                 // put weight back as evenly as possible
1353                                 else {
1354                                         redistribute_change(ndv, change_status, 2, -2, validmap, left_over, total_changed);
1355                                 }
1356                         }
1357                 } else {
1358                         // reset the weights
1359                         for(i = 0; i < ndv->totweight; i++) {
1360                                 (ndv->dw+i)->weight = (odv->dw+i)->weight;
1361                         }
1362                 }
1363         }
1364
1365         MEM_freeN(change_status);
1366 }
1367 /*Jason*/
1368 static float get_mp_change(MDeformVert *odv, char *selection, float oldw, float neww) {
1369         if(oldw) {
1370                 return neww/oldw;
1371         }
1372         return 0;
1373 }
1374 /*Jason*/
1375 /*static void reset_to_prev(VPaint *wv, MDeformVert *dv, int vgroup) {
1376         int i;
1377         MDeformWeight *d;
1378         MDeformWeight *w;
1379         for(i = 0; i < dv->totweight; i++) {
1380                 d = dv->dw+i;
1381                 if(d->def_nr == vgroup) {
1382                         continue;
1383                 }
1384                 w = defvert_find_index(wv, d->def_nr);
1385                 if(w) {
1386                         d->weight = w->weight;
1387                 } else {
1388                         d->weight = 0;
1389                 }
1390         }
1391 }*/
1392 /* Jason */
1393 static void clamp_weights(MDeformVert *dvert) {
1394         int i;
1395         for (i = 0; i < dvert->totweight; i++) {
1396                 CLAMP((dvert->dw+i)->weight, 0.0f, 1.0f);
1397         }
1398 }
1399 /*Jason*/
1400 /* fresh start to make multi-paint and locking modular */
1401 static void apply_mp_lcks_normalize(Object *ob, Mesh *me, int index, MDeformWeight *dw, int defcnt, float oldw, float neww, char *selection, int selected, char *bone_groups, char *validmap, char *flags, int multipaint) {
1402         MDeformVert *dvert = me->dvert+index;
1403         MDeformVert *dv = MEM_mallocN(sizeof (*(me->dvert+index)), "oldMDeformVert");
1404         float change = 0.0f;
1405         int i;
1406         dw->weight = oldw;
1407         
1408         dv->dw= MEM_dupallocN(dvert->dw);
1409         dv->flag = dvert->flag;
1410         dv->totweight = dvert->totweight;
1411
1412         if(!flags || flags && !has_locked_group_selected(defcnt, selection, flags) && !flags[dw->def_nr]) {// !flags[dw->def_nr] helps if nothing is selected, but active group is locked
1413                 if(multipaint && selected > 1 && (change = get_mp_change(dv, selection, oldw, neww)) && change!=1) {
1414                         multipaint_selection(dvert, change, selection, defcnt);
1415                 } else {
1416                         dw->weight = neww;
1417                         change = 0.0f;
1418                 }
1419         }
1420         clamp_weights(me->dvert+index);
1421
1422         enforce_locks(dv, dvert, defcnt, flags, bone_groups, validmap);
1423
1424         do_weight_paint_auto_normalize_all_groups(dvert, validmap);
1425         
1426         MEM_freeN(dv->dw);
1427         MEM_freeN(dv);
1428 }
1429
1430 /* Jason was here duplicate function I used in DerivedMesh.c*/
1431 static char* get_selected_defgroups(Object *ob, int defcnt) {
1432         bPoseChannel *chan;
1433         bPose *pose;
1434         bDeformGroup *defgroup;
1435         //Bone *bone;
1436         char *dg_flags = MEM_callocN(defcnt*sizeof(char), "dg_selected_flags");
1437         int i;
1438         Object *armob = ED_object_pose_armature(ob);
1439
1440         if(armob) {
1441                 pose = armob->pose;
1442                 for (chan=pose->chanbase.first; chan; chan=chan->next) {
1443                         for (i = 0, defgroup = ob->defbase.first; i < defcnt && defgroup; defgroup = defgroup->next, i++) {
1444                                 if(!strcmp(defgroup->name, chan->bone->name)) {
1445                                         dg_flags[i] = (chan->bone->flag & BONE_SELECTED);
1446                                 }
1447                         }
1448                 }
1449         }
1450         
1451         return dg_flags;
1452 }
1453 /* TODO move duplicates to header */
1454 /* Jason was here duplicate function */
1455 static int count_true(char *list, int len)
1456 {
1457         int i;
1458         int cnt = 0;
1459         for(i = 0; i < len; i++) {
1460                 if (list[i]) {
1461                         cnt++;
1462                 }
1463         }
1464         return cnt;
1465 }
1466 // Jason
1467 static char *wpaint_make_validmap(Object *ob);
1468
1469 static void do_weight_paint_vertex(VPaint *wp, Object *ob, int index, 
1470                                    float alpha, float paintweight, int flip, 
1471                                    int vgroup_mirror, char *validmap, int multipaint)
1472 {
1473         Mesh *me= ob->data;
1474         MDeformWeight *dw, *uw;
1475         int vgroup= ob->actdef-1;
1476
1477         /* Jason was here */
1478         char *flags;
1479         char *bone_groups;
1480         char *selection;
1481         int selected;
1482         float oldw;
1483         float neww;
1484         int defcnt;
1485         int i;
1486         if(validmap) {
1487                 bone_groups = validmap;
1488         }else {
1489                 bone_groups = wpaint_make_validmap(ob);
1490         }
1491
1492         if(wp->flag & VP_ONLYVGROUP) {
1493                 dw= defvert_find_index(me->dvert+index, vgroup);
1494                 uw= defvert_find_index(wp->wpaint_prev+index, vgroup);
1495         }
1496         else {
1497                 dw= defvert_verify_index(me->dvert+index, vgroup);
1498                 uw= defvert_verify_index(wp->wpaint_prev+index, vgroup);
1499         }
1500         if(dw==NULL || uw==NULL)
1501                 return;
1502         /* Jason was here */
1503         flags = gen_lck_flags(ob, defcnt = BLI_countlist(&ob->defbase), bone_groups);
1504         selection = get_selected_defgroups(ob, defcnt);
1505         selected = count_true(selection, defcnt);
1506         if(!selected && ob->actdef) {
1507                 selected = 1;
1508         }
1509         
1510         oldw = dw->weight;
1511         wpaint_blend(wp, dw, uw, alpha, paintweight, flip);
1512         neww = dw->weight;
1513         if(selected > 1 && multipaint) {
1514                 if(!oldw || neww <= 0) {
1515                         neww = oldw;
1516                         dw->weight = oldw;
1517                 }
1518         }
1519         /* Jason was here */
1520         apply_mp_lcks_normalize(ob, me, index, dw, defcnt, oldw, neww, selection, selected, bone_groups, validmap, flags, multipaint);
1521
1522         // dvert may have been altered greatly
1523         dw = defvert_find_index(me->dvert+index, vgroup);
1524
1525         if(me->editflag & ME_EDIT_MIRROR_X) {   /* x mirror painting */
1526                 int j= mesh_get_x_mirror_vert(ob, index);
1527                 if(j>=0) {
1528                         /* copy, not paint again */
1529                         if(vgroup_mirror != -1)
1530                                 uw= defvert_verify_index(me->dvert+j, vgroup_mirror);
1531                         else
1532                                 uw= defvert_verify_index(me->dvert+j, vgroup);
1533                         /* Jason */
1534                         oldw = uw->weight;
1535
1536                         //uw->weight= dw->weight;
1537                         uw->weight = neww;
1538                         /* Jason */
1539                         apply_mp_lcks_normalize(ob, me, j, uw, defcnt, oldw, neww, selection, selected, bone_groups, validmap, flags, multipaint);
1540                 }
1541         }
1542         /* Jason */
1543         if(flags) {
1544                 MEM_freeN(flags);
1545         }
1546         MEM_freeN(selection);
1547         if(!validmap) {
1548                 MEM_freeN(bone_groups);
1549         }
1550 }
1551
1552 /* *************** set wpaint operator ****************** */
1553
1554 static int set_wpaint(bContext *C, wmOperator *UNUSED(op))              /* toggle */
1555 {               
1556         Object *ob= CTX_data_active_object(C);
1557         Scene *scene= CTX_data_scene(C);
1558         VPaint *wp= scene->toolsettings->wpaint;
1559         Mesh *me;
1560         
1561         me= get_mesh(ob);
1562         if(ob->id.lib || me==NULL) return OPERATOR_PASS_THROUGH;
1563         
1564         if(ob->mode & OB_MODE_WEIGHT_PAINT) ob->mode &= ~OB_MODE_WEIGHT_PAINT;
1565         else ob->mode |= OB_MODE_WEIGHT_PAINT;
1566         
1567         
1568         /* Weightpaint works by overriding colors in mesh,
1569                 * so need to make sure we recalc on enter and
1570                 * exit (exit needs doing regardless because we
1571                                 * should redeform).
1572                 */
1573         DAG_id_tag_update(&me->id, 0);
1574         
1575         if(ob->mode & OB_MODE_WEIGHT_PAINT) {
1576                 Object *par;
1577                 
1578                 if(wp==NULL)
1579                         wp= scene->toolsettings->wpaint= new_vpaint(1);
1580
1581                 paint_init(&wp->paint, PAINT_CURSOR_WEIGHT_PAINT);
1582                 paint_cursor_start(C, weight_paint_poll);
1583                 
1584                 mesh_octree_table(ob, NULL, NULL, 's');
1585                 
1586                 /* verify if active weight group is also active bone */
1587                 par= modifiers_isDeformedByArmature(ob);
1588                 if(par && (par->mode & OB_MODE_POSE)) {
1589                         bArmature *arm= par->data;
1590
1591                         if(arm->act_bone)
1592                                 ED_vgroup_select_by_name(ob, arm->act_bone->name);
1593                 }
1594         }
1595         else {
1596                 mesh_octree_table(NULL, NULL, NULL, 'e');
1597                 mesh_mirrtopo_table(NULL, 'e');
1598         }
1599         
1600         WM_event_add_notifier(C, NC_SCENE|ND_MODE, scene);
1601         
1602         return OPERATOR_FINISHED;
1603 }
1604
1605 /* for switching to/from mode */
1606 static int paint_poll_test(bContext *C)
1607 {
1608         if(CTX_data_edit_object(C))
1609                 return 0;
1610         if(CTX_data_active_object(C)==NULL)
1611                 return 0;
1612         return 1;
1613 }
1614
1615 void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
1616 {
1617         
1618         /* identifiers */
1619         ot->name= "Weight Paint Mode";
1620         ot->idname= "PAINT_OT_weight_paint_toggle";
1621         
1622         /* api callbacks */
1623         ot->exec= set_wpaint;
1624         ot->poll= paint_poll_test;
1625         
1626         /* flags */
1627         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1628         
1629 }
1630
1631 /* ************ weight paint operator ********** */
1632
1633 struct WPaintData {
1634         ViewContext vc;
1635         int *indexar;
1636         int vgroup_mirror;
1637         float *vertexcosnos;
1638         float wpimat[3][3];
1639         
1640         /*variables for auto normalize*/
1641         int auto_normalize;
1642         char *vgroup_validmap; /*stores if vgroups tie to deforming bones or not*/
1643 };
1644
1645 static char *wpaint_make_validmap(Object *ob)
1646 {
1647         bDeformGroup *dg;
1648         ModifierData *md;
1649         char *validmap;
1650         bPose *pose;
1651         bPoseChannel *chan;
1652         ArmatureModifierData *amd;
1653         GHash *gh = BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp, "wpaint_make_validmap gh");
1654         int i = 0, step1=1;
1655
1656         /*add all names to a hash table*/
1657         for (dg=ob->defbase.first, i=0; dg; dg=dg->next, i++) {
1658                 BLI_ghash_insert(gh, dg->name, NULL);
1659         }
1660
1661         if (!i)
1662                 return NULL;
1663
1664         validmap = MEM_callocN(i, "wpaint valid map");
1665
1666         /*now loop through the armature modifiers and identify deform bones*/
1667         for (md = ob->modifiers.first; md; md= !md->next && step1 ? (step1=0), modifiers_getVirtualModifierList(ob) : md->next) {
1668                 if (!(md->mode & (eModifierMode_Realtime|eModifierMode_Virtual)))
1669                         continue;
1670
1671                 if (md->type == eModifierType_Armature) 
1672                 {
1673                         amd = (ArmatureModifierData*) md;
1674
1675                         if(amd->object && amd->object->pose) {
1676                                 pose = amd->object->pose;
1677                                 
1678                                 for (chan=pose->chanbase.first; chan; chan=chan->next) {
1679                                         if (chan->bone->flag & BONE_NO_DEFORM)
1680                                                 continue;
1681
1682                                         if (BLI_ghash_haskey(gh, chan->name)) {
1683                                                 BLI_ghash_remove(gh, chan->name, NULL, NULL);
1684                                                 BLI_ghash_insert(gh, chan->name, SET_INT_IN_POINTER(1));
1685                                         }
1686                                 }
1687                         }
1688                 }
1689         }
1690         
1691         /*add all names to a hash table*/
1692         for (dg=ob->defbase.first, i=0; dg; dg=dg->next, i++) {
1693                 if (BLI_ghash_lookup(gh, dg->name) != NULL) {
1694                         validmap[i] = 1;
1695                 }
1696         }
1697
1698         BLI_ghash_free(gh, NULL, NULL);
1699
1700         return validmap;
1701 }
1702
1703 static int wpaint_stroke_test_start(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1704 {
1705         Scene *scene= CTX_data_scene(C);
1706         struct PaintStroke *stroke = op->customdata;
1707         ToolSettings *ts= CTX_data_tool_settings(C);
1708         VPaint *wp= ts->wpaint;
1709         Object *ob= CTX_data_active_object(C);
1710         struct WPaintData *wpd;
1711         Mesh *me;
1712         float mat[4][4], imat[4][4];
1713
1714         if(scene->obedit) return OPERATOR_CANCELLED;
1715         
1716         me= get_mesh(ob);
1717         if(me==NULL || me->totface==0) return OPERATOR_PASS_THROUGH;
1718         
1719         /* if nothing was added yet, we make dverts and a vertex deform group */
1720         if (!me->dvert) {
1721                 ED_vgroup_data_create(&me->id);
1722                 WM_event_add_notifier(C, NC_GEOM|ND_DATA, me);
1723         }
1724
1725
1726         /* make mode data storage */
1727         wpd= MEM_callocN(sizeof(struct WPaintData), "WPaintData");
1728         paint_stroke_set_mode_data(stroke, wpd);
1729         view3d_set_viewcontext(C, &wpd->vc);
1730         wpd->vgroup_mirror= -1;
1731
1732         /*set up auto-normalize, and generate map for detecting which
1733           vgroups affect deform bones*/
1734         wpd->auto_normalize = ts->auto_normalize;
1735         if (wpd->auto_normalize)
1736                 wpd->vgroup_validmap = wpaint_make_validmap(ob);
1737         
1738         //      if(qual & LR_CTRLKEY) {
1739         //              sample_wpaint(scene, ar, v3d, 0);
1740         //              return;
1741         //      }
1742         //      if(qual & LR_SHIFTKEY) {
1743         //              sample_wpaint(scene, ar, v3d, 1);
1744         //              return;
1745         //      }
1746         
1747         /* ALLOCATIONS! no return after this line */
1748         /* painting on subsurfs should give correct points too, this returns me->totvert amount */
1749         wpd->vertexcosnos= mesh_get_mapped_verts_nors(scene, ob);
1750         wpd->indexar= get_indexarray(me);
1751         copy_wpaint_prev(wp, me->dvert, me->totvert);
1752         
1753         /* this happens on a Bone select, when no vgroup existed yet */
1754         if(ob->actdef<=0) {
1755                 Object *modob;
1756                 if((modob = modifiers_isDeformedByArmature(ob))) {
1757                         Bone *actbone= ((bArmature *)modob->data)->act_bone;
1758                         if(actbone) {
1759                                 bPoseChannel *pchan= get_pose_channel(modob->pose, actbone->name);
1760
1761                                 if(pchan) {
1762                                         bDeformGroup *dg= defgroup_find_name(ob, pchan->name);
1763                                         if(dg==NULL)
1764                                                 dg= ED_vgroup_add_name(ob, pchan->name);        /* sets actdef */
1765                                         else
1766                                                 ob->actdef= 1 + defgroup_find_index(ob, dg);
1767                                 }
1768                         }
1769                 }
1770         }
1771         if(ob->defbase.first==NULL) {
1772                 ED_vgroup_add(ob);
1773         }
1774         
1775         //      if(ob->lay & v3d->lay); else error("Active object is not in this layer");
1776         
1777         /* imat for normals */
1778         mul_m4_m4m4(mat, ob->obmat, wpd->vc.rv3d->viewmat);
1779         invert_m4_m4(imat, mat);
1780         copy_m3_m4(wpd->wpimat, imat);
1781         
1782         /* if mirror painting, find the other group */
1783         if(me->editflag & ME_EDIT_MIRROR_X) {
1784                 wpaint_mirror_vgroup_ensure(ob, &wpd->vgroup_mirror);
1785         }
1786
1787         return 1;
1788 }
1789
1790 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
1791 {
1792         ToolSettings *ts= CTX_data_tool_settings(C);
1793         VPaint *wp= ts->wpaint;
1794         Brush *brush = paint_brush(&wp->paint);
1795         struct WPaintData *wpd= paint_stroke_mode_data(stroke);
1796         ViewContext *vc;
1797         Object *ob;
1798         Mesh *me;
1799         float mat[4][4];
1800         float paintweight;
1801         int *indexar;
1802         int totindex, index, totw, flip;
1803         float alpha;
1804         float mval[2], pressure;
1805         
1806         /* cannot paint if there is no stroke data */
1807         if (wpd == NULL) {
1808                 // XXX: force a redraw here, since even though we can't paint, 
1809                 // at least view won't freeze until stroke ends
1810                 ED_region_tag_redraw(CTX_wm_region(C));
1811                 return;
1812         }
1813                 
1814         vc= &wpd->vc;
1815         ob= vc->obact;
1816         me= ob->data;
1817         indexar= wpd->indexar;
1818         
1819         view3d_operator_needs_opengl(C);
1820                 
1821         /* load projection matrix */
1822         mul_m4_m4m4(mat, ob->obmat, vc->rv3d->persmat);
1823
1824         flip = RNA_boolean_get(itemptr, "pen_flip");
1825         pressure = RNA_float_get(itemptr, "pressure");
1826         RNA_float_get_array(itemptr, "mouse", mval);
1827         mval[0]-= vc->ar->winrct.xmin;
1828         mval[1]-= vc->ar->winrct.ymin;
1829                         
1830         swap_m4m4(wpd->vc.rv3d->persmat, mat);
1831                         
1832         /* which faces are involved */
1833         if(wp->flag & VP_AREA) {
1834                 totindex= sample_backbuf_area(vc, indexar, me->totface, mval[0], mval[1], brush_size(brush));
1835         }
1836         else {
1837                 indexar[0]= view3d_sample_backbuf(vc, mval[0], mval[1]);
1838                 if(indexar[0]) totindex= 1;
1839                 else totindex= 0;
1840         }
1841                         
1842         if(wp->flag & VP_COLINDEX) {
1843                 for(index=0; index<totindex; index++) {
1844                         if(indexar[index] && indexar[index]<=me->totface) {
1845                                 MFace *mface= ((MFace *)me->mface) + (indexar[index]-1);
1846                                                 
1847                                 if(mface->mat_nr!=ob->actcol-1) {
1848                                         indexar[index]= 0;
1849                                 }
1850                         }
1851                 }
1852         }
1853                         
1854         if((me->editflag & ME_EDIT_PAINT_MASK) && me->mface) {
1855                 for(index=0; index<totindex; index++) {
1856                         if(indexar[index] && indexar[index]<=me->totface) {
1857                                 MFace *mface= ((MFace *)me->mface) + (indexar[index]-1);
1858                                                 
1859                                 if((mface->flag & ME_FACE_SEL)==0) {
1860                                         indexar[index]= 0;
1861                                 }
1862                         }                                       
1863                 }
1864         }
1865                         
1866         /* make sure each vertex gets treated only once */
1867         /* and calculate filter weight */
1868         totw= 0;
1869         if(brush->vertexpaint_tool==VP_BLUR) 
1870                 paintweight= 0.0f;
1871         else
1872                 paintweight= ts->vgroup_weight;
1873                         
1874         for(index=0; index<totindex; index++) {
1875                 if(indexar[index] && indexar[index]<=me->totface) {
1876                         MFace *mface= me->mface + (indexar[index]-1);
1877                                         
1878                         (me->dvert+mface->v1)->flag= 1;
1879                         (me->dvert+mface->v2)->flag= 1;
1880                         (me->dvert+mface->v3)->flag= 1;
1881                         if(mface->v4) (me->dvert+mface->v4)->flag= 1;
1882                                         
1883                         if(brush->vertexpaint_tool==VP_BLUR) {
1884                                 MDeformWeight *dw, *(*dw_func)(MDeformVert *, const int);
1885                                                 
1886                                 if(wp->flag & VP_ONLYVGROUP)
1887                                         dw_func= (MDeformWeight *(*)(MDeformVert *, const int))defvert_find_index;
1888                                 else
1889                                         dw_func= defvert_verify_index;
1890                                                 
1891                                 dw= dw_func(me->dvert+mface->v1, ob->actdef-1);
1892                                 if(dw) {paintweight+= dw->weight; totw++;}
1893                                 dw= dw_func(me->dvert+mface->v2, ob->actdef-1);
1894                                 if(dw) {paintweight+= dw->weight; totw++;}
1895                                 dw= dw_func(me->dvert+mface->v3, ob->actdef-1);
1896                                 if(dw) {paintweight+= dw->weight; totw++;}
1897                                 if(mface->v4) {
1898                                         dw= dw_func(me->dvert+mface->v4, ob->actdef-1);
1899                                         if(dw) {paintweight+= dw->weight; totw++;}
1900                                 }
1901                         }
1902                 }
1903         }
1904                         
1905         if(brush->vertexpaint_tool==VP_BLUR) 
1906                 paintweight/= (float)totw;
1907                         
1908         for(index=0; index<totindex; index++) {
1909                                 
1910                 if(indexar[index] && indexar[index]<=me->totface) {
1911                         MFace *mface= me->mface + (indexar[index]-1);
1912                                         
1913                         if((me->dvert+mface->v1)->flag) {
1914                                 alpha= calc_vp_alpha_dl(wp, vc, wpd->wpimat, wpd->vertexcosnos+6*mface->v1, mval, pressure);
1915                                 if(alpha) {
1916                                         do_weight_paint_vertex(wp, ob, mface->v1, 
1917                                                 alpha, paintweight, flip, wpd->vgroup_mirror, 
1918                                                 wpd->vgroup_validmap, ts->multipaint);
1919                                 }
1920                                 (me->dvert+mface->v1)->flag= 0;
1921                         }
1922                                         
1923                         if((me->dvert+mface->v2)->flag) {
1924                                 alpha= calc_vp_alpha_dl(wp, vc, wpd->wpimat, wpd->vertexcosnos+6*mface->v2, mval, pressure);
1925                                 if(alpha) {
1926                                         do_weight_paint_vertex(wp, ob, mface->v2, 
1927                                                 alpha, paintweight, flip, wpd->vgroup_mirror, 
1928                                                 wpd->vgroup_validmap, ts->multipaint);
1929                                 }
1930                                 (me->dvert+mface->v2)->flag= 0;
1931                         }
1932                                         
1933                         if((me->dvert+mface->v3)->flag) {
1934                                 alpha= calc_vp_alpha_dl(wp, vc, wpd->wpimat, wpd->vertexcosnos+6*mface->v3, mval, pressure);
1935                                 if(alpha) {
1936                                         do_weight_paint_vertex(wp, ob, mface->v3, 
1937                                                 alpha, paintweight, flip, wpd->vgroup_mirror, 
1938                                                 wpd->vgroup_validmap, ts->multipaint);
1939                                 }
1940                                 (me->dvert+mface->v3)->flag= 0;
1941                         }
1942                                         
1943                         if((me->dvert+mface->v4)->flag) {
1944                                 if(mface->v4) {
1945                                         alpha= calc_vp_alpha_dl(wp, vc, wpd->wpimat, wpd->vertexcosnos+6*mface->v4, mval, pressure);
1946                                         if(alpha) {
1947                                                 do_weight_paint_vertex(wp, ob, mface->v4, 
1948                                                         alpha, paintweight, flip, wpd->vgroup_mirror,
1949                                                         wpd->vgroup_validmap, ts->multipaint);
1950                                         }
1951                                         (me->dvert+mface->v4)->flag= 0;
1952                                 }
1953                         }
1954                 }
1955         }
1956                         
1957         swap_m4m4(vc->rv3d->persmat, mat);
1958                         
1959         DAG_id_tag_update(ob->data, 0);
1960         ED_region_tag_redraw(vc->ar);
1961 }
1962
1963 static void wpaint_stroke_done(bContext *C, struct PaintStroke *stroke)
1964 {
1965         ToolSettings *ts= CTX_data_tool_settings(C);
1966         Object *ob= CTX_data_active_object(C);
1967         struct WPaintData *wpd= paint_stroke_mode_data(stroke);
1968         
1969         if(wpd) {
1970                 if(wpd->vertexcosnos)
1971                         MEM_freeN(wpd->vertexcosnos);
1972                 MEM_freeN(wpd->indexar);
1973                 
1974                 if (wpd->vgroup_validmap)
1975                         MEM_freeN(wpd->vgroup_validmap);
1976                 
1977                 MEM_freeN(wpd);
1978         }
1979         
1980         /* frees prev buffer */
1981         copy_wpaint_prev(ts->wpaint, NULL, 0);
1982         
1983         /* and particles too */
1984         if(ob->particlesystem.first) {
1985                 ParticleSystem *psys;
1986                 int i;
1987                 
1988                 for(psys= ob->particlesystem.first; psys; psys= psys->next) {
1989                         for(i=0; i<PSYS_TOT_VG; i++) {
1990                                 if(psys->vgroup[i]==ob->actdef) {
1991                                         psys->recalc |= PSYS_RECALC_RESET;
1992                                         break;
1993                                 }
1994                         }
1995                 }
1996         }
1997         
1998         DAG_id_tag_update(ob->data, 0);
1999 }
2000
2001
2002 static int wpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2003 {
2004         
2005         op->customdata = paint_stroke_new(C, NULL, wpaint_stroke_test_start,
2006                                           wpaint_stroke_update_step,
2007                                           wpaint_stroke_done, event->type);
2008         
2009         /* add modal handler */
2010         WM_event_add_modal_handler(C, op);
2011
2012         op->type->modal(C, op, event);
2013         
2014         return OPERATOR_RUNNING_MODAL;
2015 }
2016
2017 static int wpaint_cancel(bContext *C, wmOperator *op)
2018 {
2019         paint_stroke_cancel(C, op);
2020
2021         return OPERATOR_CANCELLED;
2022 }
2023
2024 void PAINT_OT_weight_paint(wmOperatorType *ot)
2025 {
2026         
2027         /* identifiers */
2028         ot->name= "Weight Paint";
2029         ot->idname= "PAINT_OT_weight_paint";
2030         
2031         /* api callbacks */
2032         ot->invoke= wpaint_invoke;
2033         ot->modal= paint_stroke_modal;
2034         /* ot->exec= vpaint_exec; <-- needs stroke property */
2035         ot->poll= weight_paint_poll;
2036         ot->cancel= wpaint_cancel;
2037         
2038         /* flags */
2039         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2040
2041         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2042 }
2043
2044 static int weight_paint_set_exec(bContext *C, wmOperator *UNUSED(op))
2045 {
2046         struct Scene *scene= CTX_data_scene(C);
2047         Object *obact = CTX_data_active_object(C);
2048
2049         wpaint_fill(scene->toolsettings->wpaint, obact, scene->toolsettings->vgroup_weight);
2050         ED_region_tag_redraw(CTX_wm_region(C)); // XXX - should redraw all 3D views
2051         return OPERATOR_FINISHED;
2052 }
2053
2054 void PAINT_OT_weight_set(wmOperatorType *ot)
2055 {
2056         /* identifiers */
2057         ot->name= "Set Weight";
2058         ot->idname= "PAINT_OT_weight_set";
2059
2060         /* api callbacks */
2061         ot->exec= weight_paint_set_exec;
2062         ot->poll= facemask_paint_poll;
2063
2064         /* flags */
2065         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2066 }
2067
2068 /* ************ set / clear vertex paint mode ********** */
2069
2070
2071 static int set_vpaint(bContext *C, wmOperator *op)              /* toggle */
2072 {       
2073         Object *ob= CTX_data_active_object(C);
2074         Scene *scene= CTX_data_scene(C);
2075         VPaint *vp= scene->toolsettings->vpaint;
2076         Mesh *me;
2077         
2078         me= get_mesh(ob);
2079         
2080         if(me==NULL || object_data_is_libdata(ob)) {
2081                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2082                 return OPERATOR_PASS_THROUGH;
2083         }
2084         
2085         if(me && me->mcol==NULL) make_vertexcol(ob);
2086         
2087         /* toggle: end vpaint */
2088         if(ob->mode & OB_MODE_VERTEX_PAINT) {
2089                 
2090                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2091         }
2092         else {
2093                 ob->mode |= OB_MODE_VERTEX_PAINT;
2094                 /* Turn off weight painting */
2095                 if (ob->mode & OB_MODE_WEIGHT_PAINT)
2096                         set_wpaint(C, op);
2097                 
2098                 if(vp==NULL)
2099                         vp= scene->toolsettings->vpaint= new_vpaint(0);
2100                 
2101                 paint_cursor_start(C, vertex_paint_poll);
2102
2103                 paint_init(&vp->paint, PAINT_CURSOR_VERTEX_PAINT);
2104         }
2105         
2106         if (me)
2107                 /* update modifier stack for mapping requirements */
2108                 DAG_id_tag_update(&me->id, 0);
2109         
2110         WM_event_add_notifier(C, NC_SCENE|ND_MODE, scene);
2111         
2112         return OPERATOR_FINISHED;
2113 }
2114
2115 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2116 {
2117         
2118         /* identifiers */
2119         ot->name= "Vertex Paint Mode";
2120         ot->idname= "PAINT_OT_vertex_paint_toggle";
2121         
2122         /* api callbacks */
2123         ot->exec= set_vpaint;
2124         ot->poll= paint_poll_test;
2125         
2126         /* flags */
2127         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2128 }
2129
2130
2131
2132 /* ********************** vertex paint operator ******************* */
2133
2134 /* Implementation notes:
2135
2136 Operator->invoke()
2137   - validate context (add mcol)
2138   - create customdata storage
2139   - call paint once (mouse click)
2140   - add modal handler 
2141
2142 Operator->modal()
2143   - for every mousemove, apply vertex paint
2144   - exit on mouse release, free customdata
2145         (return OPERATOR_FINISHED also removes handler and operator)
2146
2147 For future:
2148   - implement a stroke event (or mousemove with past positons)
2149   - revise whether op->customdata should be added in object, in set_vpaint
2150
2151 */
2152
2153 typedef struct VPaintData {
2154         ViewContext vc;
2155         unsigned int paintcol;
2156         int *indexar;
2157         float *vertexcosnos;
2158         float vpimat[3][3];
2159 } VPaintData;
2160
2161 static int vpaint_stroke_test_start(bContext *C, struct wmOperator *op, wmEvent *UNUSED(event))
2162 {
2163         ToolSettings *ts= CTX_data_tool_settings(C);
2164         struct PaintStroke *stroke = op->customdata;
2165         VPaint *vp= ts->vpaint;
2166         struct VPaintData *vpd;
2167         Object *ob= CTX_data_active_object(C);
2168         Mesh *me;
2169         float mat[4][4], imat[4][4];
2170
2171         /* context checks could be a poll() */
2172         me= get_mesh(ob);
2173         if(me==NULL || me->totface==0) return OPERATOR_PASS_THROUGH;
2174         
2175         if(me->mcol==NULL) make_vertexcol(ob);
2176         if(me->mcol==NULL) return OPERATOR_CANCELLED;
2177         
2178         /* make mode data storage */
2179         vpd= MEM_callocN(sizeof(struct VPaintData), "VPaintData");
2180         paint_stroke_set_mode_data(stroke, vpd);
2181         view3d_set_viewcontext(C, &vpd->vc);
2182         
2183         vpd->vertexcosnos= mesh_get_mapped_verts_nors(vpd->vc.scene, ob);
2184         vpd->indexar= get_indexarray(me);
2185         vpd->paintcol= vpaint_get_current_col(vp);
2186         
2187         /* for filtering */
2188         copy_vpaint_prev(vp, (unsigned int *)me->mcol, me->totface);
2189         
2190         /* some old cruft to sort out later */
2191         mul_m4_m4m4(mat, ob->obmat, vpd->vc.rv3d->viewmat);
2192         invert_m4_m4(imat, mat);
2193         copy_m3_m4(vpd->vpimat, imat);
2194
2195         return 1;
2196 }
2197
2198 static void vpaint_paint_face(VPaint *vp, VPaintData *vpd, Object *ob, int index, const float mval[2], float pressure, int UNUSED(flip))
2199 {
2200         ViewContext *vc = &vpd->vc;
2201         Brush *brush = paint_brush(&vp->paint);
2202         Mesh *me = get_mesh(ob);
2203         MFace *mface= ((MFace*)me->mface) + index;
2204         unsigned int *mcol= ((unsigned int*)me->mcol) + 4*index;
2205         unsigned int *mcolorig= ((unsigned int*)vp->vpaint_prev) + 4*index;
2206         float alpha;
2207         int i;
2208         
2209         if((vp->flag & VP_COLINDEX && mface->mat_nr!=ob->actcol-1) ||
2210            ((me->editflag & ME_EDIT_PAINT_MASK) && !(mface->flag & ME_FACE_SEL)))
2211                 return;
2212
2213         if(brush->vertexpaint_tool==VP_BLUR) {
2214                 unsigned int fcol1= mcol_blend( mcol[0], mcol[1], 128);
2215                 if(mface->v4) {
2216                         unsigned int fcol2= mcol_blend( mcol[2], mcol[3], 128);
2217                         vpd->paintcol= mcol_blend( fcol1, fcol2, 128);
2218                 }
2219                 else {
2220                         vpd->paintcol= mcol_blend( mcol[2], fcol1, 170);
2221                 }
2222                 
2223         }
2224
2225         for(i = 0; i < (mface->v4 ? 4 : 3); ++i) {
2226                 alpha= calc_vp_alpha_dl(vp, vc, vpd->vpimat, vpd->vertexcosnos+6*(&mface->v1)[i], mval, pressure);
2227                 if(alpha)
2228                         vpaint_blend(vp, mcol+i, mcolorig+i, vpd->paintcol, (int)(alpha*255.0f));
2229         }
2230 }
2231
2232 static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2233 {
2234         ToolSettings *ts= CTX_data_tool_settings(C);
2235         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2236         VPaint *vp= ts->vpaint;
2237         Brush *brush = paint_brush(&vp->paint);
2238         ViewContext *vc= &vpd->vc;
2239         Object *ob= vc->obact;
2240         Mesh *me= ob->data;
2241         float mat[4][4];
2242         int *indexar= vpd->indexar;
2243         int totindex, index, flip;
2244         float pressure, mval[2];
2245
2246         RNA_float_get_array(itemptr, "mouse", mval);
2247         flip = RNA_boolean_get(itemptr, "pen_flip");
2248         pressure = RNA_float_get(itemptr, "pressure");
2249                         
2250         view3d_operator_needs_opengl(C);
2251                         
2252         /* load projection matrix */
2253         mul_m4_m4m4(mat, ob->obmat, vc->rv3d->persmat);
2254
2255         mval[0]-= vc->ar->winrct.xmin;
2256         mval[1]-= vc->ar->winrct.ymin;
2257
2258                         
2259         /* which faces are involved */
2260         if(vp->flag & VP_AREA) {
2261                 totindex= sample_backbuf_area(vc, indexar, me->totface, mval[0], mval[1], brush_size(brush));
2262         }
2263         else {
2264                 indexar[0]= view3d_sample_backbuf(vc, mval[0], mval[1]);
2265                 if(indexar[0]) totindex= 1;
2266                 else totindex= 0;
2267         }
2268                         
2269         swap_m4m4(vc->rv3d->persmat, mat);
2270                         
2271         for(index=0; index<totindex; index++) {                         
2272                 if(indexar[index] && indexar[index]<=me->totface)
2273                         vpaint_paint_face(vp, vpd, ob, indexar[index]-1, mval, pressure, flip);
2274         }
2275                                                 
2276         swap_m4m4(vc->rv3d->persmat, mat);
2277
2278         /* was disabled because it is slow, but necessary for blur */
2279         if(brush->vertexpaint_tool == VP_BLUR)
2280                 do_shared_vertexcol(me);
2281                         
2282         ED_region_tag_redraw(vc->ar);
2283                         
2284         DAG_id_tag_update(ob->data, 0);
2285 }
2286
2287 static void vpaint_stroke_done(bContext *C, struct PaintStroke *stroke)
2288 {
2289         ToolSettings *ts= CTX_data_tool_settings(C);
2290         struct VPaintData *vpd= paint_stroke_mode_data(stroke);
2291         
2292         if(vpd->vertexcosnos)
2293                 MEM_freeN(vpd->vertexcosnos);
2294         MEM_freeN(vpd->indexar);
2295         
2296         /* frees prev buffer */
2297         copy_vpaint_prev(ts->vpaint, NULL, 0);
2298         
2299         MEM_freeN(vpd);
2300 }
2301
2302 static int vpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2303 {
2304         
2305         op->customdata = paint_stroke_new(C, NULL, vpaint_stroke_test_start,
2306                                           vpaint_stroke_update_step,
2307                                           vpaint_stroke_done, event->type);
2308         
2309         /* add modal handler */
2310         WM_event_add_modal_handler(C, op);
2311
2312         op->type->modal(C, op, event);
2313         
2314         return OPERATOR_RUNNING_MODAL;
2315 }
2316
2317 static int vpaint_cancel(bContext *C, wmOperator *op)
2318 {
2319         paint_stroke_cancel(C, op);
2320
2321         return OPERATOR_CANCELLED;
2322 }
2323
2324 void PAINT_OT_vertex_paint(wmOperatorType *ot)
2325 {
2326         /* identifiers */
2327         ot->name= "Vertex Paint";
2328         ot->idname= "PAINT_OT_vertex_paint";
2329         
2330         /* api callbacks */
2331         ot->invoke= vpaint_invoke;
2332         ot->modal= paint_stroke_modal;
2333         /* ot->exec= vpaint_exec; <-- needs stroke property */
2334         ot->poll= vertex_paint_poll;
2335         ot->cancel= vpaint_cancel;
2336         
2337         /* flags */
2338         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2339
2340         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2341 }
2342
2343 /* ********************** weight from bones operator ******************* */
2344
2345 static int weight_from_bones_poll(bContext *C)
2346 {
2347         Object *ob= CTX_data_active_object(C);
2348
2349         return (ob && (ob->mode & OB_MODE_WEIGHT_PAINT) && modifiers_isDeformedByArmature(ob));
2350 }
2351
2352 static int weight_from_bones_exec(bContext *C, wmOperator *op)
2353 {
2354         Scene *scene= CTX_data_scene(C);
2355         Object *ob= CTX_data_active_object(C);
2356         Object *armob= modifiers_isDeformedByArmature(ob);
2357         Mesh *me= ob->data;
2358         int type= RNA_enum_get(op->ptr, "type");
2359
2360         create_vgroups_from_armature(op->reports, scene, ob, armob, type, (me->editflag & ME_EDIT_MIRROR_X));
2361
2362         DAG_id_tag_update(&me->id, 0);
2363         WM_event_add_notifier(C, NC_GEOM|ND_DATA, me);
2364
2365         return OPERATOR_FINISHED;
2366 }
2367
2368 void PAINT_OT_weight_from_bones(wmOperatorType *ot)
2369 {
2370         static EnumPropertyItem type_items[]= {
2371                 {ARM_GROUPS_AUTO, "AUTOMATIC", 0, "Automatic", "Automatic weights froms bones"},
2372                 {ARM_GROUPS_ENVELOPE, "ENVELOPES", 0, "From Envelopes", "Weights from envelopes with user defined radius"},
2373                 {0, NULL, 0, NULL, NULL}};
2374
2375         /* identifiers */
2376         ot->name= "Weight from Bones";
2377         ot->idname= "PAINT_OT_weight_from_bones";
2378         
2379         /* api callbacks */
2380         ot->exec= weight_from_bones_exec;
2381         ot->invoke= WM_menu_invoke;
2382         ot->poll= weight_from_bones_poll;
2383         
2384         /* flags */
2385         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2386
2387         /* properties */
2388         ot->prop= RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "Method to use for assigning weights.");
2389 }
2390