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