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