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