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