Cycles / Vector Transform Node:
[blender.git] / source / blender / editors / object / object_vgroup.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): Ove M Henriksen.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/object/object_vgroup.c
29  *  \ingroup edobj
30  */
31
32 #include <string.h>
33 #include <stddef.h>
34 #include <math.h>
35 #include <assert.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_cloth_types.h"
40 #include "DNA_curve_types.h"
41 #include "DNA_lattice_types.h"
42 #include "DNA_meshdata_types.h"
43 #include "DNA_mesh_types.h"
44 #include "DNA_modifier_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_object_force.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_particle_types.h"
49
50 #include "BLI_array.h"
51 #include "BLI_math.h"
52 #include "BLI_blenlib.h"
53 #include "BLI_utildefines.h"
54
55 #include "BLF_translation.h"
56
57 #include "BKE_context.h"
58 #include "BKE_customdata.h"
59 #include "BKE_deform.h"
60 #include "BKE_depsgraph.h"
61 #include "BKE_global.h"
62 #include "BKE_mesh.h"
63 #include "BKE_editmesh.h"
64 #include "BKE_report.h"
65 #include "BKE_DerivedMesh.h"
66 #include "BKE_object_deform.h"
67 #include "BKE_object.h"
68 #include "BKE_lattice.h"
69
70 #include "RNA_access.h"
71 #include "RNA_define.h"
72 #include "RNA_enum_types.h"
73
74 #include "WM_api.h"
75 #include "WM_types.h"
76
77 #include "ED_object.h"
78 #include "ED_mesh.h"
79
80 #include "UI_resources.h"
81
82 #include "object_intern.h"
83
84 /************************ Exported Functions **********************/
85 static void vgroup_remap_update_users(Object *ob, int *map);
86 static void vgroup_delete_edit_mode(Object *ob, bDeformGroup *defgroup);
87 static void vgroup_delete_object_mode(Object *ob, bDeformGroup *dg);
88 static void vgroup_delete_all(Object *ob);
89 static bool ED_vgroup_give_parray(ID *id, MDeformVert ***dvert_arr, int *dvert_tot, const bool use_vert_sel);
90
91 static bool vertex_group_use_vert_sel(Object *ob)
92 {
93         if (ob->mode == OB_MODE_EDIT) {
94                 return true;
95         }
96         else if (ob->type == OB_MESH && ((Mesh *)ob->data)->editflag & ME_EDIT_PAINT_VERT_SEL) {
97                 return true;
98         }
99         else {
100                 return false;
101         }
102 }
103
104 static Lattice *vgroup_edit_lattice(Object *ob)
105 {
106         Lattice *lt = ob->data;
107         BLI_assert(ob->type == OB_LATTICE);
108         return (lt->editlatt) ? lt->editlatt->latt : lt;
109 }
110
111 bool ED_vgroup_object_is_edit_mode(Object *ob)
112 {
113         if (ob->type == OB_MESH)
114                 return (BKE_editmesh_from_object(ob) != NULL);
115         else if (ob->type == OB_LATTICE)
116                 return (((Lattice *)ob->data)->editlatt != NULL);
117
118         return false;
119 }
120
121 bDeformGroup *ED_vgroup_add_name(Object *ob, const char *name)
122 {
123         bDeformGroup *defgroup;
124
125         if (!ob || !OB_TYPE_SUPPORT_VGROUP(ob->type))
126                 return NULL;
127         
128         defgroup = MEM_callocN(sizeof(bDeformGroup), "add deformGroup");
129
130         BLI_strncpy(defgroup->name, name, sizeof(defgroup->name));
131
132         BLI_addtail(&ob->defbase, defgroup);
133         defgroup_unique_name(defgroup, ob);
134
135         ob->actdef = BLI_countlist(&ob->defbase);
136
137         return defgroup;
138 }
139
140 bDeformGroup *ED_vgroup_add(Object *ob) 
141 {
142         return ED_vgroup_add_name(ob, DATA_("Group"));
143 }
144
145 void ED_vgroup_delete(Object *ob, bDeformGroup *defgroup) 
146 {
147         BLI_assert(BLI_findindex(&ob->defbase, defgroup) != -1);
148
149         if (ED_vgroup_object_is_edit_mode(ob))
150                 vgroup_delete_edit_mode(ob, defgroup);
151         else
152                 vgroup_delete_object_mode(ob, defgroup);
153 }
154
155 void ED_vgroup_clear(Object *ob)
156 {
157         bDeformGroup *dg = (bDeformGroup *)ob->defbase.first;
158         int edit_mode = ED_vgroup_object_is_edit_mode(ob);
159
160         while (dg) {
161                 bDeformGroup *next_dg = dg->next;
162
163                 if (edit_mode)
164                         vgroup_delete_edit_mode(ob, dg);
165                 else
166                         vgroup_delete_object_mode(ob, dg);
167
168                 dg = next_dg;
169         }
170 }
171
172 bool ED_vgroup_data_create(ID *id)
173 {
174         /* create deform verts */
175
176         if (GS(id->name) == ID_ME) {
177                 Mesh *me = (Mesh *)id;
178                 me->dvert = CustomData_add_layer(&me->vdata, CD_MDEFORMVERT, CD_CALLOC, NULL, me->totvert);
179                 return true;
180         }
181         else if (GS(id->name) == ID_LT) {
182                 Lattice *lt = (Lattice *)id;
183                 lt->dvert = MEM_callocN(sizeof(MDeformVert) * lt->pntsu * lt->pntsv * lt->pntsw, "lattice deformVert");
184                 return true;
185         }
186         else {
187                 return false;
188         }
189 }
190
191 /**
192  * Removes out of range MDeformWeights
193  */
194 void ED_vgroup_data_clamp_range(ID *id, const int total)
195 {
196         MDeformVert **dvert_arr;
197         int dvert_tot;
198
199         if (ED_vgroup_give_parray(id, &dvert_arr, &dvert_tot, false)) {
200                 int i;
201                 for (i = 0; i < dvert_tot; i++) {
202                         MDeformVert *dv = dvert_arr[i];
203                         int j;
204                         for (j = 0; j < dv->totweight; j++) {
205                                 if (dv->dw[j].def_nr >= total) {
206                                         defvert_remove_group(dv, &dv->dw[j]);
207                                         j--;
208                                 }
209                         }
210                 }
211         }
212 }
213
214 static bool ED_vgroup_give_parray(ID *id, MDeformVert ***dvert_arr, int *dvert_tot, const bool use_vert_sel)
215 {
216         *dvert_tot = 0;
217         *dvert_arr = NULL;
218
219         if (id) {
220                 switch (GS(id->name)) {
221                         case ID_ME:
222                         {
223                                 Mesh *me = (Mesh *)id;
224
225                                 if (me->edit_btmesh) {
226                                         BMEditMesh *em = me->edit_btmesh;
227                                         BMesh *bm = em->bm;
228                                         const int cd_dvert_offset  = CustomData_get_offset(&bm->vdata, CD_MDEFORMVERT);
229                                         BMIter iter;
230                                         BMVert *eve;
231                                         int i;
232
233                                         if (cd_dvert_offset == -1) {
234                                                 return false;
235                                         }
236
237                                         i = em->bm->totvert;
238
239                                         *dvert_arr = MEM_mallocN(sizeof(void *) * i, "vgroup parray from me");
240                                         *dvert_tot = i;
241
242                                         i = 0;
243                                         if (use_vert_sel) {
244                                                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
245                                                         (*dvert_arr)[i] = BM_elem_flag_test(eve, BM_ELEM_SELECT) ?
246                                                                           BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset) : NULL;
247                                                         i++;
248                                                 }
249                                         }
250                                         else {
251                                                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
252                                                         (*dvert_arr)[i] = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
253                                                         i++;
254                                                 }
255                                         }
256
257                                         return true;
258                                 }
259                                 else if (me->dvert) {
260                                         MVert *mvert = me->mvert;
261                                         MDeformVert *dvert = me->dvert;
262                                         int i;
263
264                                         *dvert_tot = me->totvert;
265                                         *dvert_arr = MEM_mallocN(sizeof(void *) * me->totvert, "vgroup parray from me");
266
267                                         if (use_vert_sel) {
268                                                 for (i = 0; i < me->totvert; i++) {
269                                                         (*dvert_arr)[i] = (mvert[i].flag & SELECT) ?
270                                                                           &dvert[i] : NULL;
271                                                 }
272                                         }
273                                         else {
274                                                 for (i = 0; i < me->totvert; i++) {
275                                                         (*dvert_arr)[i] = me->dvert + i;
276                                                 }
277                                         }
278
279                                         return true;
280                                 }
281                                 else {
282                                         return false;
283                                 }
284                         }
285                         case ID_LT:
286                         {
287                                 int i = 0;
288
289                                 Lattice *lt = (Lattice *)id;
290                                 lt = (lt->editlatt) ? lt->editlatt->latt : lt;
291
292                                 if (lt->dvert) {
293                                         BPoint *def = lt->def;
294                                         *dvert_tot = lt->pntsu * lt->pntsv * lt->pntsw;
295                                         *dvert_arr = MEM_mallocN(sizeof(void *) * (*dvert_tot), "vgroup parray from me");
296
297                                         if (use_vert_sel) {
298                                                 for (i = 0; i < *dvert_tot; i++) {
299                                                         (*dvert_arr)[i] = (def->f1 & SELECT) ?
300                                                                            &lt->dvert[i] : NULL;
301                                                 }
302                                         }
303                                         else {
304                                                 for (i = 0; i < *dvert_tot; i++) {
305                                                         (*dvert_arr)[i] = lt->dvert + i;
306                                                 }
307                                         }
308
309                                         return true;
310                                 }
311                                 else {
312                                         return false;
313                                 }
314                         }
315                 }
316         }
317
318         return false;
319 }
320
321 /* returns true if the id type supports weights */
322 bool ED_vgroup_give_array(ID *id, MDeformVert **dvert_arr, int *dvert_tot)
323 {
324         if (id) {
325                 switch (GS(id->name)) {
326                         case ID_ME:
327                         {
328                                 Mesh *me = (Mesh *)id;
329                                 *dvert_arr = me->dvert;
330                                 *dvert_tot = me->totvert;
331                                 return true;
332                         }
333                         case ID_LT:
334                         {
335                                 Lattice *lt = (Lattice *)id;
336                                 lt = (lt->editlatt) ? lt->editlatt->latt : lt;
337                                 *dvert_arr = lt->dvert;
338                                 *dvert_tot = lt->pntsu * lt->pntsv * lt->pntsw;
339                                 return true;
340                         }
341                 }
342         }
343
344         *dvert_arr = NULL;
345         *dvert_tot = 0;
346         return false;
347 }
348
349 /* matching index only */
350 bool ED_vgroup_copy_array(Object *ob, Object *ob_from)
351 {
352         MDeformVert **dvert_array_from, **dvf;
353         MDeformVert **dvert_array, **dv;
354         int dvert_tot_from;
355         int dvert_tot;
356         int i;
357         int defbase_tot_from = BLI_countlist(&ob_from->defbase);
358         int defbase_tot = BLI_countlist(&ob->defbase);
359         bool new_vgroup = false;
360
361         ED_vgroup_give_parray(ob_from->data, &dvert_array_from, &dvert_tot_from, false);
362         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, false);
363
364         if ((dvert_array == NULL) && (dvert_array_from != NULL) && ED_vgroup_data_create(ob->data)) {
365                 ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, false);
366                 new_vgroup = true;
367         }
368
369         if (ob == ob_from || dvert_tot == 0 || (dvert_tot != dvert_tot_from) || dvert_array_from == NULL || dvert_array == NULL) {
370                 if (dvert_array) MEM_freeN(dvert_array);
371                 if (dvert_array_from) MEM_freeN(dvert_array_from);
372
373                 if (new_vgroup == true) {
374                         /* free the newly added vgroup since it wasn't compatible */
375                         vgroup_delete_all(ob);
376                 }
377                 return false;
378         }
379
380         /* do the copy */
381         BLI_freelistN(&ob->defbase);
382         BLI_duplicatelist(&ob->defbase, &ob_from->defbase);
383         ob->actdef = ob_from->actdef;
384
385         if (defbase_tot_from < defbase_tot) {
386                 /* correct vgroup indices because the number of vgroups is being reduced. */
387                 int *remap = MEM_mallocN(sizeof(int) * (defbase_tot + 1), __func__);
388                 for (i = 0; i <= defbase_tot_from; i++) remap[i] = i;
389                 for (; i <= defbase_tot; i++) remap[i] = 0;  /* can't use these, so disable */
390
391                 vgroup_remap_update_users(ob, remap);
392                 MEM_freeN(remap);
393         }
394
395         dvf = dvert_array_from;
396         dv = dvert_array;
397
398         for (i = 0; i < dvert_tot; i++, dvf++, dv++) {
399                 if ((*dv)->dw)
400                         MEM_freeN((*dv)->dw);
401
402                 *(*dv) = *(*dvf);
403
404                 if ((*dv)->dw)
405                         (*dv)->dw = MEM_dupallocN((*dv)->dw);
406         }
407
408         MEM_freeN(dvert_array);
409         MEM_freeN(dvert_array_from);
410
411         return true;
412 }
413
414 /* TODO, cache flip data to speedup calls within a loop. */
415 static void mesh_defvert_mirror_update_internal(Object *ob,
416                                                 MDeformVert *dvert_dst, MDeformVert *dvert_src,
417                                                 const int def_nr)
418 {
419         if (def_nr == -1) {
420                 /* all vgroups, add groups where neded  */
421                 int flip_map_len;
422                 int *flip_map = defgroup_flip_map(ob, &flip_map_len, true);
423                 defvert_sync_mapped(dvert_dst, dvert_src, flip_map, flip_map_len, true);
424                 MEM_freeN(flip_map);
425         }
426         else {
427                 /* single vgroup */
428                 MDeformWeight *dw = defvert_verify_index(dvert_dst, defgroup_flip_index(ob, def_nr, 1));
429                 if (dw) {
430                         dw->weight = defvert_find_weight(dvert_src, def_nr);
431                 }
432         }
433 }
434
435 static void ED_mesh_defvert_mirror_update_em(Object *ob, BMVert *eve, int def_nr, int vidx,
436                                              const int cd_dvert_offset)
437 {
438         Mesh *me = ob->data;
439         BMEditMesh *em = me->edit_btmesh;
440         BMVert *eve_mirr;
441         bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
442
443         eve_mirr = editbmesh_get_x_mirror_vert(ob, em, eve, eve->co, vidx, use_topology);
444
445         if (eve_mirr && eve_mirr != eve) {
446                 MDeformVert *dvert_src = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
447                 MDeformVert *dvert_dst = BM_ELEM_CD_GET_VOID_P(eve_mirr, cd_dvert_offset);
448                 mesh_defvert_mirror_update_internal(ob, dvert_dst, dvert_src, def_nr);
449         }
450 }
451
452 static void ED_mesh_defvert_mirror_update_ob(Object *ob, int def_nr, int vidx)
453 {
454         int vidx_mirr;
455         Mesh *me = ob->data;
456         bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
457
458         if (vidx == -1)
459                 return;
460
461         vidx_mirr = mesh_get_x_mirror_vert(ob, vidx, use_topology);
462
463         if ((vidx_mirr) >= 0 && (vidx_mirr != vidx)) {
464                 MDeformVert *dvert_src = &me->dvert[vidx];
465                 MDeformVert *dvert_dst = &me->dvert[vidx_mirr];
466                 mesh_defvert_mirror_update_internal(ob, dvert_dst, dvert_src, def_nr);
467         }
468 }
469
470 /**
471  * Use when adjusting the active vertex weight and apply to mirror vertices.
472  */
473 void ED_vgroup_vert_active_mirror(Object *ob, int def_nr)
474 {
475         Mesh *me = ob->data;
476         BMEditMesh *em = me->edit_btmesh;
477         MDeformVert *dvert_act;
478
479         if (me->editflag & ME_EDIT_MIRROR_X) {
480                 if (em) {
481                         BMVert *eve_act;
482                         dvert_act = ED_mesh_active_dvert_get_em(ob, &eve_act);
483                         if (dvert_act) {
484                                 const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
485                                 ED_mesh_defvert_mirror_update_em(ob, eve_act, def_nr, -1, cd_dvert_offset);
486                         }
487                 }
488                 else {
489                         int v_act;
490                         dvert_act = ED_mesh_active_dvert_get_ob(ob, &v_act);
491                         if (dvert_act) {
492                                 ED_mesh_defvert_mirror_update_ob(ob, def_nr, v_act);
493                         }
494                 }
495         }
496 }
497
498 static void vgroup_remove_weight(Object *ob, const int def_nr)
499 {
500         MDeformVert *dvert_act;
501         MDeformWeight *dw;
502
503         dvert_act = ED_mesh_active_dvert_get_only(ob);
504
505         dw = defvert_find_index(dvert_act, def_nr);
506         defvert_remove_group(dvert_act, dw);
507
508 }
509
510 static void vgroup_normalize_active(Object *ob, eVGroupSelect subset_type)
511 {
512         Mesh *me = ob->data;
513         BMEditMesh *em = me->edit_btmesh;
514         BMVert *eve_act;
515         int v_act;
516         MDeformVert *dvert_act;
517         int subset_count, vgroup_tot;
518         const bool *vgroup_validmap;
519
520
521         if (em) {
522                 dvert_act = ED_mesh_active_dvert_get_em(ob, &eve_act);
523         }
524         else {
525                 dvert_act = ED_mesh_active_dvert_get_ob(ob, &v_act);
526         }
527
528         if (dvert_act == NULL) {
529                 return;
530         }
531
532         vgroup_validmap = ED_vgroup_subset_from_select_type(ob, subset_type, &vgroup_tot, &subset_count);
533         defvert_normalize_subset(dvert_act, vgroup_validmap, vgroup_tot);
534         MEM_freeN((void *)vgroup_validmap);
535
536         if (me->editflag & ME_EDIT_MIRROR_X) {
537                 if (em) {
538                         const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
539                         ED_mesh_defvert_mirror_update_em(ob, eve_act, -1, -1, cd_dvert_offset);
540                 }
541                 else {
542                         int v_act = BKE_mesh_mselect_active_get(me, ME_VSEL);
543                         ED_mesh_defvert_mirror_update_ob(ob, -1, v_act);
544                 }
545         }
546 }
547
548 static void vgroup_copy_active_to_sel(Object *ob, eVGroupSelect subset_type)
549 {
550         Mesh *me = ob->data;
551         BMEditMesh *em = me->edit_btmesh;
552         MDeformVert *dvert_act;
553         int i, vgroup_tot, subset_count;
554         const bool *vgroup_validmap = ED_vgroup_subset_from_select_type(ob, subset_type, &vgroup_tot, &subset_count);
555
556
557         if (em) {
558                 BMIter iter;
559                 BMVert *eve, *eve_act;
560                 const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
561
562                 dvert_act = ED_mesh_active_dvert_get_em(ob, &eve_act);
563                 if (dvert_act) {
564                         BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
565                                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT) && eve != eve_act) {
566                                         MDeformVert *dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
567                                         defvert_copy_subset(dv, dvert_act, vgroup_validmap, vgroup_tot);
568                                         if (me->editflag & ME_EDIT_MIRROR_X) {
569                                                 ED_mesh_defvert_mirror_update_em(ob, eve, -1, i, cd_dvert_offset);
570                                         }
571                                 }
572                         }
573                 }
574         }
575         else {
576                 MDeformVert *dv;
577                 int v_act;
578
579                 dvert_act = ED_mesh_active_dvert_get_ob(ob, &v_act);
580                 if (dvert_act) {
581                         dv  = me->dvert;
582                         for (i = 0; i < me->totvert; i++, dv++) {
583                                 if ((me->mvert[i].flag & SELECT) && dv != dvert_act) {
584                                         defvert_copy_subset(dv, dvert_act, vgroup_validmap, vgroup_tot);
585                                         if (me->editflag & ME_EDIT_MIRROR_X) {
586                                                 ED_mesh_defvert_mirror_update_ob(ob, -1, i);
587                                         }
588                                 }
589                         }
590                 }
591         }
592
593         MEM_freeN((void *)vgroup_validmap);
594 }
595
596 /***********************Start weight transfer (WT)*********************************/
597
598 typedef enum WT_VertexGroupMode {
599         WT_REPLACE_ACTIVE_VERTEX_GROUP = 1,
600         WT_REPLACE_ALL_VERTEX_GROUPS = 2
601 } WT_VertexGroupMode;
602
603 typedef enum WT_Method {
604         WT_BY_INDEX = 1,
605         WT_BY_NEAREST_VERTEX = 2,
606         WT_BY_NEAREST_FACE = 3,
607         WT_BY_NEAREST_VERTEX_IN_FACE = 4
608 } WT_Method;
609
610 typedef enum WT_ReplaceMode {
611         WT_REPLACE_ALL_WEIGHTS = 1,
612         WT_REPLACE_EMPTY_WEIGHTS = 2
613 } WT_ReplaceMode;
614
615 static EnumPropertyItem WT_vertex_group_mode_item[] = {
616         {WT_REPLACE_ACTIVE_VERTEX_GROUP,
617          "WT_REPLACE_ACTIVE_VERTEX_GROUP", 0, "Active", "Transfer active vertex group from selected to active mesh"},
618         {WT_REPLACE_ALL_VERTEX_GROUPS,
619          "WT_REPLACE_ALL_VERTEX_GROUPS", 0, "All", "Transfer all vertex groups from selected to active mesh"},
620         {0, NULL, 0, NULL, NULL}
621 };
622
623 static EnumPropertyItem WT_method_item[] = {
624         {WT_BY_INDEX,
625          "WT_BY_INDEX", 0, "Vertex index", "Copy for identical meshes"},
626         {WT_BY_NEAREST_VERTEX,
627          "WT_BY_NEAREST_VERTEX", 0, "Nearest vertex", "Copy weight from closest vertex"},
628         {WT_BY_NEAREST_FACE,
629          "WT_BY_NEAREST_FACE", 0, "Nearest face", "Barycentric interpolation from nearest face"},
630         {WT_BY_NEAREST_VERTEX_IN_FACE,
631          "WT_BY_NEAREST_VERTEX_IN_FACE", 0, "Nearest vertex in face", "Copy weight from closest vertex in nearest face"},
632         {0, NULL, 0, NULL, NULL}
633 };
634
635 static EnumPropertyItem WT_replace_mode_item[] = {
636         {WT_REPLACE_ALL_WEIGHTS,
637          "WT_REPLACE_ALL_WEIGHTS", 0, "All", "Overwrite all weights"},
638         {WT_REPLACE_EMPTY_WEIGHTS,
639          "WT_REPLACE_EMPTY_WEIGHTS", 0, "Empty", "Add weights to vertices with no weight"},
640         {0, NULL, 0, NULL, NULL}
641 };
642
643 static EnumPropertyItem WT_vertex_group_select_item[] = {
644         {WT_VGROUP_ACTIVE,
645          "ACTIVE", 0, "Active Group", "The active Vertex Group"},
646         {WT_VGROUP_BONE_SELECT,
647          "BONE_SELECT", 0, "Selected Pose Bones", "All Vertex Groups assigned to Selection"},
648         {WT_VGROUP_BONE_DEFORM,
649          "BONE_DEFORM", 0, "Deform Pose Bones", "All Vertex Groups assigned to Deform Bones"},
650         {WT_VGROUP_ALL,
651          "ALL", 0, "All Groups", "All Vertex Groups"},
652         {0, NULL, 0, NULL, NULL}
653 };
654
655 EnumPropertyItem *ED_object_vgroup_selection_itemf_helper(
656         const bContext *C, PointerRNA *UNUSED(ptr),
657         PropertyRNA *UNUSED(prop), int *free, const unsigned int selection_mask)
658 {
659         Object *ob;
660         EnumPropertyItem *item = NULL;
661         int totitem = 0;
662
663
664         if (!C) /* needed for docs and i18n tools */
665                 return WT_vertex_group_select_item;
666
667         ob = CTX_data_active_object(C);
668         if (selection_mask & (1 << WT_VGROUP_ACTIVE))
669                 RNA_enum_items_add_value(&item, &totitem, WT_vertex_group_select_item, WT_VGROUP_ACTIVE);
670
671         if (BKE_object_pose_armature_get(ob)) {
672                 if (selection_mask & (1 << WT_VGROUP_BONE_SELECT))
673                         RNA_enum_items_add_value(&item, &totitem, WT_vertex_group_select_item, WT_VGROUP_BONE_SELECT);
674                 if (selection_mask & (1 << WT_VGROUP_BONE_DEFORM))
675                         RNA_enum_items_add_value(&item, &totitem, WT_vertex_group_select_item, WT_VGROUP_BONE_DEFORM);
676         }
677
678         if (selection_mask & (1 << WT_VGROUP_ALL))
679                 RNA_enum_items_add_value(&item, &totitem, WT_vertex_group_select_item, WT_VGROUP_ALL);
680
681         RNA_enum_item_end(&item, &totitem);
682         *free = true;
683
684         return item;
685 }
686
687 static EnumPropertyItem *rna_vertex_group_with_single_itemf(bContext *C, PointerRNA *ptr,
688                                                             PropertyRNA *prop, int *free)
689 {
690         return ED_object_vgroup_selection_itemf_helper(C, ptr, prop, free, WT_VGROUP_MASK_ALL);
691 }
692
693 static EnumPropertyItem *rna_vertex_group_select_itemf(bContext *C, PointerRNA *ptr,
694                                                        PropertyRNA *prop, int *free)
695 {
696         return ED_object_vgroup_selection_itemf_helper(C, ptr, prop, free, WT_VGROUP_MASK_ALL & ~(1 << WT_VGROUP_ACTIVE));
697 }
698
699 static void vgroup_operator_subset_select_props(wmOperatorType *ot, bool use_active)
700 {
701         PropertyRNA *prop;
702
703         prop = RNA_def_enum(ot->srna,
704                             "group_select_mode", DummyRNA_NULL_items,
705                             use_active ? WT_VGROUP_ACTIVE : WT_VGROUP_ALL, "Subset",
706                             "Define which subset of Groups shall be used");
707
708         if (use_active) {
709                 RNA_def_enum_funcs(prop, rna_vertex_group_with_single_itemf);
710         }
711         else {
712                 RNA_def_enum_funcs(prop, rna_vertex_group_select_itemf);
713         }
714         ot->prop = prop;
715 }
716
717 /* Copy weight.*/
718 static void vgroup_transfer_weight(float *r_weight_dst, const float weight_src, const WT_ReplaceMode replace_mode)
719 {
720         switch (replace_mode) {
721                 case WT_REPLACE_ALL_WEIGHTS:
722                         *r_weight_dst = weight_src;
723                         break;
724
725                 case WT_REPLACE_EMPTY_WEIGHTS:
726                         if (*r_weight_dst == 0.0f) {
727                                 *r_weight_dst = weight_src;
728                         }
729                         break;
730
731                 default:
732                         BLI_assert(0);
733                         break;
734         }
735 }
736
737 /* Could be exposed externally by implementing it in header with the rest.
738  * Simple refactoring will break something.
739  * For now, naming is ed_ instead of ED_*/
740 static bool ed_vgroup_transfer_weight(Object *ob_dst, Object *ob_src, bDeformGroup *dg_src, Scene *scene,
741                                       WT_Method method, WT_ReplaceMode replace_mode, wmOperator *op)
742 {
743         bDeformGroup *dg_dst;
744         Mesh *me_dst, *me_src;
745         DerivedMesh *dmesh_src;
746         BVHTreeFromMesh tree_mesh_vertices_src, tree_mesh_faces_src = {NULL};
747         MDeformVert **dv_array_src, **dv_array_dst, **dv_src, **dv_dst;
748         MVert *mv_dst, *mv_src;
749         MFace *mface_src, *mf;
750         BVHTreeNearest nearest;
751         MDeformWeight *dw_dst, *dw_src;
752         int dv_tot_src, dv_tot_dst, i, v_index, index_dst, index_src, index_nearest, index_nearest_vertex;
753         unsigned int f_index;
754         float weight, tmp_weight[4], tmp_co[3], normal[3], tmp_mat[4][4], dist_v1, dist_v2, dist_v3, dist_v4;
755         const int use_vert_sel = vertex_group_use_vert_sel(ob_dst);
756
757         /* Ensure vertex group on target.*/
758         if (!defgroup_find_name(ob_dst, dg_src->name)) {
759                 ED_vgroup_add_name(ob_dst, dg_src->name);
760         }
761
762         /* Get destination deformgroup.*/
763         dg_dst = defgroup_find_name(ob_dst, dg_src->name);
764
765         /* Get meshes.*/
766         dmesh_src = mesh_get_derived_deform(scene, ob_src, CD_MASK_BAREMESH);
767         me_dst = ob_dst->data;
768         me_src = ob_src->data;
769
770         /* Sanity check.*/
771         if (!me_src->dvert) {
772                 BKE_report(op->reports, RPT_ERROR, "Transfer failed (source mesh does not have any vertex groups)");
773                 return false;
774         }
775
776         /* Create data in memory when nothing there.*/
777         if (!me_dst->dvert) ED_vgroup_data_create(ob_dst->data);
778
779         /* Get vertex group arrays.*/
780         ED_vgroup_give_parray(ob_src->data, &dv_array_src, &dv_tot_src, false);
781         ED_vgroup_give_parray(ob_dst->data, &dv_array_dst, &dv_tot_dst, use_vert_sel);
782
783         /* Get indexes of vertex groups.*/
784         index_src = BLI_findindex(&ob_src->defbase, dg_src);
785         index_dst = BLI_findindex(&ob_dst->defbase, dg_dst);
786
787         /* Get vertices.*/
788         mv_dst = me_dst->mvert;
789         mv_src = dmesh_src->getVertArray(dmesh_src);
790
791         /* Prepare transformation matrix.*/
792         invert_m4_m4(ob_src->imat, ob_src->obmat);
793         mul_m4_m4m4(tmp_mat, ob_src->imat, ob_dst->obmat);
794
795         /* Clear weights.*/
796         if (replace_mode == WT_REPLACE_ALL_WEIGHTS) {
797                 for (i = 0, dv_dst = dv_array_dst; i < me_dst->totvert; i++, dv_dst++) {
798
799                         if (*dv_dst == NULL) continue;
800
801                         dw_dst = defvert_find_index(*dv_dst, index_dst);
802                         /* Remove vertex from group.*/
803                         if (dw_dst) defvert_remove_group(*dv_dst, dw_dst);
804                 }
805         }
806
807         switch (method) {
808
809                 case WT_BY_INDEX:
810                         /* Check if indices are matching, delete and return if not.*/
811                         if (ob_dst == ob_src || dv_tot_dst == 0 || dv_tot_dst != dv_tot_src ||
812                             dv_array_src == NULL || dv_array_dst == NULL)
813                         {
814                                 ED_vgroup_delete(ob_dst, defgroup_find_name(ob_dst, dg_dst->name));
815                                 if (dv_array_src) MEM_freeN(dv_array_src);
816                                 if (dv_array_dst) MEM_freeN(dv_array_dst);
817                                 dmesh_src->release(dmesh_src);
818                                 BKE_report(op->reports, RPT_ERROR, "Transfer failed (indices are not matching)");
819                                 return false;
820                         }
821
822                         /* Loop through the vertices.*/
823                         for (i = 0, dv_src = dv_array_src, dv_dst = dv_array_dst;
824                              i < me_dst->totvert;
825                              i++, dv_dst++, dv_src++, mv_src++, mv_dst++)
826                         {
827
828                                 if (*dv_dst == NULL) {
829                                         continue;
830                                 }
831
832                                 /* Copy weight.*/
833                                 dw_src = defvert_find_index(*dv_src, index_src);
834                                 if (dw_src && dw_src->weight) {
835                                         dw_dst = defvert_verify_index(*dv_dst, index_dst);
836                                         vgroup_transfer_weight(&dw_dst->weight, dw_src->weight, replace_mode);
837                                 }
838                         }
839                         break;
840
841                 case WT_BY_NEAREST_VERTEX:
842                         /* Make node tree.*/
843                         bvhtree_from_mesh_verts(&tree_mesh_vertices_src, dmesh_src, FLT_EPSILON, 2, 6);
844
845                         /* Loop trough vertices.*/
846                         for (i = 0, dv_dst = dv_array_dst; i < me_dst->totvert; i++, dv_dst++, mv_dst++) {
847
848                                 if (*dv_dst == NULL) {
849                                         continue;
850                                 }
851
852                                 /* Reset nearest.*/
853                                 nearest.dist = FLT_MAX;
854                                 /* It is faster to start searching at the top of the tree instead of previous search result.*/
855                                 nearest.index = -1;
856
857                                 /* Transform into target space.*/
858                                 mul_v3_m4v3(tmp_co, tmp_mat, mv_dst->co);
859
860                                 /* Node tree accelerated search for closest vetex.*/
861                                 BLI_bvhtree_find_nearest(tree_mesh_vertices_src.tree, tmp_co,
862                                                          &nearest, tree_mesh_vertices_src.nearest_callback, &tree_mesh_vertices_src);
863
864                                 /* Copy weight that are not NULL including weight value 0. In relevant cases, existing weights are
865                                  * overwritten prior to this. See the "Clear weights." step above.*/
866                                 dw_src = defvert_find_index(dv_array_src[nearest.index], index_src);
867                                 if (dw_src && dw_src->weight) {
868                                         dw_dst = defvert_verify_index(*dv_dst, index_dst);
869                                         vgroup_transfer_weight(&dw_dst->weight, dw_src->weight, replace_mode);
870                                 }
871                         }
872
873                         /* Free memory.*/
874                         free_bvhtree_from_mesh(&tree_mesh_vertices_src);
875                         break;
876
877                 case WT_BY_NEAREST_FACE:
878                         /* Get faces.*/
879                         DM_ensure_tessface(dmesh_src);
880                         mface_src = dmesh_src->getTessFaceArray(dmesh_src);
881
882                         /* Make node tree.*/
883                         bvhtree_from_mesh_faces(&tree_mesh_faces_src, dmesh_src, FLT_EPSILON, 2, 6);
884
885                         /* Loop through the vertices.*/
886                         for (i = 0, dv_dst = dv_array_dst; i < me_dst->totvert; i++, dv_dst++, mv_dst++) {
887
888                                 if (*dv_dst == NULL) {
889                                         continue;
890                                 }
891
892                                 /* Reset nearest.*/
893                                 nearest.dist = FLT_MAX;
894                                 /* It is faster to start searching at the top of the tree instead of previous search result.*/
895                                 nearest.index = -1;
896
897                                 /* Transform into target space.*/
898                                 mul_v3_m4v3(tmp_co, tmp_mat, mv_dst->co);
899
900                                 /* Node tree accelerated search for closest face.*/
901                                 BLI_bvhtree_find_nearest(tree_mesh_faces_src.tree, tmp_co,
902                                                          &nearest, tree_mesh_faces_src.nearest_callback, &tree_mesh_faces_src);
903                                 index_nearest = nearest.index;
904
905                                 /* Project onto face.*/
906                                 mf = &mface_src[index_nearest];
907                                 normal_tri_v3(normal, mv_src[mf->v1].co, mv_src[mf->v2].co, mv_src[mf->v3].co);
908                                 project_v3_plane(tmp_co, normal, mv_src[mf->v1].co);
909
910                                 /* Interpolate weights over face.*/
911                                 f_index = mf->v4 ? 3 : 2;
912                                 if (f_index == 3) {
913                                         interp_weights_face_v3(tmp_weight, mv_src[mf->v1].co, mv_src[mf->v2].co,
914                                                                mv_src[mf->v3].co, mv_src[mf->v4].co, tmp_co);
915                                 }
916                                 else {
917                                         interp_weights_face_v3(tmp_weight, mv_src[mf->v1].co, mv_src[mf->v2].co,
918                                                                mv_src[mf->v3].co, NULL, tmp_co);
919                                 }
920
921                                 /* Get weights from face.*/
922                                 weight = 0;
923                                 do {
924                                         v_index = (&mf->v1)[f_index];
925                                         weight += tmp_weight[f_index] * defvert_find_weight(dv_array_src[v_index], index_src);
926                                 } while (f_index--);
927
928                                 /* Copy weight that are not NULL including weight value 0. In relevant cases, existing weights are
929                                  * overwritten prior to this. See the "Clear weights." step above.*/
930                                 if (weight > 0) {
931                                         dw_dst = defvert_verify_index(*dv_dst, index_dst);
932                                         vgroup_transfer_weight(&dw_dst->weight, weight, replace_mode);
933                                 }
934                         }
935
936                         /* Free memory.*/
937                         free_bvhtree_from_mesh(&tree_mesh_faces_src);
938                         break;
939
940                 case WT_BY_NEAREST_VERTEX_IN_FACE:
941                         /* Get faces.*/
942                         DM_ensure_tessface(dmesh_src);
943                         mface_src = dmesh_src->getTessFaceArray(dmesh_src);
944
945                         /* Make node tree.*/
946                         bvhtree_from_mesh_faces(&tree_mesh_faces_src, dmesh_src, FLT_EPSILON, 2, 6);
947
948                         /* Loop through the vertices.*/
949                         for (i = 0, dv_dst = dv_array_dst; i < me_dst->totvert; i++, dv_dst++, mv_dst++) {
950
951                                 if (*dv_dst == NULL) {
952                                         continue;
953                                 }
954
955                                 /* Reset nearest.*/
956                                 nearest.dist = FLT_MAX;
957                                 /* It is faster to start searching at the top of the tree instead of previous search result.*/
958                                 nearest.index = -1;
959
960                                 /* Transform into target space.*/
961                                 mul_v3_m4v3(tmp_co, tmp_mat, mv_dst->co);
962
963                                 /* Node tree accelerated search for closest face.*/
964                                 BLI_bvhtree_find_nearest(tree_mesh_faces_src.tree, tmp_co,
965                                                          &nearest, tree_mesh_faces_src.nearest_callback, &tree_mesh_faces_src);
966                                 index_nearest = nearest.index;
967
968                                 /* Get distances.*/
969                                 mf = &mface_src[index_nearest];
970                                 dist_v1 = len_squared_v3v3(tmp_co, mv_src[mf->v1].co);
971                                 dist_v2 = len_squared_v3v3(tmp_co, mv_src[mf->v2].co);
972                                 dist_v3 = len_squared_v3v3(tmp_co, mv_src[mf->v3].co);
973
974                                 /* Get closest vertex.*/
975                                 f_index = mf->v4 ? 3 : 2;
976                                 if (dist_v1 < dist_v2 && dist_v1 < dist_v3) index_nearest_vertex = mf->v1;
977                                 else if (dist_v2 < dist_v3) index_nearest_vertex = mf->v2;
978                                 else index_nearest_vertex = mf->v3;
979                                 if (f_index == 3) {
980                                         dist_v4 = len_squared_v3v3(tmp_co, mv_src[mf->v4].co);
981                                         if (dist_v4 < dist_v1 && dist_v4 < dist_v2 && dist_v4 < dist_v3) {
982                                                 index_nearest_vertex = mf->v4;
983                                         }
984                                 }
985
986                                 /* Copy weight that are not NULL including weight value 0. In relevant cases, existing weights are
987                                  * overwritten prior to this. See the "Clear weights." step above.*/
988                                 dw_src = defvert_find_index(dv_array_src[index_nearest_vertex], index_src);
989                                 if (dw_src && dw_src->weight) {
990                                         dw_dst = defvert_verify_index(*dv_dst, index_dst);
991                                         vgroup_transfer_weight(&dw_dst->weight, dw_src->weight, replace_mode);
992                                 }
993                         }
994
995                         /* Free memory.*/
996                         free_bvhtree_from_mesh(&tree_mesh_faces_src);
997                         break;
998
999                 default:
1000                         BLI_assert(0);
1001                         break;
1002         }
1003
1004         /* Free memory.*/
1005         if (dv_array_src) MEM_freeN(dv_array_src);
1006         if (dv_array_dst) MEM_freeN(dv_array_dst);
1007         dmesh_src->release(dmesh_src);
1008
1009         return true;
1010 }
1011
1012 /***********************End weight transfer (WT)***********************************/
1013
1014 /* for Mesh in Object mode */
1015 /* allows editmode for Lattice */
1016 static void ED_vgroup_nr_vert_add(Object *ob,
1017                                   const int def_nr, const int vertnum,
1018                                   const float weight, const int assignmode)
1019 {
1020         /* add the vert to the deform group with the
1021          * specified number
1022          */
1023         MDeformVert *dvert = NULL;
1024         int tot;
1025
1026         /* get the vert */
1027         ED_vgroup_give_array(ob->data, &dvert, &tot);
1028         
1029         if (dvert == NULL)
1030                 return;
1031
1032         /* check that vertnum is valid before trying to get the relevant dvert */
1033         if ((vertnum < 0) || (vertnum >= tot))
1034                 return;
1035
1036
1037         if (dvert) {
1038                 MDeformVert *dv = &dvert[vertnum];
1039                 MDeformWeight *dw;
1040
1041                 /* Lets first check to see if this vert is
1042                  * already in the weight group -- if so
1043                  * lets update it
1044                  */
1045
1046                 dw = defvert_find_index(dv, def_nr);
1047
1048                 if (dw) {
1049                         switch (assignmode) {
1050                                 case WEIGHT_REPLACE:
1051                                         dw->weight = weight;
1052                                         break;
1053                                 case WEIGHT_ADD:
1054                                         dw->weight += weight;
1055                                         if (dw->weight >= 1.0f)
1056                                                 dw->weight = 1.0f;
1057                                         break;
1058                                 case WEIGHT_SUBTRACT:
1059                                         dw->weight -= weight;
1060                                         /* if the weight is zero or less then
1061                                          * remove the vert from the deform group
1062                                          */
1063                                         if (dw->weight <= 0.0f) {
1064                                                 defvert_remove_group(dv, dw);
1065                                         }
1066                                         break;
1067                         }
1068                 }
1069                 else {
1070                         /* if the vert wasn't in the deform group then
1071                          * we must take a different form of action ...
1072                          */
1073
1074                         switch (assignmode) {
1075                                 case WEIGHT_SUBTRACT:
1076                                         /* if we are subtracting then we don't
1077                                          * need to do anything
1078                                          */
1079                                         return;
1080
1081                                 case WEIGHT_REPLACE:
1082                                 case WEIGHT_ADD:
1083                                         /* if we are doing an additive assignment, then
1084                                          * we need to create the deform weight
1085                                          */
1086
1087                                         /* we checked if the vertex was added before so no need to test again, simply add */
1088                                         defvert_add_index_notest(dv, def_nr, weight);
1089                         }
1090                 }
1091         }
1092 }
1093
1094 /* called while not in editmode */
1095 void ED_vgroup_vert_add(Object *ob, bDeformGroup *dg, int vertnum, float weight, int assignmode)
1096 {
1097         /* add the vert to the deform group with the
1098          * specified assign mode
1099          */
1100         const int def_nr = BLI_findindex(&ob->defbase, dg);
1101
1102         MDeformVert *dv = NULL;
1103         int tot;
1104
1105         /* get the deform group number, exit if
1106          * it can't be found
1107          */
1108         if (def_nr < 0) return;
1109
1110         /* if there's no deform verts then create some,
1111          */
1112         if (ED_vgroup_give_array(ob->data, &dv, &tot) && dv == NULL)
1113                 ED_vgroup_data_create(ob->data);
1114
1115         /* call another function to do the work
1116          */
1117         ED_vgroup_nr_vert_add(ob, def_nr, vertnum, weight, assignmode);
1118 }
1119
1120 /* mesh object mode, lattice can be in editmode */
1121 void ED_vgroup_vert_remove(Object *ob, bDeformGroup *dg, int vertnum)
1122 {
1123         /* This routine removes the vertex from the specified
1124          * deform group.
1125          */
1126
1127         /* TODO, this is slow in a loop, better pass def_nr directly, but leave for later... - campbell */
1128         const int def_nr = BLI_findindex(&ob->defbase, dg);
1129
1130         if (def_nr != -1) {
1131                 MDeformVert *dvert = NULL;
1132                 int tot;
1133
1134                 /* get the deform vertices corresponding to the
1135                  * vertnum
1136                  */
1137                 ED_vgroup_give_array(ob->data, &dvert, &tot);
1138
1139                 if (dvert) {
1140                         MDeformVert *dv = &dvert[vertnum];
1141                         MDeformWeight *dw;
1142
1143                         dw = defvert_find_index(dv, def_nr);
1144                         defvert_remove_group(dv, dw); /* dw can be NULL */
1145                 }
1146         }
1147 }
1148
1149 static float get_vert_def_nr(Object *ob, const int def_nr, const int vertnum)
1150 {
1151         MDeformVert *dv = NULL;
1152
1153         /* get the deform vertices corresponding to the vertnum */
1154         if (ob->type == OB_MESH) {
1155                 Mesh *me = ob->data;
1156
1157                 if (me->edit_btmesh) {
1158                         BMEditMesh *em = me->edit_btmesh;
1159                         const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
1160                         /* warning, this lookup is _not_ fast */
1161
1162                         if (cd_dvert_offset != -1) {
1163                                 BMVert *eve;
1164                                 EDBM_index_arrays_ensure(em, BM_VERT);
1165                                 eve = EDBM_vert_at_index(em, vertnum);
1166                                 dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
1167                         }
1168                         else {
1169                                 return 0.0f;
1170                         }
1171                 }
1172                 else {
1173                         if (me->dvert) {
1174                                 if (vertnum >= me->totvert) {
1175                                         return 0.0f;
1176                                 }
1177                                 dv = &me->dvert[vertnum];
1178                         }
1179                 }
1180         }
1181         else if (ob->type == OB_LATTICE) {
1182                 Lattice *lt = vgroup_edit_lattice(ob);
1183
1184                 if (lt->dvert) {
1185                         if (vertnum >= lt->pntsu * lt->pntsv * lt->pntsw) {
1186                                 return 0.0f;
1187                         }
1188                         dv = &lt->dvert[vertnum];
1189                 }
1190         }
1191         
1192         if (dv) {
1193                 MDeformWeight *dw = defvert_find_index(dv, def_nr);
1194                 if (dw) {
1195                         return dw->weight;
1196                 }
1197         }
1198
1199         return -1;
1200 }
1201
1202 float ED_vgroup_vert_weight(Object *ob, bDeformGroup *dg, int vertnum)
1203 {
1204         const int def_nr = BLI_findindex(&ob->defbase, dg);
1205
1206         if (def_nr == -1) {
1207                 return -1;
1208         }
1209
1210         return get_vert_def_nr(ob, def_nr, vertnum);
1211 }
1212
1213 void ED_vgroup_select_by_name(Object *ob, const char *name)
1214 {   /* note: ob->actdef==0 signals on painting to create a new one, if a bone in posemode is selected */
1215         ob->actdef = defgroup_name_index(ob, name) + 1;
1216 }
1217
1218 /********************** Operator Implementations *********************/
1219
1220 /* only in editmode */
1221 static void vgroup_select_verts(Object *ob, int select)
1222 {
1223         const int def_nr = ob->actdef - 1;
1224
1225         if (!BLI_findlink(&ob->defbase, def_nr)) {
1226                 return;
1227         }
1228
1229         if (ob->type == OB_MESH) {
1230                 Mesh *me = ob->data;
1231
1232                 if (me->edit_btmesh) {
1233                         BMEditMesh *em = me->edit_btmesh;
1234                         const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
1235
1236                         if (cd_dvert_offset != -1) {
1237                                 BMIter iter;
1238                                 BMVert *eve;
1239
1240                                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1241                                         if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
1242                                                 MDeformVert *dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
1243                                                 if (defvert_find_index(dv, def_nr)) {
1244                                                         BM_vert_select_set(em->bm, eve, select);
1245                                                 }
1246                                         }
1247                                 }
1248
1249                                 /* this has to be called, because this function operates on vertices only */
1250                                 if (select) EDBM_select_flush(em);  /* vertices to edges/faces */
1251                                 else EDBM_deselect_flush(em);
1252                         }
1253                 }
1254                 else {
1255                         if (me->dvert) {
1256                                 MVert *mv;
1257                                 MDeformVert *dv;
1258                                 int i;
1259
1260                                 mv = me->mvert;
1261                                 dv = me->dvert;
1262
1263                                 for (i = 0; i < me->totvert; i++, mv++, dv++) {
1264                                         if (!(mv->flag & ME_HIDE)) {
1265                                                 if (defvert_find_index(dv, def_nr)) {
1266                                                         if (select) mv->flag |=  SELECT;
1267                                                         else mv->flag &= ~SELECT;
1268                                                 }
1269                                         }
1270                                 }
1271
1272                                 paintvert_flush_flags(ob);
1273                         }
1274                 }
1275         }
1276         else if (ob->type == OB_LATTICE) {
1277                 Lattice *lt = vgroup_edit_lattice(ob);
1278                 
1279                 if (lt->dvert) {
1280                         MDeformVert *dv;
1281                         BPoint *bp, *actbp = BKE_lattice_active_point_get(lt);
1282                         int a, tot;
1283                         
1284                         dv = lt->dvert;
1285
1286                         tot = lt->pntsu * lt->pntsv * lt->pntsw;
1287                         for (a = 0, bp = lt->def; a < tot; a++, bp++, dv++) {
1288                                 if (defvert_find_index(dv, def_nr)) {
1289                                         if (select) bp->f1 |=  SELECT;
1290                                         else {
1291                                                 bp->f1 &= ~SELECT;
1292                                                 if (actbp && bp == actbp) lt->actbp = LT_ACTBP_NONE;
1293                                         }
1294                                 }
1295                         }
1296                 }
1297         }
1298 }
1299
1300 static void vgroup_duplicate(Object *ob)
1301 {
1302         bDeformGroup *dg, *cdg;
1303         char name[sizeof(dg->name)];
1304         MDeformWeight *dw_org, *dw_cpy;
1305         MDeformVert **dvert_array = NULL;
1306         int i, idg, icdg, dvert_tot = 0;
1307
1308         dg = BLI_findlink(&ob->defbase, (ob->actdef - 1));
1309         if (!dg)
1310                 return;
1311         
1312         if (!strstr(dg->name, "_copy")) {
1313                 BLI_snprintf(name, sizeof(name), "%s_copy", dg->name);
1314         }
1315         else {
1316                 BLI_strncpy(name, dg->name, sizeof(name));
1317         }
1318
1319         cdg = defgroup_duplicate(dg);
1320         BLI_strncpy(cdg->name, name, sizeof(cdg->name));
1321         defgroup_unique_name(cdg, ob);
1322
1323         BLI_addtail(&ob->defbase, cdg);
1324
1325         idg = (ob->actdef - 1);
1326         ob->actdef = BLI_countlist(&ob->defbase);
1327         icdg = (ob->actdef - 1);
1328
1329         /* TODO, we might want to allow only copy selected verts here? - campbell */
1330         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, false);
1331
1332         if (dvert_array) {
1333                 for (i = 0; i < dvert_tot; i++) {
1334                         MDeformVert *dv = dvert_array[i];
1335                         dw_org = defvert_find_index(dv, idg);
1336                         if (dw_org) {
1337                                 /* defvert_verify_index re-allocs org so need to store the weight first */
1338                                 const float weight = dw_org->weight;
1339                                 dw_cpy = defvert_verify_index(dv, icdg);
1340                                 dw_cpy->weight = weight;
1341                         }
1342                 }
1343
1344                 MEM_freeN(dvert_array);
1345         }
1346 }
1347
1348 /**
1349  * Return the subset type of the Vertex Group Selection
1350  */
1351 bool *ED_vgroup_subset_from_select_type(Object *ob, eVGroupSelect subset_type, int *r_vgroup_tot, int *r_subset_count)
1352 {
1353         bool *vgroup_validmap = NULL;
1354         *r_vgroup_tot = BLI_countlist(&ob->defbase);
1355
1356         switch (subset_type) {
1357                 case WT_VGROUP_ACTIVE:
1358                 {
1359                         const int def_nr_active = ob->actdef - 1;
1360                         vgroup_validmap = MEM_mallocN(*r_vgroup_tot * sizeof(*vgroup_validmap), __func__);
1361                         memset(vgroup_validmap, false, *r_vgroup_tot * sizeof(*vgroup_validmap));
1362                         if (def_nr_active < *r_vgroup_tot) {
1363                                 *r_subset_count = 1;
1364                                 vgroup_validmap[def_nr_active] = true;
1365                         }
1366                         else {
1367                                 *r_subset_count = 0;
1368                         }
1369                         break;
1370                 }
1371                 case WT_VGROUP_BONE_SELECT:
1372                 {
1373                         vgroup_validmap = BKE_objdef_selected_get(ob, *r_vgroup_tot, r_subset_count);
1374                         break;
1375                 }
1376                 case WT_VGROUP_BONE_DEFORM:
1377                 {
1378                         int i;
1379                         vgroup_validmap = BKE_objdef_validmap_get(ob, *r_vgroup_tot);
1380                         *r_subset_count = 0;
1381                         for (i = 0; i < *r_vgroup_tot; i++) {
1382                                 if (vgroup_validmap[i] == true) {
1383                                         *r_subset_count += 1;
1384                                 }
1385                         }
1386                         break;
1387                 }
1388                 case WT_VGROUP_BONE_DEFORM_OFF:
1389                 {
1390                         int i;
1391                         vgroup_validmap = BKE_objdef_validmap_get(ob, *r_vgroup_tot);
1392                         *r_subset_count = 0;
1393                         for (i = 0; i < *r_vgroup_tot; i++) {
1394                                 vgroup_validmap[i] = !vgroup_validmap[i];
1395                                 if (vgroup_validmap[i] == true) {
1396                                         *r_subset_count += 1;
1397                                 }
1398                         }
1399                         break;
1400                 }
1401                 case WT_VGROUP_ALL:
1402                 default:
1403                 {
1404                         vgroup_validmap = MEM_mallocN(*r_vgroup_tot * sizeof(*vgroup_validmap), __func__);
1405                         memset(vgroup_validmap, true, *r_vgroup_tot * sizeof(*vgroup_validmap));
1406                         *r_subset_count = *r_vgroup_tot;
1407                         break;
1408                 }
1409         }
1410
1411         return vgroup_validmap;
1412 }
1413
1414 static void vgroup_normalize(Object *ob)
1415 {
1416         MDeformWeight *dw;
1417         MDeformVert *dv, **dvert_array = NULL;
1418         int i, dvert_tot = 0;
1419         const int def_nr = ob->actdef - 1;
1420
1421         const int use_vert_sel = vertex_group_use_vert_sel(ob);
1422
1423         if (!BLI_findlink(&ob->defbase, def_nr)) {
1424                 return;
1425         }
1426
1427         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1428
1429         if (dvert_array) {
1430                 float weight_max = 0.0f;
1431
1432                 for (i = 0; i < dvert_tot; i++) {
1433
1434                         /* in case its not selected */
1435                         if (!(dv = dvert_array[i])) {
1436                                 continue;
1437                         }
1438
1439                         dw = defvert_find_index(dv, def_nr);
1440                         if (dw) {
1441                                 weight_max = max_ff(dw->weight, weight_max);
1442                         }
1443                 }
1444
1445                 if (weight_max > 0.0f) {
1446                         for (i = 0; i < dvert_tot; i++) {
1447                                 
1448                                 /* in case its not selected */
1449                                 if (!(dv = dvert_array[i])) {
1450                                         continue;
1451                                 }
1452
1453                                 dw = defvert_find_index(dv, def_nr);
1454                                 if (dw) {
1455                                         dw->weight /= weight_max;
1456                                         
1457                                         /* in case of division errors with very low weights */
1458                                         CLAMP(dw->weight, 0.0f, 1.0f);
1459                                 }
1460                         }
1461                 }
1462
1463                 MEM_freeN(dvert_array);
1464         }
1465 }
1466
1467 /* This finds all of the vertices face-connected to vert by an edge and returns a
1468  * MEM_allocated array of indices of size count.
1469  * count is an int passed by reference so it can be assigned the value of the length here. */
1470 static int *getSurroundingVerts(Mesh *me, int vert, int *count)
1471 {
1472         MPoly *mp = me->mpoly;
1473         int i = me->totpoly;
1474         /* Instead of looping twice on all polys and loops, and use a temp array, let's rather
1475          * use a BLI_array, with a reasonable starting/reserved size (typically, there are not
1476          * many vertices face-linked to another one, even 8 might be too high...). */
1477         int *verts = NULL;
1478         BLI_array_declare(verts);
1479
1480         BLI_array_reserve(verts, 8);
1481         while (i--) {
1482                 int j = mp->totloop;
1483                 int first_l = mp->totloop - 1;
1484                 MLoop *ml = &me->mloop[mp->loopstart];
1485                 while (j--) {
1486                         /* XXX This assume a vert can only be once in a poly, even though
1487                          *     it seems logical to me, not totally sure of that. */
1488                         if (ml->v == vert) {
1489                                 int a, b, k;
1490                                 if (j == first_l) {
1491                                         /* We are on the first corner. */
1492                                         a = ml[1].v;
1493                                         b = ml[j].v;
1494                                 }
1495                                 else if (!j) {
1496                                         /* We are on the last corner. */
1497                                         a = (ml - 1)->v;
1498                                         b = me->mloop[mp->loopstart].v;
1499                                 }
1500                                 else {
1501                                         a = (ml - 1)->v;
1502                                         b = (ml + 1)->v;
1503                                 }
1504
1505                                 /* Append a and b verts to array, if not yet present. */
1506                                 k = BLI_array_count(verts);
1507                                 /* XXX Maybe a == b is enough? */
1508                                 while (k-- && !(a == b && a == -1)) {
1509                                         if (verts[k] == a)
1510                                                 a = -1;
1511                                         else if (verts[k] == b)
1512                                                 b = -1;
1513                                 }
1514                                 if (a != -1)
1515                                         BLI_array_append(verts, a);
1516                                 if (b != -1)
1517                                         BLI_array_append(verts, b);
1518
1519                                 /* Vert found in this poly, we can go to next one! */
1520                                 break;
1521                         }
1522                         ml++;
1523                 }
1524                 mp++;
1525         }
1526
1527         /* Do not free the array! */
1528         *count = BLI_array_count(verts);
1529         return verts;
1530 }
1531
1532 /* get a single point in space by averaging a point cloud (vectors of size 3)
1533  * coord is the place the average is stored, points is the point cloud, count is the number of points in the cloud
1534  */
1535 static void getSingleCoordinate(MVert *points, int count, float coord[3])
1536 {
1537         int i;
1538         zero_v3(coord);
1539         for (i = 0; i < count; i++) {
1540                 add_v3_v3(coord, points[i].co);
1541         }
1542         mul_v3_fl(coord, 1.0f / count);
1543 }
1544
1545 /* given a plane and a start and end position,
1546  * compute the amount of vertical distance relative to the plane and store it in dists,
1547  * then get the horizontal and vertical change and store them in changes
1548  */
1549 static void getVerticalAndHorizontalChange(const float norm[3], float d, const float coord[3],
1550                                            const float start[3], float distToStart,
1551                                            float *end, float (*changes)[2], float *dists, int index)
1552 {
1553         /* A = Q - ((Q - P).N)N
1554          * D = (a * x0 + b * y0 +c * z0 + d) */
1555         float projA[3], projB[3];
1556
1557         closest_to_plane_v3(projA, coord, norm, start);
1558         closest_to_plane_v3(projB, coord, norm, end);
1559         /* (vertical and horizontal refer to the plane's y and xz respectively)
1560          * vertical distance */
1561         dists[index] = dot_v3v3(norm, end) + d;
1562         /* vertical change */
1563         changes[index][0] = dists[index] - distToStart;
1564         //printf("vc %f %f\n", distance(end, projB, 3)-distance(start, projA, 3), changes[index][0]);
1565         /* horizontal change */
1566         changes[index][1] = len_v3v3(projA, projB);
1567 }
1568
1569 /* I need the derived mesh to be forgotten so the positions are recalculated
1570  * with weight changes (see dm_deform_recalc) */
1571 static void dm_deform_clear(DerivedMesh *dm, Object *ob)
1572 {
1573         if (ob->derivedDeform && (ob->derivedDeform) == dm) {
1574                 ob->derivedDeform->needsFree = 1;
1575                 ob->derivedDeform->release(ob->derivedDeform);
1576                 ob->derivedDeform = NULL;
1577         }
1578         else if (dm) {
1579                 dm->needsFree = 1;
1580                 dm->release(dm);
1581         }
1582 }
1583
1584 /* recalculate the deformation */
1585 static DerivedMesh *dm_deform_recalc(Scene *scene, Object *ob)
1586 {
1587         return mesh_get_derived_deform(scene, ob, CD_MASK_BAREMESH);
1588 }
1589
1590 /* by changing nonzero weights, try to move a vertex in me->mverts with index 'index' to
1591  * distToBe distance away from the provided plane strength can change distToBe so that it moves
1592  * towards distToBe by that percentage cp changes how much the weights are adjusted
1593  * to check the distance
1594  *
1595  * index is the index of the vertex being moved
1596  * norm and d are the plane's properties for the equation: ax + by + cz + d = 0
1597  * coord is a point on the plane
1598  */
1599 static void moveCloserToDistanceFromPlane(Scene *scene, Object *ob, Mesh *me, int index, float norm[3],
1600                                           float coord[3], float d, float distToBe, float strength, float cp)
1601 {
1602         DerivedMesh *dm;
1603         MDeformWeight *dw;
1604         MVert m;
1605         MDeformVert *dvert = me->dvert + index;
1606         int totweight = dvert->totweight;
1607         float oldw = 0;
1608         float oldPos[3] = {0};
1609         float vc, hc, dist = 0.0f;
1610         int i, k;
1611         float (*changes)[2] = MEM_mallocN(sizeof(float *) * totweight * 2, "vertHorzChange");
1612         float *dists = MEM_mallocN(sizeof(float) * totweight, "distance");
1613
1614         /* track if up or down moved it closer for each bone */
1615         int *upDown = MEM_callocN(sizeof(int) * totweight, "upDownTracker");
1616
1617         int *dwIndices = MEM_callocN(sizeof(int) * totweight, "dwIndexTracker");
1618         float distToStart;
1619         int bestIndex = 0;
1620         bool wasChange;
1621         char wasUp;
1622         int lastIndex = -1;
1623         float originalDistToBe = distToBe;
1624         do {
1625                 wasChange = false;
1626                 dm = dm_deform_recalc(scene, ob);
1627                 dm->getVert(dm, index, &m);
1628                 copy_v3_v3(oldPos, m.co);
1629                 distToStart = dot_v3v3(norm, oldPos) + d;
1630
1631                 if (distToBe == originalDistToBe) {
1632                         distToBe += distToStart - distToStart * strength;
1633                 }
1634                 for (i = 0; i < totweight; i++) {
1635                         dwIndices[i] = i;
1636                         dw = (dvert->dw + i);
1637                         vc = hc = 0;
1638                         if (!dw->weight) {
1639                                 changes[i][0] = 0;
1640                                 changes[i][1] = 0;
1641                                 dists[i] = distToStart;
1642                                 continue;
1643                         }
1644                         for (k = 0; k < 2; k++) {
1645                                 if (dm) {
1646                                         dm_deform_clear(dm, ob); dm = NULL;
1647                                 }
1648                                 oldw = dw->weight;
1649                                 if (k) {
1650                                         dw->weight *= 1 + cp;
1651                                 }
1652                                 else {
1653                                         dw->weight /= 1 + cp;
1654                                 }
1655                                 if (dw->weight == oldw) {
1656                                         changes[i][0] = 0;
1657                                         changes[i][1] = 0;
1658                                         dists[i] = distToStart;
1659                                         break;
1660                                 }
1661                                 if (dw->weight > 1) {
1662                                         dw->weight = 1;
1663                                 }
1664                                 dm = dm_deform_recalc(scene, ob);
1665                                 dm->getVert(dm, index, &m);
1666                                 getVerticalAndHorizontalChange(norm, d, coord, oldPos, distToStart, m.co, changes, dists, i);
1667                                 dw->weight = oldw;
1668                                 if (!k) {
1669                                         vc = changes[i][0];
1670                                         hc = changes[i][1];
1671                                         dist = dists[i];
1672                                 }
1673                                 else {
1674                                         if (fabsf(dist - distToBe) < fabsf(dists[i] - distToBe)) {
1675                                                 upDown[i] = 0;
1676                                                 changes[i][0] = vc;
1677                                                 changes[i][1] = hc;
1678                                                 dists[i] = dist;
1679                                         }
1680                                         else {
1681                                                 upDown[i] = 1;
1682                                         }
1683                                         if (fabsf(dists[i] - distToBe) > fabsf(distToStart - distToBe)) {
1684                                                 changes[i][0] = 0;
1685                                                 changes[i][1] = 0;
1686                                                 dists[i] = distToStart;
1687                                         }
1688                                 }
1689                         }
1690                 }
1691                 /* sort the changes by the vertical change */
1692                 for (k = 0; k < totweight; k++) {
1693                         float tf;
1694                         int ti;
1695                         bestIndex = k;
1696                         for (i = k + 1; i < totweight; i++) {
1697                                 dist = dists[i];
1698
1699                                 if (fabsf(dist) > fabsf(dists[i])) {
1700                                         bestIndex = i;
1701                                 }
1702                         }
1703                         /* switch with k */
1704                         if (bestIndex != k) {
1705                                 ti = upDown[k];
1706                                 upDown[k] = upDown[bestIndex];
1707                                 upDown[bestIndex] = ti;
1708
1709                                 ti = dwIndices[k];
1710                                 dwIndices[k] = dwIndices[bestIndex];
1711                                 dwIndices[bestIndex] = ti;
1712
1713                                 tf = changes[k][0];
1714                                 changes[k][0] = changes[bestIndex][0];
1715                                 changes[bestIndex][0] = tf;
1716
1717                                 tf = changes[k][1];
1718                                 changes[k][1] = changes[bestIndex][1];
1719                                 changes[bestIndex][1] = tf;
1720
1721                                 tf = dists[k];
1722                                 dists[k] = dists[bestIndex];
1723                                 dists[bestIndex] = tf;
1724                         }
1725                 }
1726                 bestIndex = -1;
1727                 /* find the best change with an acceptable horizontal change */
1728                 for (i = 0; i < totweight; i++) {
1729                         if (fabsf(changes[i][0]) > fabsf(changes[i][1] * 2.0f)) {
1730                                 bestIndex = i;
1731                                 break;
1732                         }
1733                 }
1734                 if (bestIndex != -1) {
1735                         wasChange = true;
1736                         /* it is a good place to stop if it tries to move the opposite direction
1737                          * (relative to the plane) of last time */
1738                         if (lastIndex != -1) {
1739                                 if (wasUp != upDown[bestIndex]) {
1740                                         wasChange = false;
1741                                 }
1742                         }
1743                         lastIndex = bestIndex;
1744                         wasUp = upDown[bestIndex];
1745                         dw = (dvert->dw + dwIndices[bestIndex]);
1746                         oldw = dw->weight;
1747                         if (upDown[bestIndex]) {
1748                                 dw->weight *= 1 + cp;
1749                         }
1750                         else {
1751                                 dw->weight /= 1 + cp;
1752                         }
1753                         if (dw->weight > 1) {
1754                                 dw->weight = 1;
1755                         }
1756                         if (oldw == dw->weight) {
1757                                 wasChange = false;
1758                         }
1759                         if (dm) {
1760                                 dm_deform_clear(dm, ob); dm = NULL;
1761                         }
1762                 }
1763         } while (wasChange && ((distToStart - distToBe) / fabsf(distToStart - distToBe) ==
1764                                (dists[bestIndex] - distToBe) / fabsf(dists[bestIndex] - distToBe)));
1765
1766         MEM_freeN(upDown);
1767         MEM_freeN(changes);
1768         MEM_freeN(dists);
1769         MEM_freeN(dwIndices);
1770 }
1771
1772 /* this is used to try to smooth a surface by only adjusting the nonzero weights of a vertex 
1773  * but it could be used to raise or lower an existing 'bump.' */
1774 static void vgroup_fix(Scene *scene, Object *ob, float distToBe, float strength, float cp)
1775 {
1776         int i;
1777
1778         Mesh *me = ob->data;
1779         MVert *mvert = me->mvert;
1780         int *verts = NULL;
1781         if (!(me->editflag & ME_EDIT_PAINT_VERT_SEL))
1782                 return;
1783         for (i = 0; i < me->totvert && mvert; i++, mvert++) {
1784                 if (mvert->flag & SELECT) {
1785                         int count = 0;
1786                         if ((verts = getSurroundingVerts(me, i, &count))) {
1787                                 MVert m;
1788                                 MVert *p = MEM_callocN(sizeof(MVert) * (count), "deformedPoints");
1789                                 int k;
1790
1791                                 DerivedMesh *dm = mesh_get_derived_deform(scene, ob, CD_MASK_BAREMESH);
1792                                 k = count;
1793                                 while (k--) {
1794                                         dm->getVert(dm, verts[k], &m);
1795                                         p[k] = m;
1796                                 }
1797                                 
1798                                 if (count >= 3) {
1799                                         float d /*, dist */ /* UNUSED */, mag;
1800                                         float coord[3];
1801                                         float norm[3];
1802                                         getSingleCoordinate(p, count, coord);
1803                                         dm->getVert(dm, i, &m);
1804                                         sub_v3_v3v3(norm, m.co, coord);
1805                                         mag = normalize_v3(norm);
1806                                         if (mag) { /* zeros fix */
1807                                                 d = -dot_v3v3(norm, coord);
1808                                                 /* dist = (dot_v3v3(norm, m.co) + d); */ /* UNUSED */
1809                                                 moveCloserToDistanceFromPlane(scene, ob, me, i, norm, coord, d, distToBe, strength, cp);
1810                                         }
1811                                 }
1812
1813                                 MEM_freeN(verts);
1814                                 MEM_freeN(p);
1815                         }
1816                 }
1817         }
1818 }
1819
1820 static void vgroup_levels_subset(Object *ob, const bool *vgroup_validmap, const int vgroup_tot,
1821                                  const int UNUSED(subset_count),
1822                                  const float offset, const float gain)
1823 {
1824         MDeformWeight *dw;
1825         MDeformVert *dv, **dvert_array = NULL;
1826         int i, dvert_tot = 0;
1827
1828         const int use_vert_sel = vertex_group_use_vert_sel(ob);
1829
1830         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1831
1832         if (dvert_array) {
1833
1834                 for (i = 0; i < dvert_tot; i++) {
1835                         int j;
1836
1837                         /* in case its not selected */
1838                         if (!(dv = dvert_array[i])) {
1839                                 continue;
1840                         }
1841
1842                         j = vgroup_tot;
1843                         while (j--) {
1844                                 if (vgroup_validmap[j]) {
1845                                         dw = defvert_find_index(dv, j);
1846                                         if (dw) {
1847                                                 dw->weight = gain * (dw->weight + offset);
1848
1849                                                 CLAMP(dw->weight, 0.0f, 1.0f);
1850                                         }
1851                                 }
1852                         }
1853                 }
1854
1855                 MEM_freeN(dvert_array);
1856         }
1857 }
1858
1859 static void vgroup_normalize_all(Object *ob, const bool lock_active)
1860 {
1861         MDeformVert *dv, **dvert_array = NULL;
1862         int i, dvert_tot = 0;
1863         const int def_nr = ob->actdef - 1;
1864
1865         const int use_vert_sel = vertex_group_use_vert_sel(ob);
1866
1867         if (lock_active && !BLI_findlink(&ob->defbase, def_nr)) {
1868                 return;
1869         }
1870
1871         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1872
1873         if (dvert_array) {
1874                 const int defbase_tot = BLI_countlist(&ob->defbase);
1875                 bool *lock_flags = BKE_objdef_lock_flags_get(ob, defbase_tot);
1876
1877                 if ((lock_active == true) &&
1878                     (lock_flags != NULL) &&
1879                     (def_nr < defbase_tot))
1880                 {
1881                         lock_flags[def_nr] = true;
1882                 }
1883
1884                 for (i = 0; i < dvert_tot; i++) {
1885                         /* in case its not selected */
1886                         if ((dv = dvert_array[i])) {
1887                                 if (lock_flags) {
1888                                         defvert_normalize_lock_map(dv, lock_flags, defbase_tot);
1889                                 }
1890                                 else if (lock_active) {
1891                                         defvert_normalize_lock_single(dv, def_nr);
1892                                 }
1893                                 else {
1894                                         defvert_normalize(dv);
1895                                 }
1896                         }
1897                 }
1898
1899                 if (lock_flags) {
1900                         MEM_freeN(lock_flags);
1901                 }
1902
1903                 MEM_freeN(dvert_array);
1904         }
1905 }
1906
1907 enum {
1908         VGROUP_TOGGLE,
1909         VGROUP_LOCK,
1910         VGROUP_UNLOCK,
1911         VGROUP_INVERT
1912 };
1913
1914 static EnumPropertyItem vgroup_lock_actions[] = {
1915         {VGROUP_TOGGLE, "TOGGLE", 0, "Toggle", "Unlock all vertex groups if there is at least one locked group, lock all in other case"},
1916         {VGROUP_LOCK, "LOCK", 0, "Lock", "Lock all vertex groups"},
1917         {VGROUP_UNLOCK, "UNLOCK", 0, "Unlock", "Unlock all vertex groups"},
1918         {VGROUP_INVERT, "INVERT", 0, "Invert", "Invert the lock state of all vertex groups"},
1919         {0, NULL, 0, NULL, NULL}
1920 };
1921
1922 static void vgroup_lock_all(Object *ob, int action)
1923 {
1924         bDeformGroup *dg;
1925
1926         if (action == VGROUP_TOGGLE) {
1927                 action = VGROUP_LOCK;
1928                 for (dg = ob->defbase.first; dg; dg = dg->next) {
1929                         if (dg->flag & DG_LOCK_WEIGHT) {
1930                                 action = VGROUP_UNLOCK;
1931                                 break;
1932                         }
1933                 }
1934         }
1935
1936         for (dg = ob->defbase.first; dg; dg = dg->next) {
1937                 switch (action) {
1938                         case VGROUP_LOCK:
1939                                 dg->flag |= DG_LOCK_WEIGHT;
1940                                 break;
1941                         case VGROUP_UNLOCK:
1942                                 dg->flag &= ~DG_LOCK_WEIGHT;
1943                                 break;
1944                         case VGROUP_INVERT:
1945                                 dg->flag ^= DG_LOCK_WEIGHT;
1946                                 break;
1947                 }
1948         }
1949 }
1950
1951 static void vgroup_invert_subset(Object *ob,
1952                                  const bool *vgroup_validmap, const int vgroup_tot,
1953                                  const int UNUSED(subset_count), const bool auto_assign, const bool auto_remove)
1954 {
1955         MDeformWeight *dw;
1956         MDeformVert *dv, **dvert_array = NULL;
1957         int i, dvert_tot = 0;
1958         const int use_vert_sel = vertex_group_use_vert_sel(ob);
1959
1960         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1961
1962         if (dvert_array) {
1963                 for (i = 0; i < dvert_tot; i++) {
1964                         int j;
1965
1966                         /* in case its not selected */
1967                         if (!(dv = dvert_array[i])) {
1968                                 continue;
1969                         }
1970
1971                         j = vgroup_tot;
1972                         while (j--) {
1973
1974                                 if (vgroup_validmap[j]) {
1975                                         if (auto_assign) {
1976                                                 dw = defvert_verify_index(dv, j);
1977                                         }
1978                                         else {
1979                                                 dw = defvert_find_index(dv, j);
1980                                         }
1981
1982                                         if (dw) {
1983                                                 dw->weight = 1.0f - dw->weight;
1984                                                 if (auto_remove && dw->weight <= 0.0f) {
1985                                                         defvert_remove_group(dv, dw);
1986                                                 }
1987                                         }
1988                                 }
1989                         }
1990                 }
1991
1992                 MEM_freeN(dvert_array);
1993         }
1994 }
1995
1996 static void vgroup_blend(Object *ob, const float fac)
1997 {
1998         MDeformVert *dv;
1999         MDeformWeight *dw;
2000         int i, dvert_tot = 0;
2001         const int def_nr = ob->actdef - 1;
2002
2003         BLI_assert(fac >= 0.0f && fac <= 1.0f);
2004
2005         if (ob->type != OB_MESH) {
2006                 return;
2007         }
2008
2009         if (BLI_findlink(&ob->defbase, def_nr)) {
2010                 const float ifac = 1.0f - fac;
2011
2012                 BMEditMesh *em = BKE_editmesh_from_object(ob);
2013                 BMesh *bm = em ? em->bm : NULL;
2014                 Mesh  *me = em ? NULL   : ob->data;
2015
2016                 /* bmesh only*/
2017                 BMEdge *eed;
2018                 BMVert *eve;
2019                 BMIter iter;
2020
2021                 /* mesh only */
2022                 MDeformVert *dvert_array = NULL;
2023
2024
2025                 float *vg_weights;
2026                 float *vg_users;
2027                 int sel1, sel2;
2028
2029                 if (bm) {
2030                         BM_mesh_elem_index_ensure(bm, BM_VERT);
2031                         dvert_tot = bm->totvert;
2032                 }
2033                 else {
2034                         dvert_tot = me->totvert;
2035                         dvert_array = me->dvert;
2036                 }
2037
2038                 vg_weights = MEM_callocN(sizeof(float) * dvert_tot, "vgroup_blend_f");
2039                 vg_users = MEM_callocN(sizeof(int) * dvert_tot, "vgroup_blend_i");
2040
2041                 if (bm) {
2042                         const int cd_dvert_offset = CustomData_get_offset(&bm->vdata, CD_MDEFORMVERT);
2043
2044                         BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
2045                                 sel1 = BM_elem_flag_test(eed->v1, BM_ELEM_SELECT);
2046                                 sel2 = BM_elem_flag_test(eed->v2, BM_ELEM_SELECT);
2047
2048                                 if (sel1 != sel2) {
2049                                         int i1 /* , i2 */;
2050                                         /* i1 is always the selected one */
2051                                         if (sel1) {
2052                                                 i1 = BM_elem_index_get(eed->v1);
2053                                                 /* i2 = BM_elem_index_get(eed->v2); */ /* UNUSED */
2054                                                 eve = eed->v2;
2055                                         }
2056                                         else {
2057                                                 /* i2 = BM_elem_index_get(eed->v1); */ /* UNUSED */
2058                                                 i1 = BM_elem_index_get(eed->v2);
2059                                                 eve = eed->v1;
2060                                         }
2061
2062                                         dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
2063                                         dw = defvert_find_index(dv, def_nr);
2064                                         if (dw) {
2065                                                 vg_weights[i1] += dw->weight;
2066                                         }
2067                                         vg_users[i1]++;
2068                                 }
2069                         }
2070
2071                         BM_ITER_MESH_INDEX (eve, &iter, bm, BM_VERTS_OF_MESH, i) {
2072                                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT) && vg_users[i] > 0) {
2073                                         dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
2074
2075                                         dw = defvert_verify_index(dv, def_nr);
2076                                         dw->weight = (fac * (vg_weights[i] / (float)vg_users[i])) + (ifac * dw->weight);
2077                                         /* in case of division errors */
2078                                         CLAMP(dw->weight, 0.0f, 1.0f);
2079                                 }
2080                         }
2081                 }
2082                 else {
2083                         MEdge *ed = me->medge;
2084                         MVert *mv;
2085
2086                         for (i = 0; i < me->totedge; i++, ed++) {
2087                                 sel1 = me->mvert[ed->v1].flag & SELECT;
2088                                 sel2 = me->mvert[ed->v2].flag & SELECT;
2089
2090                                 if (sel1 != sel2) {
2091                                         int i1, i2;
2092                                         /* i1 is always the selected one */
2093                                         if (sel1) {
2094                                                 i1 = ed->v1;
2095                                                 i2 = ed->v2;
2096                                         }
2097                                         else {
2098                                                 i2 = ed->v1;
2099                                                 i1 = ed->v2;
2100                                         }
2101
2102                                         dv = &dvert_array[i2];
2103                                         dw = defvert_find_index(dv, def_nr);
2104                                         if (dw) {
2105                                                 vg_weights[i1] += dw->weight;
2106                                         }
2107                                         vg_users[i1]++;
2108                                 }
2109                         }
2110
2111                         mv = me->mvert;
2112                         dv = dvert_array;
2113
2114                         for (i = 0; i < dvert_tot; i++, mv++, dv++) {
2115                                 if ((mv->flag & SELECT) && (vg_users[i] > 0)) {
2116                                         dw = defvert_verify_index(dv, def_nr);
2117                                         dw->weight = (fac * (vg_weights[i] / (float)vg_users[i])) + (ifac * dw->weight);
2118
2119                                         /* in case of division errors */
2120                                         CLAMP(dw->weight, 0.0f, 1.0f);
2121                                 }
2122                         }
2123                 }
2124
2125                 MEM_freeN(vg_weights);
2126                 MEM_freeN(vg_users);
2127         }
2128 }
2129
2130 static int inv_cmp_mdef_vert_weights(const void *a1, const void *a2)
2131 {
2132         /* qsort sorts in ascending order.  We want descending order to save a memcopy
2133          * so this compare function is inverted from the standard greater than comparison qsort needs.
2134          * A normal compare function is called with two pointer arguments and should return an integer less than, equal to,
2135          * or greater than zero corresponding to whether its first argument is considered less than, equal to,
2136          * or greater than its second argument.  This does the opposite. */
2137         const struct MDeformWeight *dw1 = a1, *dw2 = a2;
2138
2139         if      (dw1->weight < dw2->weight) return  1;
2140         else if (dw1->weight > dw2->weight) return -1;
2141         else if (&dw1 < &dw2)               return  1; /* compare addresses so we have a stable sort algorithm */
2142         else                                return -1;
2143 }
2144
2145 /* Used for limiting the number of influencing bones per vertex when exporting
2146  * skinned meshes.  if all_deform_weights is True, limit all deform modifiers
2147  * to max_weights regardless of type, otherwise, only limit the number of influencing bones per vertex*/
2148 static int vgroup_limit_total_subset(Object *ob,
2149                                      const bool *vgroup_validmap,
2150                                      const int vgroup_tot,
2151                                      const int subset_count,
2152                                      const int max_weights)
2153 {
2154         MDeformVert *dv, **dvert_array = NULL;
2155         int i, dvert_tot = 0;
2156         const int use_vert_sel = vertex_group_use_vert_sel(ob);
2157         int remove_tot = 0;
2158
2159         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
2160
2161         if (dvert_array) {
2162                 int num_to_drop = 0;
2163
2164                 for (i = 0; i < dvert_tot; i++) {
2165
2166                         MDeformWeight *dw_temp;
2167                         int bone_count = 0, non_bone_count = 0;
2168                         int j;
2169
2170                         /* in case its not selected */
2171                         if (!(dv = dvert_array[i])) {
2172                                 continue;
2173                         }
2174
2175                         num_to_drop = subset_count - max_weights;
2176
2177                         /* first check if we even need to test further */
2178                         if (num_to_drop > 0) {
2179                                 /* re-pack dw array so that non-bone weights are first, bone-weighted verts at end
2180                                  * sort the tail, then copy only the truncated array back to dv->dw */
2181                                 dw_temp = MEM_mallocN(sizeof(MDeformWeight) * dv->totweight, __func__);
2182                                 bone_count = 0; non_bone_count = 0;
2183                                 for (j = 0; j < dv->totweight; j++) {
2184                                         if (LIKELY(dv->dw[j].def_nr < vgroup_tot) &&
2185                                             vgroup_validmap[dv->dw[j].def_nr])
2186                                         {
2187                                                 dw_temp[dv->totweight - 1 - bone_count] = dv->dw[j];
2188                                                 bone_count += 1;
2189                                         }
2190                                         else {
2191                                                 dw_temp[non_bone_count] = dv->dw[j];
2192                                                 non_bone_count += 1;
2193                                         }
2194                                 }
2195                                 BLI_assert(bone_count + non_bone_count == dv->totweight);
2196                                 num_to_drop = bone_count - max_weights;
2197                                 if (num_to_drop > 0) {
2198                                         qsort(&dw_temp[non_bone_count], bone_count, sizeof(MDeformWeight), inv_cmp_mdef_vert_weights);
2199                                         dv->totweight -= num_to_drop;
2200                                         /* Do we want to clean/normalize here? */
2201                                         MEM_freeN(dv->dw);
2202                                         dv->dw = MEM_reallocN(dw_temp, sizeof(MDeformWeight) * dv->totweight);
2203                                         remove_tot += num_to_drop;
2204                                 }
2205                                 else {
2206                                         MEM_freeN(dw_temp);
2207                                 }
2208                         }
2209
2210                 }
2211                 MEM_freeN(dvert_array);
2212
2213         }
2214
2215         return remove_tot;
2216 }
2217
2218
2219 static void vgroup_clean_subset(Object *ob, const bool *vgroup_validmap, const int vgroup_tot, const int UNUSED(subset_count),
2220                                 const float epsilon, const bool keep_single)
2221 {
2222         MDeformVert **dvert_array = NULL;
2223         int i, dvert_tot = 0;
2224         const int use_vert_sel = vertex_group_use_vert_sel(ob);
2225
2226         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
2227
2228         if (dvert_array) {
2229                 MDeformVert *dv;
2230                 MDeformWeight *dw;
2231
2232                 for (i = 0; i < dvert_tot; i++) {
2233                         int j;
2234
2235                         /* in case its not selected */
2236                         if (!(dv = dvert_array[i])) {
2237                                 continue;
2238                         }
2239
2240                         j = dv->totweight;
2241
2242                         while (j--) {
2243
2244                                 if (keep_single && dv->totweight == 1)
2245                                         break;
2246
2247                                 dw = dv->dw + j;
2248                                 if ((dw->def_nr < vgroup_tot) && vgroup_validmap[dw->def_nr]) {
2249                                         if (dw->weight <= epsilon) {
2250                                                 defvert_remove_group(dv, dw);
2251                                         }
2252                                 }
2253                         }
2254                 }
2255
2256                 MEM_freeN(dvert_array);
2257         }
2258 }
2259
2260
2261 static void dvert_mirror_op(MDeformVert *dvert, MDeformVert *dvert_mirr,
2262                             const char sel, const char sel_mirr,
2263                             const int *flip_map, const int flip_map_len,
2264                             const bool mirror_weights, const bool flip_vgroups, const bool all_vgroups,
2265                             const int act_vgroup)
2266 {
2267         BLI_assert(sel || sel_mirr);
2268
2269         if (sel_mirr && sel) {
2270                 /* swap */
2271                 if (mirror_weights) {
2272                         if (all_vgroups) {
2273                                 SWAP(MDeformVert, *dvert, *dvert_mirr);
2274                         }
2275                         else {
2276                                 MDeformWeight *dw =      defvert_find_index(dvert, act_vgroup);
2277                                 MDeformWeight *dw_mirr = defvert_find_index(dvert_mirr, act_vgroup);
2278
2279                                 if (dw || dw_mirr) {
2280                                         if (dw_mirr == NULL)
2281                                                 dw_mirr = defvert_verify_index(dvert_mirr, act_vgroup);
2282                                         if (dw == NULL)
2283                                                 dw = defvert_verify_index(dvert, act_vgroup);
2284
2285                                         SWAP(float, dw->weight, dw_mirr->weight);
2286                                 }
2287                         }
2288                 }
2289
2290                 if (flip_vgroups) {
2291                         defvert_flip(dvert, flip_map, flip_map_len);
2292                         defvert_flip(dvert_mirr, flip_map, flip_map_len);
2293                 }
2294         }
2295         else {
2296                 /* dvert should always be the target, only swaps pointer */
2297                 if (sel_mirr) {
2298                         SWAP(MDeformVert *, dvert, dvert_mirr);
2299                 }
2300
2301                 if (mirror_weights) {
2302                         if (all_vgroups) {
2303                                 defvert_copy(dvert, dvert_mirr);
2304                         }
2305                         else {
2306                                 defvert_copy_index(dvert, dvert_mirr, act_vgroup);
2307                         }
2308                 }
2309
2310                 /* flip map already modified for 'all_vgroups' */
2311                 if (flip_vgroups) {
2312                         defvert_flip(dvert, flip_map, flip_map_len);
2313                 }
2314         }
2315 }
2316
2317 /* TODO, vgroup locking */
2318 /* TODO, face masking */
2319 void ED_vgroup_mirror(Object *ob,
2320                       const bool mirror_weights, const bool flip_vgroups,
2321                       const bool all_vgroups, const bool use_topology,
2322                       int *r_totmirr, int *r_totfail)
2323 {
2324
2325 #define VGROUP_MIRR_OP                                                        \
2326         dvert_mirror_op(dvert, dvert_mirr,                                    \
2327                         sel, sel_mirr,                                        \
2328                         flip_map, flip_map_len,                               \
2329                         mirror_weights, flip_vgroups,                         \
2330                         all_vgroups, def_nr                                   \
2331                         )
2332
2333         BMVert *eve, *eve_mirr;
2334         MDeformVert *dvert, *dvert_mirr;
2335         char sel, sel_mirr;
2336         int *flip_map = NULL, flip_map_len;
2337         const int def_nr = ob->actdef - 1;
2338         int totmirr = 0, totfail = 0;
2339
2340         *r_totmirr = *r_totfail = 0;
2341
2342         if ((mirror_weights == false && flip_vgroups == false) ||
2343             (BLI_findlink(&ob->defbase, def_nr) == NULL))
2344         {
2345                 return;
2346         }
2347
2348         if (flip_vgroups) {
2349                 flip_map = all_vgroups ?
2350                            defgroup_flip_map(ob, &flip_map_len, false) :
2351                            defgroup_flip_map_single(ob, &flip_map_len, false, def_nr);
2352
2353                 BLI_assert(flip_map != NULL);
2354
2355                 if (flip_map == NULL) {
2356                         /* something went wrong!, possibly no groups */
2357                         return;
2358                 }
2359         }
2360         else {
2361                 flip_map = NULL;
2362                 flip_map_len = 0;
2363         }
2364
2365         /* only the active group */
2366         if (ob->type == OB_MESH) {
2367                 Mesh *me = ob->data;
2368                 BMEditMesh *em = me->edit_btmesh;
2369
2370                 if (em) {
2371                         const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
2372                         BMIter iter;
2373
2374                         if (cd_dvert_offset == -1) {
2375                                 goto cleanup;
2376                         }
2377
2378                         EDBM_verts_mirror_cache_begin(em, 0, true, false, use_topology);
2379
2380                         /* Go through the list of editverts and assign them */
2381                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2382                                 if ((eve_mirr = EDBM_verts_mirror_get(em, eve))) {
2383                                         if (eve_mirr != eve) {
2384                                                 sel = BM_elem_flag_test(eve, BM_ELEM_SELECT);
2385                                                 sel_mirr = BM_elem_flag_test(eve_mirr, BM_ELEM_SELECT);
2386
2387                                                 if ((sel || sel_mirr) && (eve != eve_mirr)) {
2388                                                         dvert      = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
2389                                                         dvert_mirr = BM_ELEM_CD_GET_VOID_P(eve_mirr, cd_dvert_offset);
2390
2391                                                         VGROUP_MIRR_OP;
2392                                                         totmirr++;
2393                                                 }
2394                                         }
2395
2396                                         /* don't use these again */
2397                                         EDBM_verts_mirror_cache_clear(em, eve);
2398                                         EDBM_verts_mirror_cache_clear(em, eve_mirr);
2399                                 }
2400                                 else {
2401                                         totfail++;
2402                                 }
2403                         }
2404                         EDBM_verts_mirror_cache_end(em);
2405                 }
2406                 else {
2407                         /* object mode / weight paint */
2408                         MVert *mv, *mv_mirr;
2409                         int vidx, vidx_mirr;
2410                         const int use_vert_sel = (me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
2411
2412                         if (me->dvert == NULL) {
2413                                 goto cleanup;
2414                         }
2415
2416                         if (!use_vert_sel) {
2417                                 sel = sel_mirr = true;
2418                         }
2419
2420                         /* tag verts we have used */
2421                         for (vidx = 0, mv = me->mvert; vidx < me->totvert; vidx++, mv++) {
2422                                 mv->flag &= ~ME_VERT_TMP_TAG;
2423                         }
2424
2425                         for (vidx = 0, mv = me->mvert; vidx < me->totvert; vidx++, mv++) {
2426                                 if ((mv->flag & ME_VERT_TMP_TAG) == 0) {
2427                                         if ((vidx_mirr = mesh_get_x_mirror_vert(ob, vidx, use_topology)) != -1) {
2428                                                 if (vidx != vidx_mirr) {
2429                                                         mv_mirr = &me->mvert[vidx_mirr];
2430                                                         if ((mv_mirr->flag & ME_VERT_TMP_TAG) == 0) {
2431
2432                                                                 if (use_vert_sel) {
2433                                                                         sel = mv->flag & SELECT;
2434                                                                         sel_mirr = mv_mirr->flag & SELECT;
2435                                                                 }
2436
2437                                                                 if (sel || sel_mirr) {
2438                                                                         dvert = &me->dvert[vidx];
2439                                                                         dvert_mirr = &me->dvert[vidx_mirr];
2440
2441                                                                         VGROUP_MIRR_OP;
2442                                                                         totmirr++;
2443                                                                 }
2444
2445                                                                 mv->flag |= ME_VERT_TMP_TAG;
2446                                                                 mv_mirr->flag |= ME_VERT_TMP_TAG;
2447                                                         }
2448                                                 }
2449                                         }
2450                                         else {
2451                                                 totfail++;
2452                                         }
2453                                 }
2454                         }
2455                 }
2456         }
2457         else if (ob->type == OB_LATTICE) {
2458                 Lattice *lt = vgroup_edit_lattice(ob);
2459                 int i1, i2;
2460                 int u, v, w;
2461                 int pntsu_half;
2462                 /* half but found up odd value */
2463
2464                 if (lt->pntsu == 1 || lt->dvert == NULL) {
2465                         goto cleanup;
2466                 }
2467
2468                 /* unlike editmesh we know that by only looping over the first half of
2469                  * the 'u' indices it will cover all points except the middle which is
2470                  * ok in this case */
2471                 pntsu_half = lt->pntsu / 2;
2472
2473                 for (w = 0; w < lt->pntsw; w++) {
2474                         for (v = 0; v < lt->pntsv; v++) {
2475                                 for (u = 0; u < pntsu_half; u++) {
2476                                         int u_inv = (lt->pntsu - 1) - u;
2477                                         if (u != u_inv) {
2478                                                 BPoint *bp, *bp_mirr;
2479
2480                                                 i1 = BKE_lattice_index_from_uvw(lt, u, v, w);
2481                                                 i2 = BKE_lattice_index_from_uvw(lt, u_inv, v, w);
2482
2483                                                 bp = &lt->def[i1];
2484                                                 bp_mirr = &lt->def[i2];
2485
2486                                                 sel = bp->f1 & SELECT;
2487                                                 sel_mirr = bp_mirr->f1 & SELECT;
2488
2489                                                 if (sel || sel_mirr) {
2490                                                         dvert = &lt->dvert[i1];
2491                                                         dvert_mirr = &lt->dvert[i2];
2492
2493                                                         VGROUP_MIRR_OP;
2494                                                         totmirr++;
2495                                                 }
2496                                         }
2497                                 }
2498                         }
2499                 }
2500         }
2501
2502         /* disabled, confusing when you have an active pose bone */
2503 #if 0
2504         /* flip active group index */
2505         if (flip_vgroups && flip_map[def_nr] >= 0)
2506                 ob->actdef = flip_map[def_nr] + 1;
2507 #endif
2508
2509 cleanup:
2510         *r_totmirr = totmirr;
2511         *r_totfail = totfail;
2512
2513         if (flip_map) MEM_freeN(flip_map);
2514
2515 #undef VGROUP_MIRR_OP
2516
2517 }
2518
2519 static void vgroup_remap_update_users(Object *ob, int *map)
2520 {
2521         ExplodeModifierData *emd;
2522         ModifierData *md;
2523         ParticleSystem *psys;
2524         ClothModifierData *clmd;
2525         ClothSimSettings *clsim;
2526         int a;
2527
2528         /* these cases don't use names to refer to vertex groups, so when
2529          * they get deleted the numbers get out of sync, this corrects that */
2530
2531         if (ob->soft)
2532                 ob->soft->vertgroup = map[ob->soft->vertgroup];
2533
2534         for (md = ob->modifiers.first; md; md = md->next) {
2535                 if (md->type == eModifierType_Explode) {
2536                         emd = (ExplodeModifierData *)md;
2537                         emd->vgroup = map[emd->vgroup];
2538                 }
2539                 else if (md->type == eModifierType_Cloth) {
2540                         clmd = (ClothModifierData *)md;
2541                         clsim = clmd->sim_parms;
2542
2543                         if (clsim) {
2544                                 clsim->vgroup_mass = map[clsim->vgroup_mass];
2545                                 clsim->vgroup_bend = map[clsim->vgroup_bend];
2546                                 clsim->vgroup_struct = map[clsim->vgroup_struct];
2547                         }
2548                 }
2549         }
2550
2551         for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2552                 for (a = 0; a < PSYS_TOT_VG; a++)
2553                         psys->vgroup[a] = map[psys->vgroup[a]];
2554         }
2555 }
2556
2557
2558 static void vgroup_delete_update_users(Object *ob, int id)
2559 {
2560         int i, defbase_tot = BLI_countlist(&ob->defbase) + 1;
2561         int *map = MEM_mallocN(sizeof(int) * defbase_tot, "vgroup del");
2562
2563         map[id] = map[0] = 0;
2564         for (i = 1; i < id; i++) map[i] = i;
2565         for (i = id + 1; i < defbase_tot; i++) map[i] = i - 1;
2566
2567         vgroup_remap_update_users(ob, map);
2568         MEM_freeN(map);
2569 }
2570
2571
2572 static void vgroup_delete_object_mode(Object *ob, bDeformGroup *dg)
2573 {
2574         MDeformVert *dvert_array = NULL;
2575         int dvert_tot = 0;
2576         const int def_nr = BLI_findindex(&ob->defbase, dg);
2577
2578         assert(def_nr > -1);
2579
2580         ED_vgroup_give_array(ob->data, &dvert_array, &dvert_tot);
2581
2582         if (dvert_array) {
2583                 int i, j;
2584                 MDeformVert *dv;
2585                 for (i = 0, dv = dvert_array; i < dvert_tot; i++, dv++) {
2586                         MDeformWeight *dw;
2587
2588                         dw = defvert_find_index(dv, def_nr);
2589                         defvert_remove_group(dv, dw); /* dw can be NULL */
2590
2591                         /* inline, make into a function if anything else needs to do this */
2592                         for (j = 0; j < dv->totweight; j++) {
2593                                 if (dv->dw[j].def_nr > def_nr) {
2594                                         dv->dw[j].def_nr--;
2595                                 }
2596                         }
2597                         /* done */
2598                 }
2599         }
2600
2601         vgroup_delete_update_users(ob, def_nr + 1);
2602
2603         /* Remove the group */
2604         BLI_freelinkN(&ob->defbase, dg);
2605
2606         /* Update the active deform index if necessary */
2607         if (ob->actdef > def_nr)
2608                 ob->actdef--;
2609         if (ob->actdef < 1 && ob->defbase.first)
2610                 ob->actdef = 1;
2611
2612         /* remove all dverts */
2613         if (ob->defbase.first == NULL) {
2614                 if (ob->type == OB_MESH) {
2615                         Mesh *me = ob->data;
2616                         CustomData_free_layer_active(&me->vdata, CD_MDEFORMVERT, me->totvert);
2617                         me->dvert = NULL;
2618                 }
2619                 else if (ob->type == OB_LATTICE) {
2620                         Lattice *lt = ob->data;
2621                         if (lt->dvert) {
2622                                 MEM_freeN(lt->dvert);
2623                                 lt->dvert = NULL;
2624                         }
2625                 }
2626         }
2627 }
2628
2629 /* only in editmode */
2630 /* removes from active defgroup, if allverts==0 only selected vertices */
2631 static bool vgroup_active_remove_verts(Object *ob, const bool allverts, bDeformGroup *dg)
2632 {
2633         MDeformVert *dv;
2634         const int def_nr = BLI_findindex(&ob->defbase, dg);
2635         bool change = false;
2636
2637         if (ob->type == OB_MESH) {
2638                 Mesh *me = ob->data;
2639
2640                 if (me->edit_btmesh) {
2641                         BMEditMesh *em = me->edit_btmesh;
2642                         const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
2643
2644                         if (cd_dvert_offset != -1) {
2645                                 BMVert *eve;
2646                                 BMIter iter;
2647
2648                                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2649                                         dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
2650
2651                                         if (dv && dv->dw && (allverts || BM_elem_flag_test(eve, BM_ELEM_SELECT))) {
2652                                                 MDeformWeight *dw = defvert_find_index(dv, def_nr);
2653                                                 defvert_remove_group(dv, dw); /* dw can be NULL */
2654                                                 change = true;
2655                                         }
2656                                 }
2657                         }
2658                 }
2659                 else {
2660                         if (me->dvert) {
2661                                 MVert *mv;
2662                                 int i;
2663
2664                                 mv = me->mvert;
2665                                 dv = me->dvert;
2666
2667                                 for (i = 0; i < me->totvert; i++, mv++, dv++) {
2668                                         if (mv->flag & SELECT) {
2669                                                 if (dv->dw && (allverts || (mv->flag & SELECT))) {
2670                                                         MDeformWeight *dw = defvert_find_index(dv, def_nr);
2671                                                         defvert_remove_group(dv, dw); /* dw can be NULL */
2672                                                         change = true;
2673                                                 }
2674                                         }
2675                                 }
2676                         }
2677                 }
2678         }
2679         else if (ob->type == OB_LATTICE) {
2680                 Lattice *lt = vgroup_edit_lattice(ob);
2681                 
2682                 if (lt->dvert) {
2683                         BPoint *bp;
2684                         int i, tot = lt->pntsu * lt->pntsv * lt->pntsw;
2685                                 
2686                         for (i = 0, bp = lt->def; i < tot; i++, bp++) {
2687                                 if (allverts || (bp->f1 & SELECT)) {
2688                                         MDeformWeight *dw;
2689
2690                                         dv = &lt->dvert[i];
2691
2692                                         dw = defvert_find_index(dv, def_nr);
2693                                         defvert_remove_group(dv, dw); /* dw can be NULL */
2694                                         change = true;
2695                                 }
2696                         }
2697                 }
2698         }
2699
2700         return change;
2701 }
2702
2703 static void vgroup_delete_edit_mode(Object *ob, bDeformGroup *dg)
2704 {
2705         int i;
2706         const int dg_index = BLI_findindex(&ob->defbase, dg);
2707
2708         assert(dg_index > -1);
2709
2710         /* Make sure that no verts are using this group */
2711         if (vgroup_active_remove_verts(ob, true, dg) == false) {
2712                 /* do nothing */
2713         }
2714         /* Make sure that any verts with higher indices are adjusted accordingly */
2715         else if (ob->type == OB_MESH) {
2716                 Mesh *me = ob->data;
2717                 BMEditMesh *em = me->edit_btmesh;
2718                 const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
2719
2720                 BMIter iter;
2721                 BMVert *eve;
2722                 MDeformVert *dvert;
2723
2724                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2725                         dvert = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
2726
2727                         if (dvert)
2728                                 for (i = 0; i < dvert->totweight; i++)
2729                                         if (dvert->dw[i].def_nr > dg_index)
2730                                                 dvert->dw[i].def_nr--;
2731                 }
2732         }
2733         else if (ob->type == OB_LATTICE) {
2734                 Lattice *lt = vgroup_edit_lattice(ob);
2735                 BPoint *bp;
2736                 MDeformVert *dvert = lt->dvert;
2737                 int a, tot;
2738
2739                 if (dvert) {
2740                         tot = lt->pntsu * lt->pntsv * lt->pntsw;
2741                         for (a = 0, bp = lt->def; a < tot; a++, bp++, dvert++) {
2742                                 for (i = 0; i < dvert->totweight; i++) {
2743                                         if (dvert->dw[i].def_nr > dg_index)
2744                                                 dvert->dw[i].def_nr--;
2745                                 }
2746                         }
2747                 }
2748         }
2749
2750         vgroup_delete_update_users(ob, dg_index + 1);
2751
2752         /* Remove the group */
2753         BLI_freelinkN(&ob->defbase, dg);
2754
2755         /* Update the active deform index if necessary */
2756         if (ob->actdef > dg_index)
2757                 ob->actdef--;
2758         if (ob->actdef < 1 && ob->defbase.first)
2759                 ob->actdef = 1;
2760
2761         /* remove all dverts */
2762         if (ob->defbase.first == NULL) {
2763                 if (ob->type == OB_MESH) {
2764                         Mesh *me = ob->data;
2765                         CustomData_free_layer_active(&me->vdata, CD_MDEFORMVERT, me->totvert);
2766                         me->dvert = NULL;
2767                 }
2768                 else if (ob->type == OB_LATTICE) {
2769                         Lattice *lt = vgroup_edit_lattice(ob);
2770                         if (lt->dvert) {
2771                                 MEM_freeN(lt->dvert);
2772                                 lt->dvert = NULL;
2773                         }
2774                 }
2775         }
2776 }
2777
2778 static bool vgroup_object_in_edit_mode(Object *ob)
2779 {
2780         if (ob->type == OB_MESH)
2781                 return (BKE_editmesh_from_object(ob) != NULL);
2782         else if (ob->type == OB_LATTICE)
2783                 return (((Lattice *)ob->data)->editlatt != NULL);
2784         
2785         return false;
2786 }
2787
2788 static bool vgroup_object_in_wpaint_vert_select(Object *ob)
2789 {
2790         if (ob->type == OB_MESH) {
2791                 Mesh *me = ob->data;
2792                 return ( (ob->mode & OB_MODE_WEIGHT_PAINT) &&
2793                          (me->edit_btmesh == NULL) &&
2794                          (ME_EDIT_PAINT_SEL_MODE(me) == SCE_SELECT_VERTEX) );
2795         }
2796
2797         return false;
2798 }
2799
2800 static void vgroup_delete(Object *ob)
2801 {
2802         bDeformGroup *dg = BLI_findlink(&ob->defbase, ob->actdef - 1);
2803         if (!dg)
2804                 return;
2805
2806         if (vgroup_object_in_edit_mode(ob))
2807                 vgroup_delete_edit_mode(ob, dg);
2808         else
2809                 vgroup_delete_object_mode(ob, dg);
2810 }
2811
2812 static void vgroup_delete_all(Object *ob)
2813 {
2814         /* Remove all DVerts */
2815         if (ob->type == OB_MESH) {
2816                 Mesh *me = ob->data;
2817                 CustomData_free_layer_active(&me->vdata, CD_MDEFORMVERT, me->totvert);
2818                 me->dvert = NULL;
2819         }
2820         else if (ob->type == OB_LATTICE) {
2821                 Lattice *lt = vgroup_edit_lattice(ob);
2822                 if (lt->dvert) {
2823                         MEM_freeN(lt->dvert);
2824                         lt->dvert = NULL;
2825                 }
2826         }
2827         
2828         /* Remove all DefGroups */
2829         BLI_freelistN(&ob->defbase);
2830         
2831         /* Fix counters/indices */
2832         ob->actdef = 0;
2833 }
2834
2835 /* only in editmode */
2836 static void vgroup_assign_verts(Object *ob, const float weight)
2837 {
2838         const int def_nr = ob->actdef - 1;
2839
2840         if (!BLI_findlink(&ob->defbase, def_nr))
2841                 return;
2842
2843         if (ob->type == OB_MESH) {
2844                 Mesh *me = ob->data;
2845
2846                 if (me->edit_btmesh) {
2847                         BMEditMesh *em = me->edit_btmesh;
2848                         int cd_dvert_offset;
2849
2850                         BMIter iter;
2851                         BMVert *eve;
2852
2853                         if (!CustomData_has_layer(&em->bm->vdata, CD_MDEFORMVERT))
2854                                 BM_data_layer_add(em->bm, &em->bm->vdata, CD_MDEFORMVERT);
2855
2856                         cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
2857
2858                         /* Go through the list of editverts and assign them */
2859                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2860                                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
2861                                         MDeformVert *dv;
2862                                         MDeformWeight *dw;
2863                                         dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset); /* can be NULL */
2864                                         dw = defvert_verify_index(dv, def_nr);
2865                                         if (dw) {
2866                                                 dw->weight = weight;
2867                                         }
2868                                 }
2869                         }
2870                 }
2871                 else {
2872                         MVert *mv;
2873                         MDeformVert *dv;
2874                         int i;
2875
2876                         if (!me->dvert) {
2877                                 ED_vgroup_data_create(&me->id);
2878                         }
2879
2880                         mv = me->mvert;
2881                         dv = me->dvert;
2882
2883                         for (i = 0; i < me->totvert; i++, mv++, dv++) {
2884                                 if (mv->flag & SELECT) {
2885                                         MDeformWeight *dw;
2886                                         dw = defvert_verify_index(dv, def_nr);
2887                                         if (dw) {
2888                                                 dw->weight = weight;
2889                                         }
2890                                 }
2891                         }
2892                 }
2893         }
2894         else if (ob->type == OB_LATTICE) {
2895                 Lattice *lt = vgroup_edit_lattice(ob);
2896                 MDeformVert *dv;
2897                 BPoint *bp;
2898                 int a, tot;
2899
2900                 if (lt->dvert == NULL)
2901                         ED_vgroup_data_create(&lt->id);
2902