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