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