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