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