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