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