svn merge ^/trunk/blender -r40367:40368 --- raddish weight paint merge
[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         // don't forget to free it if it is unneeded
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         int i;
1266         for(i = 0; i < defbase_tot; i++) {
1267                 if(defbase_sel[i] && lock_flags[i]) {
1268                         return TRUE;
1269                 }
1270         }
1271         return FALSE;
1272 }
1273
1274
1275 #if 0 /* UNUSED */
1276 static int has_unselected_unlocked_bone_group(int defbase_tot, char *defbase_sel, int selected, char *lock_flags, char *vgroup_validmap) {
1277         int i;
1278         if(defbase_tot == selected) {
1279                 return FALSE;
1280         }
1281         for(i = 0; i < defbase_tot; i++) {
1282                 if(vgroup_validmap[i] && !defbase_sel[i] && !lock_flags[i]) {
1283                         return TRUE;
1284                 }
1285         }
1286         return FALSE;
1287 }
1288 #endif
1289
1290
1291 static void multipaint_selection(MDeformVert *dvert, float change, char *defbase_sel, int defbase_tot) {
1292         int i;
1293         MDeformWeight *dw;
1294         float val;
1295         // make sure they are all at most 1 after the change
1296         for(i = 0; i < defbase_tot; i++) {
1297                 if(defbase_sel[i]) {
1298                         dw = defvert_find_index(dvert, i);
1299                         if(dw && dw->weight) {
1300                                 val = dw->weight * change;
1301                                 if(val > 1) {
1302                                         /*  TODO: when the change is reduced, you need to recheck the earlier values to make sure they are not 0 (precision error) */
1303                                         change = 1.0f/dw->weight;
1304                                 }
1305                                 // the value should never reach zero while multi-painting if it was nonzero beforehand
1306                                 if(val <= 0) {
1307                                         return;
1308                                 }
1309                         }
1310                 }
1311         }
1312         // apply the valid change
1313         for(i = 0; i < defbase_tot; i++) {
1314                 if(defbase_sel[i]) {
1315                         dw = defvert_find_index(dvert, i);
1316                         if(dw && dw->weight) {
1317                                 dw->weight = dw->weight * change;
1318                         }
1319                 }
1320         }
1321 }
1322
1323 // move all change onto valid, unchanged groups.  If there is change left over, then return it.
1324 // assumes there are valid groups to shift weight onto
1325 static float redistribute_change(MDeformVert *ndv, char *change_status, int changeme, int changeto, const char *vgroup_validmap, float totchange, float total_valid, char do_auto_normalize) {
1326         float was_change;
1327         float change;
1328         float oldval;
1329         MDeformWeight *ndw;
1330         int i;
1331         do {
1332                 // assume there is no change until you see one
1333                 was_change = FALSE;
1334                 // change each group by the same amount each time
1335                 change = totchange/total_valid;
1336                 for(i = 0; i < ndv->totweight && total_valid && totchange; i++) {
1337                         ndw = (ndv->dw+i);
1338                         // change only the groups with a valid status
1339                         if(change_status[ndw->def_nr] == changeme) {
1340                                 oldval = ndw->weight;
1341                                 // if auto normalize is active, don't worry about upper bounds
1342                                 if(do_auto_normalize == FALSE && ndw->weight + change > 1) {
1343                                         totchange -= 1-ndw->weight;
1344                                         ndw->weight = 1;
1345                                         // stop the changes to this group
1346                                         change_status[ndw->def_nr] = changeto;
1347                                         total_valid--;
1348                                 } else if(ndw->weight + change < 0) { // check the lower bound
1349                                         totchange -= ndw->weight;
1350                                         ndw->weight = 0;
1351                                         change_status[ndw->def_nr] = changeto;
1352                                         total_valid--;
1353                                 } else {// a perfectly valid change occurred to ndw->weight
1354                                         totchange -= change;
1355                                         ndw->weight += change;
1356                                 }
1357                                 // see if there was a change
1358                                 if(oldval != ndw->weight) {
1359                                         was_change = TRUE;
1360                                 }
1361                         }
1362                 }
1363         // don't go again if there was no change, if there is no valid group, or there is no change left
1364         }while(was_change && total_valid && totchange);
1365         // left overs
1366         (void)vgroup_validmap;
1367         return totchange;
1368 }
1369
1370 // observe the changes made to the weights of groups.
1371 // make sure all locked groups on the vertex have the same deformation
1372 // by moving the changes made to groups onto other unlocked groups
1373 static void enforce_locks(MDeformVert *odv, MDeformVert *ndv, int defbase_tot,
1374                           const char *lock_flags, const char *vgroup_validmap, char do_auto_normalize)
1375 {
1376         float totchange = 0.0f;
1377         float totchange_allowed = 0.0f;
1378         float left_over;
1379
1380         int total_valid = 0;
1381         int total_changed = 0;
1382         int i;
1383         MDeformWeight *ndw;
1384         MDeformWeight *odw;
1385         MDeformWeight *ndw2;
1386         MDeformWeight *odw2;
1387         int designatedw = -1;
1388         int designatedw_changed = FALSE;
1389         float storedw;
1390         char *change_status;
1391         char new_weight_has_zero = FALSE;
1392
1393         if(!lock_flags || !has_locked_group(ndv, lock_flags)) {
1394                 return;
1395         }
1396         // record if a group was changed, unlocked and not changed, or locked
1397         change_status = MEM_callocN(sizeof(char)*defbase_tot, "unlocked_unchanged");
1398
1399         for(i = 0; i < defbase_tot; i++) {
1400                 ndw = defvert_find_index(ndv, i);
1401                 odw = defvert_find_index(odv, i);
1402                 // the weights are zero, so we can assume a lot
1403                 if(!ndw || !odw) {
1404                         if (!lock_flags[i] && vgroup_validmap[i]){
1405                                 defvert_verify_index(odv, i);
1406                                 defvert_verify_index(ndv, i);
1407                                 total_valid++;
1408                                 change_status[i] = 1; // can be altered while redistributing
1409                         }
1410                         continue;
1411                 }
1412                 // locked groups should not be changed
1413                 if(lock_flags[i]) {
1414                         ndw->weight = odw->weight;
1415                 }
1416                 else if(ndw->weight != odw->weight) { // changed groups are handled here
1417                         totchange += ndw->weight - odw->weight;
1418                         change_status[i] = 2; // was altered already
1419                         total_changed++;
1420                         if(ndw->weight == 0) {
1421                                 new_weight_has_zero = TRUE;
1422                         }
1423                         else if(designatedw == -1){
1424                                 designatedw = i;
1425                         }
1426                 } // unchanged, unlocked bone groups are handled here
1427                 else if (vgroup_validmap[i]){
1428                         totchange_allowed += ndw->weight;
1429                         total_valid++;
1430                         change_status[i] = 1; // can be altered while redistributing
1431                 }
1432         }
1433         // if there was any change, redistribute it
1434         if(total_changed) {
1435                 // auto normalize will allow weights to temporarily go above 1 in redistribution
1436                 if(vgroup_validmap && total_changed < 0 && total_valid) {
1437                         totchange_allowed = total_valid;
1438                 }
1439                 // there needs to be change allowed, or you should not bother
1440                 if(totchange_allowed) {
1441                         // the way you modify the unlocked+unchanged groups is different depending
1442                         // on whether or not you are painting the weight(s) up or down
1443                         if(totchange < 0) {
1444                                 totchange_allowed = total_valid - totchange_allowed;
1445                         }
1446                         else {
1447                                 totchange_allowed *= -1;
1448                         }
1449                         left_over = 0;
1450                         if(fabsf(totchange_allowed) < fabsf(totchange)) {
1451                                 // this amount goes back onto the changed, unlocked weights
1452                                 left_over = fabsf(fabsf(totchange) - fabsf(totchange_allowed));
1453                                 if(totchange > 0) {
1454                                         left_over *= -1;
1455                                 }
1456                         }
1457                         else {
1458                                 // all of the change will be permitted
1459                                 totchange_allowed = -totchange;
1460                         }
1461                         // move the weight evenly between the allowed groups, move excess back onto the used groups based on the change
1462                         totchange_allowed = redistribute_change(ndv, change_status, 1, -1, vgroup_validmap, totchange_allowed, total_valid, do_auto_normalize);
1463                         left_over += totchange_allowed;
1464                         if(left_over) {
1465                                 // more than one nonzero weights were changed with the same ratio, so keep them changed that way!
1466                                 if(total_changed > 1 && !new_weight_has_zero && designatedw >= 0) {
1467                                         // this dw is special, it is used as a base to determine how to change the others
1468                                         ndw = defvert_find_index(ndv, designatedw);
1469                                         odw = defvert_find_index(odv, designatedw);
1470                                         storedw = ndw->weight;
1471                                         for(i = 0; i < ndv->totweight; i++) {
1472                                                 if(change_status[ndw->def_nr] == 2) {
1473                                                         odw2 = (odv->dw+i);
1474                                                         ndw2 = (ndv->dw+i);
1475                                                         if(!designatedw_changed) {
1476                                                                 ndw->weight = (totchange_allowed + odw->weight + odw2->weight)/(1 + ndw2->weight/ndw->weight);
1477                                                                 designatedw_changed = TRUE;
1478                                                         }
1479                                                         ndw2->weight = ndw->weight * ndw2->weight / storedw;
1480                                                 }
1481                                         }
1482                                 }
1483                                 // a weight was changed to zero, only one weight was changed, or designatedw is still -1
1484                                 // put weight back as evenly as possible
1485                                 else {
1486                                         redistribute_change(ndv, change_status, 2, -2, vgroup_validmap, left_over, total_changed, do_auto_normalize);
1487                                 }
1488                         }
1489                 }
1490                 else {
1491                         // reset the weights
1492                         for(i = 0; i < ndv->totweight; i++) {
1493                                 ndv->dw[i].weight = odv->dw[i].weight;
1494                         }
1495                 }
1496         }
1497
1498         MEM_freeN(change_status);
1499 }
1500
1501 // multi-paint's initial, potential change is computed here based on the user's stroke
1502 static float get_mp_change(MDeformVert *odv, char *defbase_sel, float brush_change) {
1503         float selwsum = 0.0f;
1504         int i;
1505         MDeformWeight *dw;
1506         for(i=0; i < odv->totweight; i++) {
1507                 if(defbase_sel[(dw= &odv->dw[i])->def_nr]) {
1508                         selwsum += dw->weight;
1509                 }
1510         }
1511         if(selwsum && selwsum+brush_change > 0) {
1512                 return (selwsum+brush_change)/selwsum;
1513         }
1514         return 0.0f;
1515 }
1516
1517 // change the weights back to the wv's weights
1518 // it assumes you already have the correct pointer index
1519 static void reset_to_prev(MDeformVert *wv, MDeformVert *dv) {
1520         int i;
1521         MDeformWeight *d;
1522         MDeformWeight *w;
1523         for(i = 0; i < dv->totweight; i++) {
1524                 d= &dv->dw[i];
1525                 w= defvert_find_index(wv, d->def_nr);
1526                 /* if there was no w when there is a d, then the old weight was 0 */
1527                 d->weight = w ? w->weight : 0.0f;
1528         }
1529 }
1530
1531 static void clamp_weights(MDeformVert *dvert) {
1532         int i;
1533         for (i = 0; i < dvert->totweight; i++) {
1534                 CLAMP((dvert->dw+i)->weight, 0.0f, 1.0f);
1535         }
1536 }
1537
1538 /* struct to avoid passing many args each call to do_weight_paint_vertex()
1539  * this _could_ be made a part of the operators 'WPaintData' struct, or at
1540  * least a member, but for now keep its own struct, initialized on every
1541  * paint stroke update - campbell */
1542 typedef struct WeightPaintInfo {
1543
1544         int defbase_tot;
1545
1546         /* both must add up to 'defbase_tot' */
1547         int defbase_tot_sel;
1548         int defbase_tot_unsel;
1549
1550         int vgroup_mirror; /* mirror group or -1 */
1551
1552         char *lock_flags;  /* boolean array for locked bones,
1553                                                 * length of defbase_tot */
1554         char *defbase_sel; /* boolean array for selected bones,
1555                                                 * length of defbase_tot */
1556
1557         char *vgroup_validmap; /* same as WeightPaintData.vgroup_validmap,
1558                                 * only added here for convenience */
1559
1560         char do_flip;
1561         char do_multipaint;
1562         char do_auto_normalize;
1563 } WeightPaintInfo;
1564
1565 /* fresh start to make multi-paint and locking modular */
1566 /* returns TRUE if it thinks you need to reset the weights due to
1567  * normalizing while multi-painting */
1568 static int apply_mp_locks_normalize(Mesh *me, const WeightPaintInfo *wpi,
1569                                     const int index,
1570                                     MDeformWeight *dw, MDeformWeight *tdw,
1571                                     float change, float oldChange,
1572                                     float oldw, float neww)
1573 {
1574         MDeformVert *dv= me->dvert+index;
1575         MDeformVert dv_test= {NULL};
1576
1577         dv_test.dw= MEM_dupallocN(dv->dw);
1578         dv_test.flag = dv->flag;
1579         dv_test.totweight = dv->totweight;
1580         /* do not multi-paint if a locked group is selected or the active group is locked
1581          * !lock_flags[dw->def_nr] helps if nothing is selected, but active group is locked */
1582         if((wpi->lock_flags == NULL) || (wpi->lock_flags[dw->def_nr] == FALSE && has_locked_group_selected(wpi->defbase_tot, wpi->defbase_sel, wpi->lock_flags) == FALSE)) {
1583                 if(wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1584                         if(change && change!=1) {
1585                                 multipaint_selection(dv, change, wpi->defbase_sel, wpi->defbase_tot);
1586                         }
1587                 }
1588                 else { /* this lets users paint normally, but don't let them paint locked groups */
1589                         dw->weight = neww;
1590                 }
1591         }
1592         clamp_weights(dv);
1593
1594         enforce_locks(&dv_test, dv, wpi->defbase_tot, wpi->lock_flags, wpi->vgroup_validmap, wpi->do_auto_normalize);
1595
1596         do_weight_paint_auto_normalize_all_groups(dv, wpi->vgroup_validmap, wpi->do_auto_normalize);
1597
1598         if(oldChange && wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1599                 if(tdw->weight != oldw) {
1600                         if(neww > oldw) {
1601                                 if(tdw->weight <= oldw) {
1602                                         MEM_freeN(dv_test.dw);
1603                                         return TRUE;
1604                                 }
1605                         }
1606                         else {
1607                                 if(tdw->weight >= oldw) {
1608                                         MEM_freeN(dv_test.dw);
1609                                         return TRUE;
1610                                 }
1611                         }
1612                 }
1613         }
1614         MEM_freeN(dv_test.dw);
1615         return FALSE;
1616 }
1617
1618 /* within the current dvert index, get the dw that is selected and has a weight
1619  * above 0, this helps multi-paint */
1620 static int get_first_selected_nonzero_weight(MDeformVert *dvert, char *defbase_sel) {
1621         int i;
1622         MDeformWeight *dw;
1623         for(i=0; i< dvert->totweight; i++) {
1624                 dw = &dvert->dw[i];
1625                 if(defbase_sel[dw->def_nr] && dw->weight > 0) {
1626                         return i;
1627                 }
1628         }
1629         return -1;
1630 }
1631
1632
1633 static char *wpaint_make_validmap(Object *ob);
1634
1635
1636 static void do_weight_paint_vertex( /* vars which remain the same for every vert */
1637                                    VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
1638                                     /* vars which change on each stroke */
1639                                    int index, float alpha, float paintweight
1640                                    )
1641 {
1642         Mesh *me= ob->data;
1643         
1644         MDeformWeight *dw, *uw;
1645         int vgroup= ob->actdef-1;
1646
1647         if(wp->flag & VP_ONLYVGROUP) {
1648                 dw= defvert_find_index(me->dvert+index, vgroup);
1649                 uw= defvert_find_index(wp->wpaint_prev+index, vgroup);
1650         }
1651         else {
1652                 dw= defvert_verify_index(me->dvert+index, vgroup);
1653                 uw= defvert_verify_index(wp->wpaint_prev+index, vgroup);
1654         }
1655         if(dw==NULL || uw==NULL)
1656                 return;
1657
1658         /* TODO: De-duplicate the simple weight paint - jason */
1659         /* ... or not, since its <10 SLOC - campbell */
1660
1661         /* If there are no locks or multipaint,
1662          * then there is no need to run the more complicated checks */
1663         if((wpi->do_multipaint == FALSE || wpi->defbase_tot_sel <= 1) && (wpi->lock_flags == NULL || has_locked_group(&me->dvert[index], wpi->lock_flags) == FALSE)) {
1664                 wpaint_blend(wp, dw, uw, alpha, paintweight, wpi->do_flip, FALSE);
1665                 do_weight_paint_auto_normalize_all_groups(me->dvert+index, wpi->vgroup_validmap, wpi->do_auto_normalize);
1666
1667                 if(me->editflag & ME_EDIT_MIRROR_X) {   /* x mirror painting */
1668                         int j= mesh_get_x_mirror_vert(ob, index);
1669                         if(j>=0) {
1670                                 /* copy, not paint again */
1671                                 uw= defvert_verify_index(me->dvert+j, (wpi->vgroup_mirror != -1) ? wpi->vgroup_mirror : vgroup);
1672                                         
1673                                 uw->weight= dw->weight;
1674
1675                                 do_weight_paint_auto_normalize_all_groups(me->dvert+j, wpi->vgroup_validmap, wpi->do_auto_normalize);
1676                         }
1677                 }
1678         }
1679         else {
1680                 /* use locks and/or multipaint */
1681                 float oldw;
1682                 float neww;
1683                 float testw=0;
1684                 float change = 0;
1685                 float oldChange = 0;
1686                 int i;
1687                 MDeformWeight *tdw = NULL, *tuw;
1688                 MDeformVert dv= {NULL};
1689
1690                 oldw = dw->weight;
1691                 wpaint_blend(wp, dw, uw, alpha, paintweight, wpi->do_flip, wpi->do_multipaint && wpi->defbase_tot_sel >1);
1692                 neww = dw->weight;
1693                 dw->weight = oldw;
1694                 
1695                 // setup multi-paint
1696                 if(wpi->defbase_tot_sel > 1 && wpi->do_multipaint) {
1697                         dv.dw= MEM_dupallocN((me->dvert+index)->dw);
1698                         dv.flag = me->dvert[index].flag;
1699                         dv.totweight = (me->dvert+index)->totweight;
1700                         tdw = dw;
1701                         tuw = uw;
1702                         change = get_mp_change(wp->wpaint_prev+index, wpi->defbase_sel, neww - oldw);
1703                         if(change) {
1704                                 if(!tdw->weight) {
1705                                         i = get_first_selected_nonzero_weight(me->dvert+index, wpi->defbase_sel);
1706                                         if(i>=0) {
1707                                                 tdw = &(me->dvert[index].dw[i]);
1708                                                 tuw = defvert_verify_index(wp->wpaint_prev+index, tdw->def_nr);
1709                                         }
1710                                         else {
1711                                                 change = 0;
1712                                         }
1713                                 }
1714                                 if(change && tuw->weight && tuw->weight * change) {
1715                                         if(tdw->weight != tuw->weight) {
1716                                                 oldChange = tdw->weight/tuw->weight;
1717                                                 testw = tuw->weight*change;
1718                                                 if( testw > tuw->weight ) {
1719                                                         if(change > oldChange) {
1720                                                                 /* reset the weights and use the new change */
1721                                                                 reset_to_prev(wp->wpaint_prev+index, me->dvert+index);
1722                                                         }
1723                                                         else {
1724                                                                 /* the old change was more significant, so set
1725                                                                  * the change to 0 so that it will not do another multi-paint */
1726                                                                 change = 0;
1727                                                         }
1728                                                 }
1729                                                 else {
1730                                                         if(change < oldChange) {
1731                                                                 reset_to_prev(wp->wpaint_prev+index, me->dvert+index);
1732                                                         }
1733                                                         else {
1734                                                                 change = 0;
1735                                                         }
1736                                                 }
1737                                         }
1738                                 }
1739                                 else {
1740                                         change = 0;
1741                                 }
1742                         }
1743                 }
1744                 
1745                 if(apply_mp_locks_normalize(me, wpi, index, dw, tdw, change, oldChange, oldw, neww)) {
1746                         reset_to_prev(&dv, me->dvert+index);
1747                         change = 0;
1748                         oldChange = 0;
1749                 }
1750                 if(dv.dw) {
1751                         MEM_freeN(dv.dw);
1752                 }
1753                 /* dvert may have been altered greatly */
1754                 dw = defvert_find_index(me->dvert+index, vgroup);
1755
1756                 if(me->editflag & ME_EDIT_MIRROR_X) {   /* x mirror painting */
1757                         int j= mesh_get_x_mirror_vert(ob, index);
1758                         if(j>=0) {
1759                                 /* copy, not paint again */
1760                                 uw= defvert_verify_index(me->dvert+j, (wpi->vgroup_mirror != -1) ? wpi->vgroup_mirror : vgroup);
1761                                 
1762                                 //uw->weight= dw->weight;
1763                                 
1764                                 apply_mp_locks_normalize(me, wpi, j, uw, tdw, change, oldChange, oldw, neww);
1765                         }
1766                 }
1767         }
1768 }
1769
1770
1771 /* *************** set wpaint operator ****************** */
1772
1773 static int set_wpaint(bContext *C, wmOperator *UNUSED(op))              /* toggle */
1774 {               
1775         Object *ob= CTX_data_active_object(C);
1776         Scene *scene= CTX_data_scene(C);
1777         VPaint *wp= scene->toolsettings->wpaint;
1778         Mesh *me;
1779         
1780         me= get_mesh(ob);
1781         if(ob->id.lib || me==NULL) return OPERATOR_PASS_THROUGH;
1782         
1783         if(ob->mode & OB_MODE_WEIGHT_PAINT) ob->mode &= ~OB_MODE_WEIGHT_PAINT;
1784         else ob->mode |= OB_MODE_WEIGHT_PAINT;
1785         
1786         
1787         /* Weightpaint works by overriding colors in mesh,
1788                 * so need to make sure we recalc on enter and
1789                 * exit (exit needs doing regardless because we
1790                                 * should redeform).
1791                 */
1792         DAG_id_tag_update(&me->id, 0);
1793         
1794         if(ob->mode & OB_MODE_WEIGHT_PAINT) {
1795                 Object *par;
1796                 
1797                 if(wp==NULL)
1798                         wp= scene->toolsettings->wpaint= new_vpaint(1);
1799
1800                 paint_init(&wp->paint, PAINT_CURSOR_WEIGHT_PAINT);
1801                 paint_cursor_start(C, weight_paint_poll);
1802                 
1803                 //BMESH_TODO mesh_octree_table(ob, NULL, NULL, 's');
1804                 
1805                 /* verify if active weight group is also active bone */
1806                 par= modifiers_isDeformedByArmature(ob);
1807                 if(par && (par->mode & OB_MODE_POSE)) {
1808                         bArmature *arm= par->data;
1809
1810                         if(arm->act_bone)
1811                                 ED_vgroup_select_by_name(ob, arm->act_bone->name);
1812                 }
1813         }
1814         else {
1815                 //BMESH_TODO mesh_octree_table(NULL, NULL, NULL, 'e');
1816                 //BMESH_TODO mesh_mirrtopo_table(NULL, 'e');
1817         }
1818         
1819         WM_event_add_notifier(C, NC_SCENE|ND_MODE, scene);
1820         
1821         return OPERATOR_FINISHED;
1822 }
1823
1824 /* for switching to/from mode */
1825 static int paint_poll_test(bContext *C)
1826 {
1827         if(CTX_data_edit_object(C))
1828                 return 0;
1829         if(CTX_data_active_object(C)==NULL)
1830                 return 0;
1831         return 1;
1832 }
1833
1834 void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
1835 {
1836         
1837         /* identifiers */
1838         ot->name= "Weight Paint Mode";
1839         ot->idname= "PAINT_OT_weight_paint_toggle";
1840         
1841         /* api callbacks */
1842         ot->exec= set_wpaint;
1843         ot->poll= paint_poll_test;
1844         
1845         /* flags */
1846         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1847         
1848 }
1849
1850 /* ************ weight paint operator ********** */
1851
1852 struct WPaintData {
1853         ViewContext vc;
1854         int *indexar;
1855         int vgroup_mirror;
1856         float *vertexcosnos;
1857         float wpimat[3][3];
1858         
1859         /*variables for auto normalize*/
1860         int auto_normalize;
1861         char *vgroup_validmap; /*stores if vgroups tie to deforming bones or not*/
1862         char *lock_flags;
1863         int defbase_tot;
1864 };
1865
1866 static char *wpaint_make_validmap(Object *ob)
1867 {
1868         bDeformGroup *dg;
1869         ModifierData *md;
1870         char *vgroup_validmap;
1871         GHash *gh = BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp, "wpaint_make_validmap gh");
1872         int i = 0, step1=1;
1873
1874         /*add all names to a hash table*/
1875         for (dg=ob->defbase.first, i=0; dg; dg=dg->next, i++) {
1876                 BLI_ghash_insert(gh, dg->name, NULL);
1877         }
1878
1879         if (!i)
1880                 return NULL;
1881
1882         vgroup_validmap= MEM_callocN(i, "wpaint valid map");
1883
1884         /*now loop through the armature modifiers and identify deform bones*/
1885         for (md = ob->modifiers.first; md; md= !md->next && step1 ? (step1=0), modifiers_getVirtualModifierList(ob) : md->next) {
1886                 if (!(md->mode & (eModifierMode_Realtime|eModifierMode_Virtual)))
1887                         continue;
1888
1889                 if (md->type == eModifierType_Armature) 
1890                 {
1891                         ArmatureModifierData *amd= (ArmatureModifierData*) md;
1892
1893                         if(amd->object && amd->object->pose) {
1894                                 bPose *pose= amd->object->pose;
1895                                 bPoseChannel *chan;
1896                                 
1897                                 for (chan=pose->chanbase.first; chan; chan=chan->next) {
1898                                         if (chan->bone->flag & BONE_NO_DEFORM)
1899                                                 continue;
1900
1901                                         if (BLI_ghash_haskey(gh, chan->name)) {
1902                                                 BLI_ghash_remove(gh, chan->name, NULL, NULL);
1903                                                 BLI_ghash_insert(gh, chan->name, SET_INT_IN_POINTER(1));
1904                                         }
1905                                 }
1906                         }
1907                 }
1908         }
1909         
1910         /*add all names to a hash table*/
1911         for (dg=ob->defbase.first, i=0; dg; dg=dg->next, i++) {
1912                 if (BLI_ghash_lookup(gh, dg->name) != NULL) {
1913                         vgroup_validmap[i] = TRUE;
1914                 }
1915         }
1916
1917         BLI_ghash_free(gh, NULL, NULL);
1918
1919         return vgroup_validmap;
1920 }
1921
1922 static int wpaint_stroke_test_start(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1923 {
1924         Scene *scene= CTX_data_scene(C);
1925         struct PaintStroke *stroke = op->customdata;
1926         ToolSettings *ts= CTX_data_tool_settings(C);
1927         VPaint *wp= ts->wpaint;
1928         Object *ob= CTX_data_active_object(C);
1929         struct WPaintData *wpd;
1930         Mesh *me;
1931         float mat[4][4], imat[4][4];
1932         
1933         if(scene->obedit) return OPERATOR_CANCELLED;
1934         
1935         me= get_mesh(ob);
1936         if(me==NULL || me->totface==0) return OPERATOR_PASS_THROUGH;
1937         
1938         /*we can't assume mfaces have a correct origindex layer that indices to mpolys.
1939           so instead we have to regenerate the tesselation faces altogether.*/
1940         me->totface = mesh_recalcTesselation(&me->fdata, &me->ldata, &me->pdata, 
1941                 me->mvert, me->totface, me->totloop, me->totpoly, 1, 0);
1942         mesh_update_customdata_pointers(me);
1943         makeDerivedMesh(scene, ob, NULL, CD_MASK_BAREMESH, 0);
1944
1945         /* if nothing was added yet, we make dverts and a vertex deform group */
1946         if (!me->dvert) {
1947                 ED_vgroup_data_create(&me->id);
1948                 WM_event_add_notifier(C, NC_GEOM|ND_DATA, me);
1949         }
1950         
1951         /* make mode data storage */
1952         wpd= MEM_callocN(sizeof(struct WPaintData), "WPaintData");
1953         paint_stroke_set_mode_data(stroke, wpd);
1954         view3d_set_viewcontext(C, &wpd->vc);
1955         wpd->vgroup_mirror= -1;
1956         
1957         /*set up auto-normalize, and generate map for detecting which
1958           vgroups affect deform bones*/
1959         wpd->auto_normalize = ts->auto_normalize;
1960         wpd->defbase_tot = BLI_countlist(&ob->defbase);
1961         wpd->lock_flags = gen_lock_flags(ob, wpd->defbase_tot);
1962         if (wpd->auto_normalize || ts->multipaint || wpd->lock_flags)
1963                 wpd->vgroup_validmap = wpaint_make_validmap(ob);
1964         
1965         //      if(qual & LR_CTRLKEY) {
1966         //              sample_wpaint(scene, ar, v3d, 0);
1967         //              return;
1968         //      }
1969         //      if(qual & LR_SHIFTKEY) {
1970         //              sample_wpaint(scene, ar, v3d, 1);
1971         //              return;
1972         //      }
1973         
1974         /* ALLOCATIONS! no return after this line */
1975         /* painting on subsurfs should give correct points too, this returns me->totvert amount */
1976         wpd->vertexcosnos= mesh_get_mapped_verts_nors(scene, ob);
1977         wpd->indexar= get_indexarray(me);
1978         copy_wpaint_prev(wp, me->dvert, me->totvert);
1979         
1980         /* this happens on a Bone select, when no vgroup existed yet */
1981         if(ob->actdef<=0) {
1982                 Object *modob;
1983                 if((modob = modifiers_isDeformedByArmature(ob))) {
1984                         Bone *actbone= ((bArmature *)modob->data)->act_bone;
1985                         if(actbone) {
1986                                 bPoseChannel *pchan= get_pose_channel(modob->pose, actbone->name);
1987
1988                                 if(pchan) {
1989                                         bDeformGroup *dg= defgroup_find_name(ob, pchan->name);
1990                                         if(dg==NULL)
1991                                                 dg= ED_vgroup_add_name(ob, pchan->name);        /* sets actdef */
1992                                         else
1993                                                 ob->actdef= 1 + defgroup_find_index(ob, dg);
1994                                 }
1995                         }
1996                 }
1997         }
1998         if(ob->defbase.first==NULL) {
1999                 ED_vgroup_add(ob);
2000         }
2001         
2002         //      if(ob->lay & v3d->lay); else error("Active object is not in this layer");
2003         
2004         /* imat for normals */
2005         mul_m4_m4m4(mat, ob->obmat, wpd->vc.rv3d->viewmat);
2006         invert_m4_m4(imat, mat);
2007         copy_m3_m4(wpd->wpimat, imat);
2008         
2009         /* if mirror painting, find the other group */
2010         if(me->editflag & ME_EDIT_MIRROR_X) {
2011                 wpaint_mirror_vgroup_ensure(ob, &wpd->vgroup_mirror);
2012         }
2013         
2014         return 1;
2015 }
2016
2017 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2018 {
2019         ToolSettings *ts= CTX_data_tool_settings(C);
2020         VPaint *wp= ts->wpaint;
2021         Brush *brush = paint_brush(&wp->paint);
2022         struct WPaintData *wpd= paint_stroke_mode_data(stroke);
2023         ViewContext *vc;
2024         Object *ob;
2025         Mesh *me;
2026         float mat[4][4];
2027         float paintweight;
2028         int *indexar;
2029         int totindex, index, totw;
2030         float alpha;
2031         float mval[2], pressure;
2032         int use_vert_sel;
2033
2034         /* intentionally dont initialize as NULL, make sure we initialize all members below */
2035         WeightPaintInfo wpi;
2036
2037         /* cannot paint if there is no stroke data */
2038         if (wpd == NULL) {
2039                 // XXX: force a redraw here, since even though we can't paint, 
2040                 // at least view won't freeze until stroke ends
2041                 ED_region_tag_redraw(CTX_wm_region(C));
2042                 return;
2043         }
2044                 
2045         vc= &wpd->vc;
2046         ob= vc->obact;
2047         me= ob->data;
2048         indexar= wpd->indexar;
2049         
2050         view3d_operator_needs_opengl(C);
2051                 
2052         /* load projection matrix */
2053         mul_m4_m4m4(mat, ob->obmat, vc->rv3d->persmat);
2054
2055         pressure = RNA_float_get(itemptr, "pressure");
2056         RNA_float_get_array(itemptr, "mouse", mval);
2057         mval[0]-= vc->ar->winrct.xmin;
2058         mval[1]-= vc->ar->winrct.ymin;
2059
2060
2061
2062         /* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
2063         wpi.defbase_tot=        wpd->defbase_tot;
2064         wpi.defbase_sel=        MEM_mallocN(wpi.defbase_tot*sizeof(char), "wpi.defbase_sel");
2065         wpi.defbase_tot_sel=    get_selected_defgroups(ob, wpi.defbase_sel, wpi.defbase_tot);
2066         if(wpi.defbase_tot_sel == 0 && ob->actdef) wpi.defbase_tot_sel = 1;
2067         wpi.defbase_tot_unsel=  wpi.defbase_tot - wpi.defbase_tot_sel;
2068         wpi.vgroup_mirror=      wpd->vgroup_mirror;
2069         wpi.lock_flags=         wpd->lock_flags;
2070         wpi.vgroup_validmap=    wpd->vgroup_validmap;
2071         wpi.do_flip=            RNA_boolean_get(itemptr, "pen_flip");
2072         wpi.do_multipaint=      (ts->multipaint != 0);
2073         wpi.do_auto_normalize=  (ts->auto_normalize != 0);
2074         /* *** done setting up WeightPaintInfo *** */
2075
2076
2077
2078         swap_m4m4(wpd->vc.rv3d->persmat, mat);
2079
2080         use_vert_sel= (me->editflag & ME_EDIT_VERT_SEL) != 0;
2081
2082         /* which faces are involved */
2083         if(wp->flag & VP_AREA) {
2084                 // Ugly hack, to avoid drawing vertex index when getting the face index buffer - campbell
2085                 me->editflag &= ~ME_EDIT_VERT_SEL;
2086                 totindex= sample_backbuf_area(vc, indexar, me->totface, mval[0], mval[1], brush_size(brush));
2087                 me->editflag |= use_vert_sel ? ME_EDIT_VERT_SEL : 0;
2088         }
2089         else {
2090                 indexar[0]= view3d_sample_backbuf(vc, mval[0], mval[1]);
2091                 if(indexar[0]) totindex= 1;
2092                 else totindex= 0;
2093         }
2094                         
2095         if(wp->flag & VP_COLINDEX) {
2096                 for(index=0; index<totindex; index++) {
2097                         if(indexar[index] && indexar[index]<=me->totpoly) {
2098                                 MPoly *mpoly= ((MPoly *)me->mpoly) + (indexar[index]-1);
2099                                                 
2100                                 if(mpoly->mat_nr!=ob->actcol-1) {
2101                                         indexar[index]= 0;
2102                                 }
2103                         }
2104                 }
2105         }
2106                         
2107         if((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
2108                 for(index=0; index<totindex; index++) {
2109                         if(indexar[index] && indexar[index]<=me->totpoly) {
2110                                 MPoly *mpoly= ((MPoly *)me->mpoly) + (indexar[index]-1);
2111                                                 
2112                                 if((mpoly->flag & ME_FACE_SEL)==0) {
2113                                         indexar[index]= 0;
2114                                 }
2115                         }                                       
2116                 }
2117         }
2118                         
2119         /* make sure each vertex gets treated only once */
2120         /* and calculate filter weight */
2121         totw= 0;
2122         if(brush->vertexpaint_tool==VP_BLUR) 
2123                 paintweight= 0.0f;
2124         else
2125                 paintweight= ts->vgroup_weight;
2126                         
2127         for(index=0; index<totindex; index++) {
2128                 if(indexar[index] && indexar[index]<=me->totpoly) {
2129                         MPoly *mpoly= me->mpoly + (indexar[index]-1);
2130                         MLoop *ml = me->mloop + mpoly->loopstart;
2131                         int i;
2132
2133                         if(use_vert_sel) {
2134                                 for (i=0; i<mpoly->totloop; i++, ml++) {
2135                                         me->dvert[ml->v].flag = (me->mvert[ml->v].flag & SELECT);
2136                                 }
2137                         }
2138                         else {
2139                                 for (i=0; i<mpoly->totloop; i++, ml++) {
2140                                         me->dvert[ml->v].flag = 1;
2141                                 }
2142                         }
2143                                         
2144                         if(brush->vertexpaint_tool==VP_BLUR) {
2145                                 MDeformWeight *dw, *(*dw_func)(MDeformVert *, const int);
2146                                                 
2147                                 if(wp->flag & VP_ONLYVGROUP)
2148                                         dw_func= (MDeformWeight *(*)(MDeformVert *, const int))defvert_find_index;
2149                                 else
2150                                         dw_func= defvert_verify_index;
2151                                                 
2152                                 ml = me->mloop + mpoly->loopstart;
2153                                 for (i=0; i<mpoly->totloop; i++, ml++) {
2154                                         dw = dw_func(me->dvert+ml->v, ob->actdef-1);
2155                                         if (dw) {
2156                                                 paintweight += dw->weight;
2157                                                 totw++;
2158                                         }
2159                                 }
2160                         }
2161                 }
2162         }
2163                         
2164         if(brush->vertexpaint_tool==VP_BLUR) 
2165                 paintweight/= (float)totw;
2166                         
2167         for(index=0; index<totindex; index++) {
2168                 if(indexar[index] && indexar[index]<=me->totpoly) {
2169                         MPoly *mpoly= me->mpoly + (indexar[index]-1);
2170                         MLoop *ml=me->mloop+mpoly->loopstart;
2171                         int i;
2172
2173                         for (i=0; i<mpoly->totloop; i++, ml++) {
2174                                 unsigned int vidx= ml->v;
2175                                 if (me->dvert[vidx].flag) {
2176                                         alpha= calc_vp_alpha_dl(wp, vc, wpd->wpimat, wpd->vertexcosnos+6*vidx, mval, pressure);
2177                                         if(alpha != 0.0f) {
2178                                                 do_weight_paint_vertex(wp, ob, &wpi, vidx, alpha, paintweight);
2179                                         }
2180                                         me->dvert[vidx].flag= 0;
2181                                 }
2182                         }
2183                 }
2184         }
2185
2186
2187         /* *** free wpi members */
2188         MEM_freeN(wpi.defbase_sel);
2189         /* *** dont freeing wpi members */
2190
2191
2192         swap_m4m4(vc->rv3d->persmat, mat);
2193                         
2194         DAG_id_tag_update(ob->data, 0);
2195         ED_region_tag_redraw(vc->ar);
2196 }
2197
2198 static void wpaint_stroke_done(bContext *C, struct PaintStroke *stroke)
2199 {
2200         ToolSettings *ts= CTX_data_tool_settings(C);
2201         Object *ob= CTX_data_active_object(C);
2202         struct WPaintData *wpd= paint_stroke_mode_data(stroke);
2203         
2204         if(wpd) {
2205                 if(wpd->vertexcosnos)
2206                         MEM_freeN(wpd->vertexcosnos);
2207                 MEM_freeN(wpd->indexar);
2208                 
2209                 if (wpd->vgroup_validmap)
2210                         MEM_freeN(wpd->vgroup_validmap);
2211                 if(wpd->lock_flags)
2212                         MEM_freeN(wpd->lock_flags);
2213
2214                 MEM_freeN(wpd);
2215         }
2216         
2217         /* frees prev buffer */
2218         copy_wpaint_prev(ts->wpaint, NULL, 0);
2219         
2220         /* and particles too */
2221         if(ob->particlesystem.first) {
2222                 ParticleSystem *psys;
2223                 int i;
2224                 
2225                 for(psys= ob->particlesystem.first; psys; psys= psys->next) {
2226                         for(i=0; i<PSYS_TOT_VG; i++) {
2227                                 if(psys->vgroup[i]==ob->actdef) {
2228                                         psys->recalc |= PSYS_RECALC_RESET;
2229                                         break;
2230                                 }
2231                         }
2232                 }
2233         }
2234         
2235         DAG_id_tag_update(ob->data, 0);
2236 }
2237
2238
2239 static int wpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2240 {
2241         
2242         op->customdata = paint_stroke_new(C, NULL, wpaint_stroke_test_start,
2243                                           wpaint_stroke_update_step,
2244                                           wpaint_stroke_done, event->type);
2245         
2246         /* add modal handler */
2247         WM_event_add_modal_handler(C, op);
2248
2249         op->type->modal(C, op, event);
2250         
2251         return OPERATOR_RUNNING_MODAL;
2252 }
2253
2254 static int wpaint_cancel(bContext *C, wmOperator *op)
2255 {
2256         paint_stroke_cancel(C, op);
2257
2258         return OPERATOR_CANCELLED;
2259 }
2260
2261 void PAINT_OT_weight_paint(wmOperatorType *ot)
2262 {
2263         
2264         /* identifiers */
2265         ot->name= "Weight Paint";
2266         ot->idname= "PAINT_OT_weight_paint";
2267         
2268         /* api callbacks */
2269         ot->invoke= wpaint_invoke;
2270         ot->modal= paint_stroke_modal;
2271         /* ot->exec= vpaint_exec; <-- needs stroke property */
2272         ot->poll= weight_paint_poll;
2273         ot->cancel= wpaint_cancel;
2274         
2275         /* flags */
2276         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2277
2278         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2279 }
2280
2281 static int weight_paint_set_exec(bContext *C, wmOperator *UNUSED(op))
2282 {
2283         struct Scene *scene= CTX_data_scene(C);
2284         Object *obact = CTX_data_active_object(C);
2285
2286         wpaint_fill(scene->toolsettings->wpaint, obact, scene->toolsettings->vgroup_weight);
2287         ED_region_tag_redraw(CTX_wm_region(C)); // XXX - should redraw all 3D views
2288         return OPERATOR_FINISHED;
2289 }
2290
2291 void PAINT_OT_weight_set(wmOperatorType *ot)
2292 {
2293         /* identifiers */
2294         ot->name= "Set Weight";
2295         ot->idname= "PAINT_OT_weight_set";
2296
2297         /* api callbacks */
2298         ot->exec= weight_paint_set_exec;
2299         ot->poll= mask_paint_poll; /* it was facemask_paint_poll */
2300
2301         /* flags */
2302         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2303 }
2304
2305 /* ************ set / clear vertex paint mode ********** */
2306
2307
2308 static int set_vpaint(bContext *C, wmOperator *op)              /* toggle */
2309 {       
2310         Object *ob= CTX_data_active_object(C);
2311         Scene *scene= CTX_data_scene(C);
2312         VPaint *vp= scene->toolsettings->vpaint;
2313         Mesh *me;
2314         
2315         me= get_mesh(ob);
2316         
2317         if(me==NULL || object_data_is_libdata(ob)) {
2318                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2319                 return OPERATOR_PASS_THROUGH;
2320         }
2321         
2322         if(me && me->mloopcol==NULL) make_vertexcol(ob);
2323         
2324         /* toggle: end vpaint */
2325         if(ob->mode & OB_MODE_VERTEX_PAINT) {
2326                 
2327                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2328         }
2329         else {
2330                 ob->mode |= OB_MODE_VERTEX_PAINT;
2331                 /* Turn off weight painting */
2332                 if (ob->mode & OB_MODE_WEIGHT_PAINT)
2333                         set_wpaint(C, op);
2334                 
2335                 if(vp==NULL)
2336                         vp= scene->toolsettings->vpaint= new_vpaint(0);
2337                 
2338                 paint_cursor_start(C, vertex_paint_poll);
2339
2340                 paint_init(&vp->paint, PAINT_CURSOR_VERTEX_PAINT);
2341         }
2342         
2343         if (me)
2344                 /* update modifier stack for mapping requirements */
2345                 DAG_id_tag_update(&me->id, 0);
2346         
2347         WM_event_add_notifier(C, NC_SCENE|ND_MODE, scene);
2348         
2349         return OPERATOR_FINISHED;
2350 }
2351
2352 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2353 {
2354         
2355         /* identifiers */
2356         ot->name= "Vertex Paint Mode";
2357         ot->idname= "PAINT_OT_vertex_paint_toggle";
2358         
2359         /* api callbacks */
2360         ot->exec= set_vpaint;
2361         ot->poll= paint_poll_test;
2362         
2363         /* flags */
2364         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2365 }
2366
2367
2368
2369 /* ********************** vertex paint operator ******************* */
2370
2371 /* Implementation notes:
2372
2373 Operator->invoke()
2374   - validate context (add mcol)
2375   - create customdata storage
2376   - call paint once (mouse click)
2377   - add modal handler 
2378
2379 Operator->modal()
2380   - for every mousemove, apply vertex paint
2381   - exit on mouse release, free customdata
2382         (return OPERATOR_FINISHED also removes handler and operator)
2383
2384 For future:
2385   - implement a stroke event (or mousemove with past positons)
2386   - revise whether op->customdata should be added in object, in set_vpaint
2387
2388 */
2389
2390 typedef struct polyfacemap_e {
2391         struct polyfacemap_e *next, *prev;
2392         int facenr;
2393 } polyfacemap_e;
2394
2395 typedef struct VPaintData {
2396         ViewContext vc;
2397         unsigned int paintcol;
2398         int *indexar;
2399         float *vertexcosnos;
2400         float vpimat[3][3];
2401         
2402         /*mpoly -> mface mapping*/
2403         MemArena *arena;
2404         ListBase *polyfacemap;
2405 } VPaintData;
2406
2407 static void vpaint_build_poly_facemap(struct VPaintData *vd, Mesh *me,
2408                                       Object *ob, Scene *scene)
2409 {
2410         MFace *mf;
2411         polyfacemap_e *e;
2412         int *origIndex;
2413         int i;
2414
2415         vd->arena = BLI_memarena_new(1<<13, "vpaint tmp");
2416         BLI_memarena_use_calloc(vd->arena);
2417
2418         vd->polyfacemap = BLI_memarena_alloc(vd->arena, sizeof(ListBase)*me->totpoly);
2419
2420         /*we can't assume mfaces have a correct origindex layer that indices to mpolys.
2421           so instead we have to regenerate the tesselation faces altogether.*/
2422         me->totface = mesh_recalcTesselation(&me->fdata, &me->ldata, &me->pdata, 
2423                 me->mvert, me->totface, me->totloop, me->totpoly, 1, 0);
2424         mesh_update_customdata_pointers(me);
2425         makeDerivedMesh(scene, ob, NULL, CD_MASK_BAREMESH, 0);
2426
2427         origIndex = CustomData_get_layer(&me->fdata, CD_ORIGINDEX);
2428         mf = me->mface;
2429
2430         if (!origIndex)
2431                 return;
2432
2433         for (i=0; i<me->totface; i++, mf++, origIndex++) {
2434                 if (*origIndex == ORIGINDEX_NONE)
2435                         continue;
2436
2437                 e = BLI_memarena_alloc(vd->arena, sizeof(polyfacemap_e));
2438                 e->facenr = i;
2439                 
2440                 BLI_addtail(&vd->polyfacemap[*origIndex], e);
2441         }
2442 }
2443
2444 static int vpaint_stroke_test_start(bContext *C, struct wmOperator *op, wmEvent *UNUSED(event))
2445 {
2446         ToolSettings *ts= CTX_data_tool_settings(C);
2447         struct PaintStroke *stroke = op->customdata;
2448         VPaint *vp= ts->vpaint;
2449         struct VPaintData *vpd;
2450         Object *ob= CTX_data_active_object(C);
2451         Scene *scene = CTX_data_scene(C);
2452         Mesh *me;
2453         float mat[4][4], imat[4][4];
2454
2455         /* context checks could be a poll() */
2456         me= get_mesh(ob);
2457         if(me==NULL || me->totpoly==0)
2458                 return OPERATOR_PASS_THROUGH;
2459         
2460         if(me->mloopcol==NULL)
2461                 make_vertexcol(ob);
2462         if(me->mloopcol==NULL)
2463                 return OPERATOR_CANCELLED;
2464         
2465         /* make mode data storage */
2466         vpd= MEM_callocN(sizeof(struct VPaintData), "VPaintData");
2467         paint_stroke_set_mode_data(stroke, vpd);
2468         view3d_set_viewcontext(C, &vpd->vc);
2469         
2470         vpd->vertexcosnos= mesh_get_mapped_verts_nors(vpd->vc.scene, ob);
2471         vpd->indexar= get_indexarray(me);
2472         vpd->paintcol= vpaint_get_current_col(vp);
2473         vpaint_build_poly_facemap(vpd, me, ob, scene);
2474         
2475         /* for filtering */
2476         copy_vpaint_prev(vp, (unsigned int *)me->mloopcol, me->totloop);
2477         
2478         /* some old cruft to sort out later */
2479         mul_m4_m4m4(mat, ob->obmat, vpd->vc.rv3d->viewmat);
2480         invert_m4_m4(imat, mat);
2481         copy_m3_m4(vpd->vpimat, imat);
2482
2483         return 1;
2484 }
2485
2486 #if 0
2487 static void vpaint_paint_face(VPaint *vp, VPaintData *vpd, Object *ob, int index, const float mval[2], float pressure, int UNUSED(flip))
2488 {
2489         ViewContext *vc = &vpd->vc;
2490         Brush *brush = paint_brush(&vp->paint);
2491         Mesh *me = get_mesh(ob);
2492         MFace *mface= ((MFace*)me->mface) + index;
2493         unsigned int *mcol= ((unsigned int*)me->mcol) + 4*index;
2494         unsigned int *mcolorig= ((unsigned int*)vp->vpaint_prev) + 4*index;
2495         float alpha;
2496         int i;
2497         
2498         if((vp->flag & VP_COLINDEX && mface->mat_nr!=ob->actcol-1) ||
2499            ((me->editflag & ME_EDIT_PAINT_MASK) && !(mface->flag & ME_FACE_SEL)))
2500                 return;
2501
2502         if(brush->vertexpaint_tool==VP_BLUR) {
2503                 unsigned int fcol1= mcol_blend( mcol[0], mcol[1], 128);
2504                 if(mface->v4) {
2505                         unsigned int fcol2= mcol_blend( mcol[2], mcol[3], 128);
2506                         vpd->paintcol= mcol_blend( fcol1, fcol2, 128);
2507                 }
2508                 else {
2509                         vpd->paintcol= mcol_blend( mcol[2], fcol1, 170);
2510                 }
2511                 
2512         }
2513
2514         for(i = 0; i < (mface->v4 ? 4 : 3); ++i) {
2515                 alpha= calc_vp_alpha_dl(vp, vc, vpd->vpimat, vpd->vertexcosnos+6*(&mface->v1)[i], mval, pressure);
2516                 if(alpha)
2517                         vpaint_blend(vp, mcol+i, mcolorig+i, vpd->paintcol, (int)(alpha*255.0f));
2518         }
2519 }
2520 #endif
2521
2522 static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2523 {
2524         ToolSettings *ts= CTX_data_tool_settings(C);
2525         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2526         VPaint *vp= ts->vpaint;
2527         Brush *brush = paint_brush(&vp->paint);
2528         ViewContext *vc= &vpd->vc;
2529         Object *ob= vc->obact;
2530         polyfacemap_e *e;
2531         Mesh *me= ob->data;
2532         float mat[4][4];
2533         int *indexar= vpd->indexar;
2534         int totindex, index, flip;
2535         float pressure, mval[2];
2536
2537         RNA_float_get_array(itemptr, "mouse", mval);
2538         flip = RNA_boolean_get(itemptr, "pen_flip");
2539         pressure = RNA_float_get(itemptr, "pressure");
2540                         
2541         view3d_operator_needs_opengl(C);
2542                         
2543         /* load projection matrix */
2544         mul_m4_m4m4(mat, ob->obmat, vc->rv3d->persmat);
2545
2546         mval[0]-= vc->ar->winrct.xmin;
2547         mval[1]-= vc->ar->winrct.ymin;
2548
2549                         
2550         /* which faces are involved */
2551         if(vp->flag & VP_AREA) {
2552                 totindex= sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size(brush));
2553         }
2554         else {
2555                 indexar[0]= view3d_sample_backbuf(vc, mval[0], mval[1]);
2556                 if(indexar[0]) totindex= 1;
2557                 else totindex= 0;
2558         }
2559                         
2560         swap_m4m4(vc->rv3d->persmat, mat);
2561                         
2562         if(vp->flag & VP_COLINDEX) {
2563                 for(index=0; index<totindex; index++) {
2564                         if(indexar[index] && indexar[index]<=me->totpoly) {
2565                                 MPoly *mpoly= ((MPoly *)me->mpoly) + (indexar[index]-1);
2566                                                 
2567                                 if(mpoly->mat_nr!=ob->actcol-1) {
2568                                         indexar[index]= 0;
2569                                 }
2570                         }                                       
2571                 }
2572         }
2573
2574         if((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
2575                 for(index=0; index<totindex; index++) {
2576                         if(indexar[index] && indexar[index]<=me->totpoly) {
2577                                 MPoly *mpoly= ((MPoly *)me->mpoly) + (indexar[index]-1);
2578                                                 
2579                                 if((mpoly->flag & ME_FACE_SEL)==0)
2580                                         indexar[index]= 0;
2581                         }                                       
2582                 }
2583         }
2584         
2585         swap_m4m4(vc->rv3d->persmat, mat);
2586
2587         /* was disabled because it is slow, but necessary for blur */
2588         if(brush->vertexpaint_tool == VP_BLUR)
2589                 do_shared_vertexcol(me);
2590                         
2591         for(index=0; index<totindex; index++) {
2592                                 
2593                 if(indexar[index] && indexar[index]<=me->totpoly) {
2594                         MPoly *mpoly= ((MPoly *)me->mpoly) + (indexar[index]-1);
2595                         MFace *mf;
2596                         MCol *mc;
2597                         MLoop *ml;
2598                         MLoopCol *mlc;
2599                         unsigned int *lcol = ((unsigned int*)me->mloopcol) + mpoly->loopstart;
2600                         unsigned int *lcolorig = ((unsigned int*)vp->vpaint_prev) + mpoly->loopstart;
2601                         float alpha;
2602                         int i, j;
2603                                         
2604                         if(brush->vertexpaint_tool==VP_BLUR) {
2605                                 unsigned int blend[5] = {0};
2606                                 char *col;
2607
2608                                 for (j=0; j<mpoly->totloop; j += 2) {
2609                                         col = (char*)(lcol + j);
2610                                         blend[0] += col[0];
2611                                         blend[1] += col[1];
2612                                         blend[2] += col[2];
2613                                         blend[3] += col[3];
2614                                 }
2615
2616                                 blend[0] /= mpoly->totloop;
2617                                 blend[1] /= mpoly->totloop;
2618                                 blend[2] /= mpoly->totloop;
2619                                 blend[3] /= mpoly->totloop;
2620                                 col = (char*)(blend + 4);
2621                                 col[0] = blend[0];
2622                                 col[1] = blend[1];
2623                                 col[2] = blend[2];
2624                                 col[3] = blend[3];
2625
2626                                 vpd->paintcol = *((unsigned int*)col);
2627                         }
2628
2629                         ml = me->mloop + mpoly->loopstart;
2630                         for (i=0; i<mpoly->totloop; i++, ml++) {
2631                                 alpha= calc_vp_alpha_dl(vp, vc, vpd->vpimat, 
2632                                            vpd->vertexcosnos+6*ml->v, mval, pressure);
2633                                 if(alpha > 0.0f) vpaint_blend(vp, lcol+i, lcolorig+i, vpd->paintcol, (int)(alpha*255.0f));
2634                         }
2635         
2636                         #ifdef CPYCOL
2637                         #undef CPYCOL
2638                         #endif
2639                         #define CPYCOL(c, l) (c)->a = (l)->a, (c)->r = (l)->r, (c)->g = (l)->g, (c)->b = (l)->b
2640
2641                         /*update vertex colors for tesselations incrementally,
2642                           rather then regenerating the tesselation altogether.*/
2643                         for (e=vpd->polyfacemap[(indexar[index]-1)].first; e; e=e->next) {
2644                                 mf = me->mface + e->facenr;
2645                                 mc = me->mcol + e->facenr*4;
2646                                 
2647                                 ml = me->mloop + mpoly->loopstart;
2648                                 mlc = me->mloopcol + mpoly->loopstart;
2649                                 for (j=0; j<mpoly->totloop; j++, ml++, mlc++) {
2650                                         if (ml->v == mf->v1)
2651                                                 CPYCOL(mc, mlc);
2652                                         else if (ml->v == mf->v2)
2653                                                 CPYCOL(mc+1, mlc);
2654                                         else if (ml->v == mf->v3)
2655                                                 CPYCOL(mc+2, mlc);
2656                                         else if (mf->v4 && ml->v == mf->v4)
2657                                                 CPYCOL(mc+3, mlc);
2658
2659                                 }
2660                         }
2661                         #undef CPYCOL
2662                 }
2663         }
2664                 
2665         swap_m4m4(vc->rv3d->persmat, mat);
2666                         
2667         do_shared_vertexcol(me);
2668
2669         ED_region_tag_redraw(vc->ar);           
2670         DAG_id_tag_update(ob->data, 0);
2671 }
2672
2673 static void vpaint_stroke_done(bContext *C, struct PaintStroke *stroke)
2674 {
2675         ToolSettings *ts= CTX_data_tool_settings(C);
2676         struct VPaintData *vpd= paint_stroke_mode_data(stroke);
2677         
2678         if(vpd->vertexcosnos)
2679                 MEM_freeN(vpd->vertexcosnos);
2680         MEM_freeN(vpd->indexar);
2681         
2682         /* frees prev buffer */
2683         copy_vpaint_prev(ts->vpaint, NULL, 0);
2684         BLI_memarena_free(vpd->arena);
2685
2686         MEM_freeN(vpd);
2687 }
2688
2689 static int vpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2690 {
2691         
2692         op->customdata = paint_stroke_new(C, NULL, vpaint_stroke_test_start,
2693                                           vpaint_stroke_update_step,
2694                                           vpaint_stroke_done, event->type);
2695         
2696         /* add modal handler */
2697         WM_event_add_modal_handler(C, op);
2698
2699         op->type->modal(C, op, event);
2700         
2701         return OPERATOR_RUNNING_MODAL;
2702 }
2703
2704 static int vpaint_cancel(bContext *C, wmOperator *op)
2705 {
2706         paint_stroke_cancel(C, op);
2707
2708         return OPERATOR_CANCELLED;
2709 }
2710
2711 void PAINT_OT_vertex_paint(wmOperatorType *ot)
2712 {
2713         /* identifiers */
2714         ot->name= "Vertex Paint";
2715         ot->idname= "PAINT_OT_vertex_paint";
2716         
2717         /* api callbacks */
2718         ot->invoke= vpaint_invoke;
2719         ot->modal= paint_stroke_modal;
2720         /* ot->exec= vpaint_exec; <-- needs stroke property */
2721         ot->poll= vertex_paint_poll;
2722         ot->cancel= vpaint_cancel;
2723         
2724         /* flags */
2725         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2726
2727         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2728 }
2729
2730 /* ********************** weight from bones operator ******************* */
2731
2732 static int weight_from_bones_poll(bContext *C)
2733 {
2734         Object *ob= CTX_data_active_object(C);
2735
2736         return (ob && (ob->mode & OB_MODE_WEIGHT_PAINT) && modifiers_isDeformedByArmature(ob));
2737 }
2738
2739 static int weight_from_bones_exec(bContext *C, wmOperator *op)
2740 {
2741         Scene *scene= CTX_data_scene(C);
2742         Object *ob= CTX_data_active_object(C);
2743         Object *armob= modifiers_isDeformedByArmature(ob);
2744         Mesh *me= ob->data;
2745         int type= RNA_enum_get(op->ptr, "type");
2746
2747         create_vgroups_from_armature(op->reports, scene, ob, armob, type, (me->editflag & ME_EDIT_MIRROR_X));
2748
2749         DAG_id_tag_update(&me->id, 0);
2750         WM_event_add_notifier(C, NC_GEOM|ND_DATA, me);
2751
2752         return OPERATOR_FINISHED;
2753 }
2754
2755 void PAINT_OT_weight_from_bones(wmOperatorType *ot)
2756 {
2757         static EnumPropertyItem type_items[]= {
2758                 {ARM_GROUPS_AUTO, "AUTOMATIC", 0, "Automatic", "Automatic weights froms bones"},
2759                 {ARM_GROUPS_ENVELOPE, "ENVELOPES", 0, "From Envelopes", "Weights from envelopes with user defined radius"},
2760                 {0, NULL, 0, NULL, NULL}};
2761
2762         /* identifiers */
2763         ot->name= "Weight from Bones";
2764         ot->idname= "PAINT_OT_weight_from_bones";
2765         
2766         /* api callbacks */
2767         ot->exec= weight_from_bones_exec;
2768         ot->invoke= WM_menu_invoke;
2769         ot->poll= weight_from_bones_poll;
2770         
2771         /* flags */
2772         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2773
2774         /* properties */
2775         ot->prop= RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "Method to use for assigning weights");
2776 }
2777