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