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