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