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