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