1be09847ef266fa6ccddf99aa0a3b0ac1f537e73
[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 with weight changes (see dm_deform_recalc)
1194 static void dm_deform_clear(DerivedMesh *dm, Object *ob)
1195 {
1196         if (ob->derivedDeform && (ob->derivedDeform) == dm) {
1197                 ob->derivedDeform->needsFree = 1;
1198                 ob->derivedDeform->release(ob->derivedDeform);
1199                 ob->derivedDeform = NULL;
1200         }
1201         else if (dm) {
1202                 dm->needsFree = 1;
1203                 dm->release(dm);
1204         }
1205 }
1206
1207 /* recalculate the deformation */
1208 static DerivedMesh *dm_deform_recalc(Scene *scene, Object *ob)
1209 {
1210         return mesh_get_derived_deform(scene, ob, CD_MASK_BAREMESH);
1211 }
1212
1213 /* by changing nonzero weights, try to move a vertex in me->mverts with index 'index' to
1214  * distToBe distance away from the provided plane strength can change distToBe so that it moves
1215  * towards distToBe by that percentage cp changes how much the weights are adjusted
1216  * to check the distance
1217  *
1218  * index is the index of the vertex being moved
1219  * norm and d are the plane's properties for the equation: ax + by + cz + d = 0
1220  * coord is a point on the plane
1221  */
1222 static void moveCloserToDistanceFromPlane(Scene *scene, Object *ob, Mesh *me, int index, float norm[3],
1223                                           float coord[3], float d, float distToBe, float strength, float cp)
1224 {
1225         DerivedMesh *dm;
1226         MDeformWeight *dw;
1227         MVert m;
1228         MDeformVert *dvert = me->dvert + index;
1229         int totweight = dvert->totweight;
1230         float oldw = 0;
1231         float oldPos[3] = {0};
1232         float vc, hc, dist = 0.0f;
1233         int i, k;
1234         float (*changes)[2] = MEM_mallocN(sizeof(float *) * totweight * 2, "vertHorzChange");
1235         float *dists = MEM_mallocN(sizeof(float) * totweight, "distance");
1236
1237         /* track if up or down moved it closer for each bone */
1238         int *upDown = MEM_callocN(sizeof(int) * totweight, "upDownTracker");
1239
1240         int *dwIndices = MEM_callocN(sizeof(int) * totweight, "dwIndexTracker");
1241         float distToStart;
1242         int bestIndex = 0;
1243         char wasChange;
1244         char wasUp;
1245         int lastIndex = -1;
1246         float originalDistToBe = distToBe;
1247         do {
1248                 wasChange = FALSE;
1249                 dm = dm_deform_recalc(scene, ob);
1250                 dm->getVert(dm, index, &m);
1251                 copy_v3_v3(oldPos, m.co);
1252                 distToStart = dot_v3v3(norm, oldPos) + d;
1253
1254                 if (distToBe == originalDistToBe) {
1255                         distToBe += distToStart - distToStart * strength;
1256                 }
1257                 for (i = 0; i < totweight; i++) {
1258                         dwIndices[i] = i;
1259                         dw = (dvert->dw + i);
1260                         vc = hc = 0;
1261                         if (!dw->weight) {
1262                                 changes[i][0] = 0;
1263                                 changes[i][1] = 0;
1264                                 dists[i] = distToStart;
1265                                 continue;
1266                         }
1267                         for (k = 0; k < 2; k++) {
1268                                 if (dm) {
1269                                         dm_deform_clear(dm, ob); dm = NULL;
1270                                 }
1271                                 oldw = dw->weight;
1272                                 if (k) {
1273                                         dw->weight *= 1 + cp;
1274                                 }
1275                                 else {
1276                                         dw->weight /= 1 + cp;
1277                                 }
1278                                 if (dw->weight == oldw) {
1279                                         changes[i][0] = 0;
1280                                         changes[i][1] = 0;
1281                                         dists[i] = distToStart;
1282                                         break;
1283                                 }
1284                                 if (dw->weight > 1) {
1285                                         dw->weight = 1;
1286                                 }
1287                                 dm = dm_deform_recalc(scene, ob);
1288                                 dm->getVert(dm, index, &m);
1289                                 getVerticalAndHorizontalChange(norm, d, coord, oldPos, distToStart, m.co, changes, dists, i);
1290                                 dw->weight = oldw;
1291                                 if (!k) {
1292                                         vc = changes[i][0];
1293                                         hc = changes[i][1];
1294                                         dist = dists[i];
1295                                 }
1296                                 else {
1297                                         if (fabsf(dist - distToBe) < fabsf(dists[i] - distToBe)) {
1298                                                 upDown[i] = 0;
1299                                                 changes[i][0] = vc;
1300                                                 changes[i][1] = hc;
1301                                                 dists[i] = dist;
1302                                         }
1303                                         else {
1304                                                 upDown[i] = 1;
1305                                         }
1306                                         if (fabsf(dists[i] - distToBe) > fabsf(distToStart - distToBe)) {
1307                                                 changes[i][0] = 0;
1308                                                 changes[i][1] = 0;
1309                                                 dists[i] = distToStart;
1310                                         }
1311                                 }
1312                         }
1313                 }
1314                 // sort the changes by the vertical change
1315                 for (k = 0; k < totweight; k++) {
1316                         float tf;
1317                         int ti;
1318                         bestIndex = k;
1319                         for (i = k + 1; i < totweight; i++) {
1320                                 dist = dists[i];
1321
1322                                 if (fabsf(dist) > fabsf(dists[i])) {
1323                                         bestIndex = i;
1324                                 }
1325                         }
1326                         // switch with k
1327                         if (bestIndex != k) {
1328                                 ti = upDown[k];
1329                                 upDown[k] = upDown[bestIndex];
1330                                 upDown[bestIndex] = ti;
1331
1332                                 ti = dwIndices[k];
1333                                 dwIndices[k] = dwIndices[bestIndex];
1334                                 dwIndices[bestIndex] = ti;
1335
1336                                 tf = changes[k][0];
1337                                 changes[k][0] = changes[bestIndex][0];
1338                                 changes[bestIndex][0] = tf;
1339
1340                                 tf = changes[k][1];
1341                                 changes[k][1] = changes[bestIndex][1];
1342                                 changes[bestIndex][1] = tf;
1343
1344                                 tf = dists[k];
1345                                 dists[k] = dists[bestIndex];
1346                                 dists[bestIndex] = tf;
1347                         }
1348                 }
1349                 bestIndex = -1;
1350                 /* find the best change with an acceptable horizontal change */
1351                 for (i = 0; i < totweight; i++) {
1352                         if (fabsf(changes[i][0]) > fabsf(changes[i][1] * 2.0f)) {
1353                                 bestIndex = i;
1354                                 break;
1355                         }
1356                 }
1357                 if (bestIndex != -1) {
1358                         wasChange = TRUE;
1359                         /* it is a good place to stop if it tries to move the opposite direction
1360                          * (relative to the plane) of last time */
1361                         if (lastIndex != -1) {
1362                                 if (wasUp != upDown[bestIndex]) {
1363                                         wasChange = FALSE;
1364                                 }
1365                         }
1366                         lastIndex = bestIndex;
1367                         wasUp = upDown[bestIndex];
1368                         dw = (dvert->dw + dwIndices[bestIndex]);
1369                         oldw = dw->weight;
1370                         if (upDown[bestIndex]) {
1371                                 dw->weight *= 1 + cp;
1372                         }
1373                         else {
1374                                 dw->weight /= 1 + cp;
1375                         }
1376                         if (dw->weight > 1) {
1377                                 dw->weight = 1;
1378                         }
1379                         if (oldw == dw->weight) {
1380                                 wasChange = FALSE;
1381                         }
1382                         if (dm) {
1383                                 dm_deform_clear(dm, ob); dm = NULL;
1384                         }
1385                 }
1386         } while (wasChange && ((distToStart - distToBe) / fabsf(distToStart - distToBe) ==
1387                                (dists[bestIndex] - distToBe) / fabsf(dists[bestIndex] - distToBe)));
1388
1389         MEM_freeN(upDown);
1390         MEM_freeN(changes);
1391         MEM_freeN(dists);
1392         MEM_freeN(dwIndices);
1393 }
1394
1395 /* this is used to try to smooth a surface by only adjusting the nonzero weights of a vertex 
1396  * but it could be used to raise or lower an existing 'bump.' */
1397 static void vgroup_fix(Scene *scene, Object *ob, float distToBe, float strength, float cp)
1398 {
1399         int i;
1400
1401         Mesh *me = ob->data;
1402         MVert *mvert = me->mvert;
1403         int *verts = NULL;
1404         if (!(me->editflag & ME_EDIT_VERT_SEL))
1405                 return;
1406         for (i = 0; i < me->totvert && mvert; i++, mvert++) {
1407                 if (mvert->flag & SELECT) {
1408                         int count = 0;
1409                         if ((verts = getSurroundingVerts(me, i, &count))) {
1410                                 MVert m;
1411                                 MVert *p = MEM_callocN(sizeof(MVert) * (count), "deformedPoints");
1412                                 int k;
1413
1414                                 DerivedMesh *dm = mesh_get_derived_deform(scene, ob, CD_MASK_BAREMESH);
1415                                 k = count;
1416                                 while (k--) {
1417                                         dm->getVert(dm, verts[k], &m);
1418                                         p[k] = m;
1419                                 }
1420                                 
1421                                 if (count >= 3) {
1422                                         float d /*, dist */ /* UNUSED */, mag;
1423                                         float coord[3];
1424                                         float norm[3];
1425                                         getSingleCoordinate(p, count, coord);
1426                                         dm->getVert(dm, i, &m);
1427                                         sub_v3_v3v3(norm, m.co, coord);
1428                                         mag = normalize_v3(norm);
1429                                         if (mag) { /* zeros fix */
1430                                                 d = -dot_v3v3(norm, coord);
1431                                                 /* dist = (dot_v3v3(norm, m.co) + d); */ /* UNUSED */
1432                                                 moveCloserToDistanceFromPlane(scene, ob, me, i, norm, coord, d, distToBe, strength, cp);
1433                                         }
1434                                 }
1435
1436                                 MEM_freeN(verts);
1437                                 MEM_freeN(p);
1438                         }
1439                 }
1440         }
1441 }
1442
1443 static void vgroup_levels(Object *ob, float offset, float gain)
1444 {
1445         MDeformWeight *dw;
1446         MDeformVert *dv, **dvert_array = NULL;
1447         int i, dvert_tot = 0;
1448         const int def_nr = ob->actdef - 1;
1449
1450         const int use_vert_sel = vertex_group_use_vert_sel(ob);
1451
1452         if (!BLI_findlink(&ob->defbase, def_nr)) {
1453                 return;
1454         }
1455
1456         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1457
1458         if (dvert_array) {
1459                 for (i = 0; i < dvert_tot; i++) {
1460
1461                         /* in case its not selected */
1462                         if (!(dv = dvert_array[i])) {
1463                                 continue;
1464                         }
1465
1466                         dw = defvert_find_index(dv, def_nr);
1467                         if (dw) {
1468                                 dw->weight = gain * (dw->weight + offset);
1469
1470                                 CLAMP(dw->weight, 0.0f, 1.0f);
1471                         }
1472                 }
1473
1474                 MEM_freeN(dvert_array);
1475         }
1476 }
1477
1478 static void vgroup_normalize_all(Object *ob, int lock_active)
1479 {
1480         MDeformVert *dv, **dvert_array = NULL;
1481         int i, dvert_tot = 0;
1482         const int def_nr = ob->actdef - 1;
1483
1484         const int use_vert_sel = vertex_group_use_vert_sel(ob);
1485
1486         if (lock_active && !BLI_findlink(&ob->defbase, def_nr)) {
1487                 return;
1488         }
1489
1490         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1491
1492         if (dvert_array) {
1493                 const int defbase_tot = BLI_countlist(&ob->defbase);
1494                 char *lock_flags = BKE_objdef_lock_flags_get(ob, defbase_tot);
1495
1496                 if ((lock_active == TRUE) &&
1497                     (lock_flags != NULL) &&
1498                     (def_nr < defbase_tot))
1499                 {
1500                         lock_flags[def_nr] = TRUE;
1501                 }
1502
1503                 for (i = 0; i < dvert_tot; i++) {
1504                         /* in case its not selected */
1505                         if ((dv = dvert_array[i])) {
1506                                 if (lock_flags) {
1507                                         defvert_normalize_lock_map(dv, lock_flags, defbase_tot);
1508                                 }
1509                                 else if (lock_active) {
1510                                         defvert_normalize_lock_single(dv, def_nr);
1511                                 }
1512                                 else {
1513                                         defvert_normalize(dv);
1514                                 }
1515                         }
1516                 }
1517
1518                 if (lock_flags) {
1519                         MEM_freeN(lock_flags);
1520                 }
1521
1522                 MEM_freeN(dvert_array);
1523         }
1524 }
1525
1526
1527 static void vgroup_lock_all(Object *ob, int action)
1528 {
1529         bDeformGroup *dg;
1530
1531         if (action == SEL_TOGGLE) {
1532                 action = SEL_SELECT;
1533                 for (dg = ob->defbase.first; dg; dg = dg->next) {
1534                         if (dg->flag & DG_LOCK_WEIGHT) {
1535                                 action = SEL_DESELECT;
1536                                 break;
1537                         }
1538                 }
1539         }
1540
1541         for (dg = ob->defbase.first; dg; dg = dg->next) {
1542                 switch (action) {
1543                         case SEL_SELECT:
1544                                 dg->flag |= DG_LOCK_WEIGHT;
1545                                 break;
1546                         case SEL_DESELECT:
1547                                 dg->flag &= ~DG_LOCK_WEIGHT;
1548                                 break;
1549                         case SEL_INVERT:
1550                                 dg->flag ^= DG_LOCK_WEIGHT;
1551                                 break;
1552                 }
1553         }
1554 }
1555
1556 static void vgroup_invert(Object *ob, const short auto_assign, const short auto_remove)
1557 {
1558         MDeformWeight *dw;
1559         MDeformVert *dv, **dvert_array = NULL;
1560         int i, dvert_tot = 0;
1561         const int def_nr = ob->actdef - 1;
1562         const int use_vert_sel = vertex_group_use_vert_sel(ob);
1563
1564         if (!BLI_findlink(&ob->defbase, def_nr)) {
1565                 return;
1566         }
1567
1568         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1569
1570         if (dvert_array) {
1571                 for (i = 0; i < dvert_tot; i++) {
1572
1573                         /* in case its not selected */
1574                         if (!(dv = dvert_array[i])) {
1575                                 continue;
1576                         }
1577
1578                         if (auto_assign) {
1579                                 dw = defvert_verify_index(dv, def_nr);
1580                         }
1581                         else {
1582                                 dw = defvert_find_index(dv, def_nr);
1583                         }
1584
1585                         if (dw) {
1586                                 dw->weight = 1.0f - dw->weight;
1587
1588                                 if (auto_remove && dw->weight <= 0.0f) {
1589                                         defvert_remove_group(dv, dw);
1590                                 }
1591                         }
1592                 }
1593
1594                 MEM_freeN(dvert_array);
1595         }
1596 }
1597
1598 static void vgroup_blend(Object *ob, const float fac)
1599 {
1600         MDeformVert *dv;
1601         MDeformWeight *dw;
1602         int i, dvert_tot = 0;
1603         const int def_nr = ob->actdef - 1;
1604
1605         BLI_assert(fac >= 0.0f && fac <= 1.0f);
1606
1607         if (ob->type != OB_MESH) {
1608                 return;
1609         }
1610
1611         if (BLI_findlink(&ob->defbase, def_nr)) {
1612                 const float ifac = 1.0f - fac;
1613
1614                 BMEditMesh *em = BMEdit_FromObject(ob);
1615                 BMesh *bm = em ? em->bm : NULL;
1616                 Mesh  *me = em ? NULL   : ob->data;
1617
1618                 /* bmesh only*/
1619                 BMEdge *eed;
1620                 BMVert *eve;
1621                 BMIter iter;
1622
1623                 /* mesh only */
1624                 MDeformVert *dvert_array = NULL;
1625
1626
1627                 float *vg_weights;
1628                 float *vg_users;
1629                 int sel1, sel2;
1630
1631                 if (bm) {
1632                         BM_mesh_elem_index_ensure(bm, BM_VERT);
1633                         dvert_tot = bm->totvert;
1634                 }
1635                 else {
1636                         dvert_tot = me->totvert;
1637                         dvert_array = me->dvert;
1638                 }
1639
1640                 vg_weights = MEM_callocN(sizeof(float) * dvert_tot, "vgroup_blend_f");
1641                 vg_users = MEM_callocN(sizeof(int) * dvert_tot, "vgroup_blend_i");
1642
1643                 if (bm) {
1644                         BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
1645                                 sel1 = BM_elem_flag_test(eed->v1, BM_ELEM_SELECT);
1646                                 sel2 = BM_elem_flag_test(eed->v2, BM_ELEM_SELECT);
1647
1648                                 if (sel1 != sel2) {
1649                                         int i1 /* , i2 */;
1650                                         /* i1 is always the selected one */
1651                                         if (sel1) {
1652                                                 i1 = BM_elem_index_get(eed->v1);
1653                                                 /* i2= BM_elem_index_get(eed->v2); */ /* UNUSED */
1654                                                 eve = eed->v2;
1655                                         }
1656                                         else {
1657                                                 /* i2= BM_elem_index_get(eed->v1); */ /* UNUSED */
1658                                                 i1 = BM_elem_index_get(eed->v2);
1659                                                 eve = eed->v1;
1660                                         }
1661
1662                                         dv = CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_MDEFORMVERT);
1663                                         dw = defvert_find_index(dv, def_nr);
1664                                         if (dw) {
1665                                                 vg_weights[i1] += dw->weight;
1666                                         }
1667                                         vg_users[i1]++;
1668                                 }
1669                         }
1670
1671                         BM_ITER_MESH_INDEX (eve, &iter, bm, BM_VERTS_OF_MESH, i) {
1672                                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT) && vg_users[i] > 0) {
1673                                         dv = CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_MDEFORMVERT);
1674
1675                                         dw = defvert_verify_index(dv, def_nr);
1676                                         dw->weight = (fac * (vg_weights[i] / (float)vg_users[i])) + (ifac * dw->weight);
1677                                         /* in case of division errors */
1678                                         CLAMP(dw->weight, 0.0f, 1.0f);
1679                                 }
1680                         }
1681                 }
1682                 else {
1683                         MEdge *ed = me->medge;
1684                         MVert *mv;
1685
1686                         for (i = 0; i < me->totedge; i++, ed++) {
1687                                 sel1 = me->mvert[ed->v1].flag & SELECT;
1688                                 sel2 = me->mvert[ed->v2].flag & SELECT;
1689
1690                                 if (sel1 != sel2) {
1691                                         int i1, i2;
1692                                         /* i1 is always the selected one */
1693                                         if (sel1) {
1694                                                 i1 = ed->v1;
1695                                                 i2 = ed->v2;
1696                                         }
1697                                         else {
1698                                                 i2 = ed->v1;
1699                                                 i1 = ed->v2;
1700                                         }
1701
1702                                         dv = &dvert_array[i2];
1703                                         dw = defvert_find_index(dv, def_nr);
1704                                         if (dw) {
1705                                                 vg_weights[i1] += dw->weight;
1706                                         }
1707                                         vg_users[i1]++;
1708                                 }
1709                         }
1710
1711                         mv = me->mvert;
1712                         dv = dvert_array;
1713
1714                         for (i = 0; i < dvert_tot; i++, mv++, dv++) {
1715                                 if ((mv->flag & SELECT) && (vg_users[i] > 0)) {
1716                                         dw = defvert_verify_index(dv, def_nr);
1717                                         dw->weight = (fac * (vg_weights[i] / (float)vg_users[i])) + (ifac * dw->weight);
1718
1719                                         /* in case of division errors */
1720                                         CLAMP(dw->weight, 0.0f, 1.0f);
1721                                 }
1722                         }
1723                 }
1724
1725                 MEM_freeN(vg_weights);
1726                 MEM_freeN(vg_users);
1727         }
1728 }
1729
1730 static int inv_cmp_mdef_vert_weights(const void *a1, const void *a2)
1731 {
1732         /* qsort sorts in ascending order.  We want descending order to save a memcopy
1733          * so this compare function is inverted from the standard greater than comparison qsort needs.
1734          * A normal compare function is called with two pointer arguments and should return an integer less than, equal to,
1735          * or greater than zero corresponding to whether its first argument is considered less than, equal to,
1736          * or greater than its second argument.  This does the opposite. */
1737         const struct MDeformWeight *dw1 = a1, *dw2 = a2;
1738
1739         if      (dw1->weight < dw2->weight) return  1;
1740         else if (dw1->weight > dw2->weight) return -1;
1741         else if (&dw1 < &dw2)               return  1; /* compare addresses so we have a stable sort algorithm */
1742         else                                return -1;
1743 }
1744
1745 /* Used for limiting the number of influencing bones per vertex when exporting
1746  * skinned meshes.  if all_deform_weights is True, limit all deform modifiers
1747  * to max_weights regardless of type, otherwise, only limit the number of influencing bones per vertex*/
1748 static int vertex_group_limit_total(Object *ob,
1749                                     const int max_weights,
1750                                     const int all_deform_weights)
1751 {
1752         MDeformVert *dv, **dvert_array = NULL;
1753         int i, dvert_tot = 0;
1754         const int use_vert_sel = vertex_group_use_vert_sel(ob);
1755         int is_change = FALSE;
1756
1757         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1758
1759         if (dvert_array) {
1760                 int defbase_tot = BLI_countlist(&ob->defbase);
1761                 const char *vgroup_validmap = (all_deform_weights == FALSE) ?
1762                             BKE_objdef_validmap_get(ob, defbase_tot) :
1763                             NULL;
1764                 int num_to_drop = 0;
1765
1766                 /* only the active group */
1767                 for (i = 0; i < dvert_tot; i++) {
1768
1769                         /* in case its not selected */
1770                         if (!(dv = dvert_array[i])) {
1771                                 continue;
1772                         }
1773
1774                         if (all_deform_weights) {
1775                                 /* keep only the largest weights, discarding the rest
1776                                  * qsort will put array in descending order because of  invCompare function */
1777                                 num_to_drop = dv->totweight - max_weights;
1778                                 if (num_to_drop > 0) {
1779                                         qsort(dv->dw, dv->totweight, sizeof(MDeformWeight), inv_cmp_mdef_vert_weights);
1780                                         dv->dw = MEM_reallocN(dv->dw, sizeof(MDeformWeight) * max_weights);
1781                                         dv->totweight = max_weights;
1782                                         is_change = TRUE;
1783                                 }
1784                         }
1785                         else {
1786                                 MDeformWeight *dw_temp;
1787                                 int bone_count = 0, non_bone_count = 0;
1788                                 int j;
1789                                 /* only consider vgroups with bone modifiers attached (in vgroup_validmap) */
1790
1791                                 num_to_drop = dv->totweight - max_weights;
1792
1793                                 /* first check if we even need to test further */
1794                                 if (num_to_drop > 0) {
1795                                         /* re-pack dw array so that non-bone weights are first, bone-weighted verts at end
1796                                          * sort the tail, then copy only the truncated array back to dv->dw */
1797                                         dw_temp = MEM_mallocN(sizeof(MDeformWeight) * (dv->totweight), __func__);
1798                                         bone_count = 0; non_bone_count = 0;
1799                                         for (j = 0; j < dv->totweight; j++) {
1800                                                 BLI_assert(dv->dw[j].def_nr < defbase_tot);
1801                                                 if (!vgroup_validmap[(dv->dw[j]).def_nr]) {
1802                                                         dw_temp[non_bone_count] = dv->dw[j];
1803                                                         non_bone_count += 1;
1804                                                 }
1805                                                 else {
1806                                                         dw_temp[dv->totweight - 1 - bone_count] = dv->dw[j];
1807                                                         bone_count += 1;
1808                                                 }
1809                                         }
1810                                         BLI_assert(bone_count + non_bone_count == dv->totweight);
1811                                         num_to_drop = bone_count - max_weights;
1812                                         if (num_to_drop > 0) {
1813                                                 qsort(&dw_temp[non_bone_count], bone_count, sizeof(MDeformWeight), inv_cmp_mdef_vert_weights);
1814                                                 dv->totweight -= num_to_drop;
1815                                                 /* Do we want to clean/normalize here? */
1816                                                 MEM_freeN(dv->dw);
1817                                                 dv->dw = MEM_reallocN(dw_temp, sizeof(MDeformWeight) * dv->totweight);
1818                                                 is_change = TRUE;
1819                                         }
1820                                         else {
1821                                                 MEM_freeN(dw_temp);
1822                                         }
1823                                 }
1824                         }
1825                 }
1826                 MEM_freeN(dvert_array);
1827
1828                 if (vgroup_validmap) {
1829                         MEM_freeN((void *)vgroup_validmap);
1830                 }
1831         }
1832
1833         return is_change;
1834 }
1835
1836 static void vgroup_clean(Object *ob, const float epsilon, int keep_single)
1837 {
1838         MDeformWeight *dw;
1839         MDeformVert *dv, **dvert_array = NULL;
1840         int i, dvert_tot = 0;
1841         const int def_nr = ob->actdef - 1;
1842         const int use_vert_sel = vertex_group_use_vert_sel(ob);
1843
1844         if (!BLI_findlink(&ob->defbase, def_nr)) {
1845                 return;
1846         }
1847
1848         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1849
1850         if (dvert_array) {
1851                 /* only the active group */
1852                 for (i = 0; i < dvert_tot; i++) {
1853
1854                         /* in case its not selected */
1855                         if (!(dv = dvert_array[i])) {
1856                                 continue;
1857                         }
1858
1859                         dw = defvert_find_index(dv, def_nr);
1860
1861                         if (dw) {
1862                                 if (dw->weight <= epsilon) {
1863                                         if (keep_single == FALSE || dv->totweight > 1) {
1864                                                 defvert_remove_group(dv, dw); /* dw can be NULL */
1865                                         }
1866                                 }
1867                         }
1868                 }
1869
1870                 MEM_freeN(dvert_array);
1871         }
1872 }
1873
1874 static void vgroup_clean_all(Object *ob, const float epsilon, const int keep_single)
1875 {
1876         MDeformVert **dvert_array = NULL;
1877         int i, dvert_tot = 0;
1878         const int use_vert_sel = vertex_group_use_vert_sel(ob);
1879
1880         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1881
1882         if (dvert_array) {
1883                 MDeformVert *dv;
1884                 MDeformWeight *dw;
1885
1886                 for (i = 0; i < dvert_tot; i++) {
1887                         int j;
1888
1889                         /* in case its not selected */
1890                         if (!(dv = dvert_array[i])) {
1891                                 continue;
1892                         }
1893
1894                         j = dv->totweight;
1895
1896                         while (j--) {
1897
1898                                 if (keep_single && dv->totweight == 1)
1899                                         break;
1900
1901                                 dw = dv->dw + j;
1902
1903                                 if (dw->weight <= epsilon) {
1904                                         defvert_remove_group(dv, dw);
1905                                 }
1906                         }
1907                 }
1908
1909                 MEM_freeN(dvert_array);
1910         }
1911 }
1912
1913
1914 static void dvert_mirror_op(MDeformVert *dvert, MDeformVert *dvert_mirr,
1915                             const char sel, const char sel_mirr,
1916                             const int *flip_map, const int flip_map_len,
1917                             const short mirror_weights, const short flip_vgroups,
1918                             const short all_vgroups, const int act_vgroup)
1919 {
1920         BLI_assert(sel || sel_mirr);
1921
1922         if (sel_mirr && sel) {
1923                 /* swap */
1924                 if (mirror_weights) {
1925                         if (all_vgroups) {
1926                                 SWAP(MDeformVert, *dvert, *dvert_mirr);
1927                         }
1928                         else {
1929                                 MDeformWeight *dw =      defvert_find_index(dvert, act_vgroup);
1930                                 MDeformWeight *dw_mirr = defvert_find_index(dvert_mirr, act_vgroup);
1931
1932                                 if (dw || dw_mirr) {
1933                                         if (dw_mirr == NULL)
1934                                                 dw_mirr = defvert_verify_index(dvert_mirr, act_vgroup);
1935                                         if (dw == NULL)
1936                                                 dw = defvert_verify_index(dvert, act_vgroup);
1937
1938                                         SWAP(float, dw->weight, dw_mirr->weight);
1939                                 }
1940                         }
1941                 }
1942
1943                 if (flip_vgroups) {
1944                         defvert_flip(dvert, flip_map, flip_map_len);
1945                         defvert_flip(dvert_mirr, flip_map, flip_map_len);
1946                 }
1947         }
1948         else {
1949                 /* dvert should always be the target, only swaps pointer */
1950                 if (sel_mirr) {
1951                         SWAP(MDeformVert *, dvert, dvert_mirr);
1952                 }
1953
1954                 if (mirror_weights) {
1955                         if (all_vgroups) {
1956                                 defvert_copy(dvert, dvert_mirr);
1957                         }
1958                         else {
1959                                 defvert_copy_index(dvert, dvert_mirr, act_vgroup);
1960                         }
1961                 }
1962
1963                 /* flip map already modified for 'all_vgroups' */
1964                 if (flip_vgroups) {
1965                         defvert_flip(dvert, flip_map, flip_map_len);
1966                 }
1967         }
1968 }
1969
1970 /* TODO, vgroup locking */
1971 /* TODO, face masking */
1972 void ED_vgroup_mirror(Object *ob, const short mirror_weights, const short flip_vgroups, const short all_vgroups)
1973 {
1974
1975 #define VGROUP_MIRR_OP                                                        \
1976         dvert_mirror_op(dvert, dvert_mirr,                                    \
1977                         sel, sel_mirr,                                        \
1978                         flip_map, flip_map_len,                               \
1979                         mirror_weights, flip_vgroups,                         \
1980                         all_vgroups, def_nr                                   \
1981                         )
1982
1983         BMVert *eve, *eve_mirr;
1984         MDeformVert *dvert, *dvert_mirr;
1985         short sel, sel_mirr;
1986         int *flip_map, flip_map_len;
1987         const int def_nr = ob->actdef - 1;
1988
1989         if ((mirror_weights == 0 && flip_vgroups == 0) ||
1990             (BLI_findlink(&ob->defbase, def_nr) == NULL))
1991         {
1992                 return;
1993         }
1994
1995         if (flip_vgroups) {
1996                 flip_map = all_vgroups ?
1997                            defgroup_flip_map(ob, &flip_map_len, FALSE) :
1998                            defgroup_flip_map_single(ob, &flip_map_len, FALSE, def_nr);
1999
2000                 BLI_assert(flip_map != NULL);
2001
2002                 if (flip_map == NULL) {
2003                         /* something went wrong!, possibly no groups */
2004                         return;
2005                 }
2006         }
2007         else {
2008                 flip_map = NULL;
2009                 flip_map_len = 0;
2010         }
2011
2012         /* only the active group */
2013         if (ob->type == OB_MESH) {
2014                 Mesh *me = ob->data;
2015                 BMEditMesh *em = me->edit_btmesh;
2016
2017                 if (em) {
2018                         BMIter iter;
2019
2020                         if (!CustomData_has_layer(&em->bm->vdata, CD_MDEFORMVERT)) {
2021                                 goto cleanup;
2022                         }
2023
2024                         EDBM_verts_mirror_cache_begin(em, FALSE);
2025
2026                         /* Go through the list of editverts and assign them */
2027                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2028                                 if ((eve_mirr = EDBM_verts_mirror_get(em, eve))) {
2029                                         sel = BM_elem_flag_test(eve, BM_ELEM_SELECT);
2030                                         sel_mirr = BM_elem_flag_test(eve_mirr, BM_ELEM_SELECT);
2031
2032                                         if ((sel || sel_mirr) && (eve != eve_mirr)) {
2033                                                 dvert = CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_MDEFORMVERT);
2034                                                 dvert_mirr = CustomData_bmesh_get(&em->bm->vdata, eve_mirr->head.data, CD_MDEFORMVERT);
2035                                                 if (dvert && dvert_mirr) {
2036                                                         VGROUP_MIRR_OP;
2037                                                 }
2038                                         }
2039
2040                                         /* don't use these again */
2041                                         EDBM_verts_mirror_cache_clear(em, eve);
2042                                         EDBM_verts_mirror_cache_clear(em, eve_mirr);
2043                                 }
2044                         }
2045                         EDBM_verts_mirror_cache_end(em);
2046                 }
2047                 else {
2048                         /* object mode / weight paint */
2049                         MVert *mv, *mv_mirr;
2050                         int vidx, vidx_mirr;
2051                         const int use_vert_sel = (me->editflag & ME_EDIT_VERT_SEL) != 0;
2052
2053                         if (me->dvert == NULL) {
2054                                 goto cleanup;
2055                         }
2056
2057                         if (!use_vert_sel) {
2058                                 sel = sel_mirr = TRUE;
2059                         }
2060
2061                         /* tag verts we have used */
2062                         for (vidx = 0, mv = me->mvert; vidx < me->totvert; vidx++, mv++) {
2063                                 mv->flag &= ~ME_VERT_TMP_TAG;
2064                         }
2065
2066                         for (vidx = 0, mv = me->mvert; vidx < me->totvert; vidx++, mv++) {
2067                                 if (    ((mv->flag & ME_VERT_TMP_TAG) == 0) &&
2068                                         ((vidx_mirr = mesh_get_x_mirror_vert(ob, vidx)) != -1) &&
2069                                         (vidx != vidx_mirr) &&
2070                                         ((((mv_mirr = me->mvert + vidx_mirr)->flag) & ME_VERT_TMP_TAG) == 0))
2071                                 {
2072
2073                                         if (use_vert_sel) {
2074                                                 sel = mv->flag & SELECT;
2075                                                 sel_mirr = mv_mirr->flag & SELECT;
2076                                         }
2077
2078                                         if (sel || sel_mirr) {
2079                                                 dvert = &me->dvert[vidx];
2080                                                 dvert_mirr = &me->dvert[vidx_mirr];
2081
2082                                                 VGROUP_MIRR_OP;
2083                                         }
2084
2085                                         mv->flag |= ME_VERT_TMP_TAG;
2086                                         mv_mirr->flag |= ME_VERT_TMP_TAG;
2087                                 }
2088                         }
2089                 }
2090         }
2091         else if (ob->type == OB_LATTICE) {
2092                 Lattice *lt = vgroup_edit_lattice(ob);
2093                 int i1, i2;
2094                 int u, v, w;
2095                 int pntsu_half;
2096                 /* half but found up odd value */
2097
2098                 if (lt->pntsu == 1 || lt->dvert == NULL) {
2099                         goto cleanup;
2100                 }
2101
2102                 /* unlike editmesh we know that by only looping over the first half of
2103                  * the 'u' indices it will cover all points except the middle which is
2104                  * ok in this case */
2105                 pntsu_half = lt->pntsu / 2;
2106
2107                 for (w = 0; w < lt->pntsw; w++) {
2108                         for (v = 0; v < lt->pntsv; v++) {
2109                                 for (u = 0; u < pntsu_half; u++) {
2110                                         int u_inv = (lt->pntsu - 1) - u;
2111                                         if (u != u_inv) {
2112                                                 BPoint *bp, *bp_mirr;
2113
2114                                                 i1 = LT_INDEX(lt, u, v, w);
2115                                                 i2 = LT_INDEX(lt, u_inv, v, w);
2116
2117                                                 bp = &lt->def[i1];
2118                                                 bp_mirr = &lt->def[i2];
2119
2120                                                 sel = bp->f1 & SELECT;
2121                                                 sel_mirr = bp_mirr->f1 & SELECT;
2122
2123                                                 if (sel || sel_mirr) {
2124                                                         dvert = &lt->dvert[i1];
2125                                                         dvert_mirr = &lt->dvert[i2];
2126
2127                                                         VGROUP_MIRR_OP;
2128                                                 }
2129                                         }
2130                                 }
2131                         }
2132                 }
2133         }
2134
2135         /* flip active group index */
2136         if (flip_vgroups && flip_map[def_nr] >= 0)
2137                 ob->actdef = flip_map[def_nr] + 1;
2138
2139 cleanup:
2140         if (flip_map) MEM_freeN(flip_map);
2141
2142 #undef VGROUP_MIRR_OP
2143
2144 }
2145
2146 static void vgroup_remap_update_users(Object *ob, int *map)
2147 {
2148         ExplodeModifierData *emd;
2149         ModifierData *md;
2150         ParticleSystem *psys;
2151         ClothModifierData *clmd;
2152         ClothSimSettings *clsim;
2153         int a;
2154
2155         /* these cases don't use names to refer to vertex groups, so when
2156          * they get deleted the numbers get out of sync, this corrects that */
2157
2158         if (ob->soft)
2159                 ob->soft->vertgroup = map[ob->soft->vertgroup];
2160
2161         for (md = ob->modifiers.first; md; md = md->next) {
2162                 if (md->type == eModifierType_Explode) {
2163                         emd = (ExplodeModifierData *)md;
2164                         emd->vgroup = map[emd->vgroup];
2165                 }
2166                 else if (md->type == eModifierType_Cloth) {
2167                         clmd = (ClothModifierData *)md;
2168                         clsim = clmd->sim_parms;
2169
2170                         if (clsim) {
2171                                 clsim->vgroup_mass = map[clsim->vgroup_mass];
2172                                 clsim->vgroup_bend = map[clsim->vgroup_bend];
2173                                 clsim->vgroup_struct = map[clsim->vgroup_struct];
2174                         }
2175                 }
2176         }
2177
2178         for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2179                 for (a = 0; a < PSYS_TOT_VG; a++)
2180                         psys->vgroup[a] = map[psys->vgroup[a]];
2181         }
2182 }
2183
2184
2185 static void vgroup_delete_update_users(Object *ob, int id)
2186 {
2187         int i, defbase_tot = BLI_countlist(&ob->defbase) + 1;
2188         int *map = MEM_mallocN(sizeof(int) * defbase_tot, "vgroup del");
2189
2190         map[id] = map[0] = 0;
2191         for (i = 1; i < id; i++) map[i] = i;
2192         for (i = id + 1; i < defbase_tot; i++) map[i] = i - 1;
2193
2194         vgroup_remap_update_users(ob, map);
2195         MEM_freeN(map);
2196 }
2197
2198
2199 static void vgroup_delete_object_mode(Object *ob, bDeformGroup *dg)
2200 {
2201         MDeformVert *dvert_array = NULL;
2202         int dvert_tot = 0;
2203         const int def_nr = BLI_findindex(&ob->defbase, dg);
2204
2205         assert(def_nr > -1);
2206
2207         ED_vgroup_give_array(ob->data, &dvert_array, &dvert_tot);
2208
2209         if (dvert_array) {
2210                 int i, j;
2211                 MDeformVert *dv;
2212                 for (i = 0, dv = dvert_array; i < dvert_tot; i++, dv++) {
2213                         MDeformWeight *dw;
2214
2215                         dw = defvert_find_index(dv, def_nr);
2216                         defvert_remove_group(dv, dw); /* dw can be NULL */
2217
2218                         /* inline, make into a function if anything else needs to do this */
2219                         for (j = 0; j < dv->totweight; j++) {
2220                                 if (dv->dw[j].def_nr > def_nr) {
2221                                         dv->dw[j].def_nr--;
2222                                 }
2223                         }
2224                         /* done */
2225                 }
2226         }
2227
2228         vgroup_delete_update_users(ob, def_nr + 1);
2229
2230         /* Remove the group */
2231         BLI_freelinkN(&ob->defbase, dg);
2232
2233         /* Update the active deform index if necessary */
2234         if (ob->actdef > def_nr)
2235                 ob->actdef--;
2236         if (ob->actdef < 1 && ob->defbase.first)
2237                 ob->actdef = 1;
2238
2239         /* remove all dverts */
2240         if (ob->defbase.first == NULL) {
2241                 if (ob->type == OB_MESH) {
2242                         Mesh *me = ob->data;
2243                         CustomData_free_layer_active(&me->vdata, CD_MDEFORMVERT, me->totvert);
2244                         me->dvert = NULL;
2245                 }
2246                 else if (ob->type == OB_LATTICE) {
2247                         Lattice *lt = ob->data;
2248                         if (lt->dvert) {
2249                                 MEM_freeN(lt->dvert);
2250                                 lt->dvert = NULL;
2251                         }
2252                 }
2253         }
2254 }
2255
2256 /* only in editmode */
2257 /* removes from active defgroup, if allverts==0 only selected vertices */
2258 static void vgroup_active_remove_verts(Object *ob, const int allverts, bDeformGroup *dg)
2259 {
2260         MDeformVert *dv;
2261         const int def_nr = BLI_findindex(&ob->defbase, dg);
2262
2263         if (ob->type == OB_MESH) {
2264                 Mesh *me = ob->data;
2265
2266                 if (me->edit_btmesh) {
2267                         BMEditMesh *em = me->edit_btmesh;
2268                         BMVert *eve;
2269                         BMIter iter;
2270
2271                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2272                                 dv = CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_MDEFORMVERT);
2273
2274                                 if (dv && dv->dw && (allverts || BM_elem_flag_test(eve, BM_ELEM_SELECT))) {
2275                                         MDeformWeight *dw = defvert_find_index(dv, def_nr);
2276                                         defvert_remove_group(dv, dw); /* dw can be NULL */
2277                                 }
2278                         }
2279                 }
2280                 else {
2281                         MVert *mv;
2282                         int i;
2283
2284                         if (!me->dvert) {
2285                                 ED_vgroup_data_create(&me->id);
2286                         }
2287
2288                         mv = me->mvert;
2289                         dv = me->dvert;
2290
2291                         for (i = 0; i < me->totvert; i++, mv++, dv++) {
2292                                 if (mv->flag & SELECT) {
2293                                         if (dv->dw && (allverts || (mv->flag & SELECT))) {
2294                                                 MDeformWeight *dw = defvert_find_index(dv, def_nr);
2295                                                 defvert_remove_group(dv, dw); /* dw can be NULL */
2296                                         }
2297                                 }
2298                         }
2299                 }
2300         }
2301         else if (ob->type == OB_LATTICE) {
2302                 Lattice *lt = vgroup_edit_lattice(ob);
2303                 
2304                 if (lt->dvert) {
2305                         BPoint *bp;
2306                         int i, tot = lt->pntsu * lt->pntsv * lt->pntsw;
2307                                 
2308                         for (i = 0, bp = lt->def; i < tot; i++, bp++) {
2309                                 if (allverts || (bp->f1 & SELECT)) {
2310                                         MDeformWeight *dw;
2311
2312                                         dv = &lt->dvert[i];
2313
2314                                         dw = defvert_find_index(dv, def_nr);
2315                                         defvert_remove_group(dv, dw); /* dw can be NULL */
2316                                 }
2317                         }
2318                 }
2319         }
2320 }
2321
2322 static void vgroup_delete_edit_mode(Object *ob, bDeformGroup *dg)
2323 {
2324         int i;
2325         const int dg_index = BLI_findindex(&ob->defbase, dg);
2326
2327         assert(dg_index > -1);
2328
2329         /* Make sure that no verts are using this group */
2330         vgroup_active_remove_verts(ob, TRUE, dg);
2331
2332         /* Make sure that any verts with higher indices are adjusted accordingly */
2333         if (ob->type == OB_MESH) {
2334                 Mesh *me = ob->data;
2335                 BMEditMesh *em = me->edit_btmesh;
2336                 BMIter iter;
2337                 BMVert *eve;
2338                 MDeformVert *dvert;
2339                 
2340                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2341                         dvert = CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_MDEFORMVERT);
2342
2343                         if (dvert)
2344                                 for (i = 0; i < dvert->totweight; i++)
2345                                         if (dvert->dw[i].def_nr > dg_index)
2346                                                 dvert->dw[i].def_nr--;
2347                 }
2348         }
2349         else if (ob->type == OB_LATTICE) {
2350                 Lattice *lt = vgroup_edit_lattice(ob);
2351                 BPoint *bp;
2352                 MDeformVert *dvert = lt->dvert;
2353                 int a, tot;
2354                 
2355                 if (dvert) {
2356                         tot = lt->pntsu * lt->pntsv * lt->pntsw;
2357                         for (a = 0, bp = lt->def; a < tot; a++, bp++, dvert++) {
2358                                 for (i = 0; i < dvert->totweight; i++) {
2359                                         if (dvert->dw[i].def_nr > dg_index)
2360                                                 dvert->dw[i].def_nr--;
2361                                 }
2362                         }
2363                 }
2364         }
2365
2366         vgroup_delete_update_users(ob, dg_index + 1);
2367
2368         /* Remove the group */
2369         BLI_freelinkN(&ob->defbase, dg);
2370
2371         /* Update the active deform index if necessary */
2372         if (ob->actdef > dg_index)
2373                 ob->actdef--;
2374         if (ob->actdef < 1 && ob->defbase.first)
2375                 ob->actdef = 1;
2376
2377         /* remove all dverts */
2378         if (ob->defbase.first == NULL) {
2379                 if (ob->type == OB_MESH) {
2380                         Mesh *me = ob->data;
2381                         CustomData_free_layer_active(&me->vdata, CD_MDEFORMVERT, me->totvert);
2382                         me->dvert = NULL;
2383                 }
2384                 else if (ob->type == OB_LATTICE) {
2385                         Lattice *lt = vgroup_edit_lattice(ob);
2386                         if (lt->dvert) {
2387                                 MEM_freeN(lt->dvert);
2388                                 lt->dvert = NULL;
2389                         }
2390                 }
2391         }
2392 }
2393
2394 static int vgroup_object_in_edit_mode(Object *ob)
2395 {
2396         if (ob->type == OB_MESH)
2397                 return (BMEdit_FromObject(ob) != NULL);
2398         else if (ob->type == OB_LATTICE)
2399                 return (((Lattice *)ob->data)->editlatt != NULL);
2400         
2401         return 0;
2402 }
2403
2404 static int vgroup_object_in_wpaint_vert_select(Object *ob)
2405 {
2406         if (ob->type == OB_MESH) {
2407                 Mesh *me = ob->data;
2408                 return ( (ob->mode & OB_MODE_WEIGHT_PAINT) &&
2409                          (me->edit_btmesh == NULL) &&
2410                          (ME_EDIT_PAINT_SEL_MODE(me) == SCE_SELECT_VERTEX) );
2411         }
2412
2413         return 0;
2414 }
2415
2416 static void vgroup_delete(Object *ob)
2417 {
2418         bDeformGroup *dg = BLI_findlink(&ob->defbase, ob->actdef - 1);
2419         if (!dg)
2420                 return;
2421
2422         if (vgroup_object_in_edit_mode(ob))
2423                 vgroup_delete_edit_mode(ob, dg);
2424         else
2425                 vgroup_delete_object_mode(ob, dg);
2426 }
2427
2428 static void vgroup_delete_all(Object *ob)
2429 {
2430         /* Remove all DVerts */
2431         if (ob->type == OB_MESH) {
2432                 Mesh *me = ob->data;
2433                 CustomData_free_layer_active(&me->vdata, CD_MDEFORMVERT, me->totvert);
2434                 me->dvert = NULL;
2435         }
2436         else if (ob->type == OB_LATTICE) {
2437                 Lattice *lt = vgroup_edit_lattice(ob);
2438                 if (lt->dvert) {
2439                         MEM_freeN(lt->dvert);
2440                         lt->dvert = NULL;
2441                 }
2442         }
2443         
2444         /* Remove all DefGroups */
2445         BLI_freelistN(&ob->defbase);
2446         
2447         /* Fix counters/indices */
2448         ob->actdef = 0;
2449 }
2450
2451 /* only in editmode */
2452 static void vgroup_assign_verts(Object *ob, const float weight)
2453 {
2454         const int def_nr = ob->actdef - 1;
2455
2456         if (!BLI_findlink(&ob->defbase, def_nr))
2457                 return;
2458
2459         if (ob->type == OB_MESH) {
2460                 Mesh *me = ob->data;
2461
2462                 if (me->edit_btmesh) {
2463                         BMEditMesh *em = me->edit_btmesh;
2464                         BMIter iter;
2465                         BMVert *eve;
2466
2467                         if (!CustomData_has_layer(&em->bm->vdata, CD_MDEFORMVERT))
2468                                 BM_data_layer_add(em->bm, &em->bm->vdata, CD_MDEFORMVERT);
2469
2470                         /* Go through the list of editverts and assign them */
2471                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2472                                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
2473                                         MDeformVert *dv;
2474                                         MDeformWeight *dw;
2475                                         dv = CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_MDEFORMVERT); /* can be NULL */
2476                                         dw = defvert_verify_index(dv, def_nr);
2477                                         if (dw) {
2478                                                 dw->weight = weight;
2479                                         }
2480                                 }
2481                         }
2482                 }
2483                 else {
2484                         MVert *mv;
2485                         MDeformVert *dv;
2486                         int i;
2487
2488                         if (!me->dvert) {
2489                                 ED_vgroup_data_create(&me->id);
2490                         }
2491
2492                         mv = me->mvert;
2493                         dv = me->dvert;
2494
2495                         for (i = 0; i < me->totvert; i++, mv++, dv++) {
2496                                 if (mv->flag & SELECT) {
2497                                         MDeformWeight *dw;
2498                                         dw = defvert_verify_index(dv, def_nr);
2499                                         if (dw) {
2500                                                 dw->weight = weight;
2501                                         }
2502                                 }
2503                         }
2504                 }
2505         }
2506         else if (ob->type == OB_LATTICE) {
2507                 Lattice *lt = vgroup_edit_lattice(ob);
2508                 MDeformVert *dv;
2509                 BPoint *bp;
2510                 int a, tot;
2511
2512                 if (lt->dvert == NULL)
2513                         ED_vgroup_data_create(&lt->id);
2514
2515                 dv = lt->dvert;
2516
2517                 tot = lt->pntsu * lt->pntsv * lt->pntsw;
2518                 for (a = 0, bp = lt->def; a < tot; a++, bp++, dv++) {
2519                         if (bp->f1 & SELECT) {
2520                                 MDeformWeight *dw;
2521
2522                                 dw = defvert_verify_index(dv, def_nr);
2523                                 if (dw) {
2524                                         dw->weight = weight;
2525                                 }
2526                         }
2527                 }
2528         }
2529 }
2530
2531 /* only in editmode */
2532 /* removes from all defgroup, if allverts==0 only selected vertices */
2533 static void vgroup_remove_verts(Object *ob, int allverts)
2534 {
2535         /* To prevent code redundancy, we just use vgroup_active_remove_verts, but that
2536          * only operates on the active vgroup. So we iterate through all groups, by changing
2537          * active group index
2538          */
2539         bDeformGroup *dg;
2540         for (dg = ob->defbase.first; dg; dg = dg->next) {
2541                 vgroup_active_remove_verts(ob, allverts, dg);
2542         }
2543 }
2544
2545 /********************** vertex group operators *********************/
2546
2547 static int vertex_group_poll(bContext *C)
2548 {
2549         Object *ob = ED_object_context(C);
2550         ID *data = (ob) ? ob->data : NULL;
2551         return (ob && !ob->id.lib && OB_TYPE_SUPPORT_VGROUP(ob->type) && data && !data->lib);
2552 }
2553
2554 static int UNUSED_FUNCTION(vertex_group_poll_edit) (bContext * C)
2555 {
2556         Object *ob = ED_object_context(C);
2557         ID *data = (ob) ? ob->data : NULL;
2558
2559         if (!(ob && !ob->id.lib && data && !data->lib))
2560                 return 0;
2561
2562         return vgroup_object_in_edit_mode(ob);
2563 }
2564
2565 /* editmode _or_ weight paint vertex sel */
2566 static int vertex_group_poll_edit_or_wpaint_vert_select(bContext *C)
2567 {
2568         Object *ob = ED_object_context(C);
2569         ID *data = (ob) ? ob->data : NULL;
2570
2571         if (!(ob && !ob->id.lib && data && !data->lib))
2572                 return 0;
2573
2574         return (vgroup_object_in_edit_mode(ob) ||
2575                 vgroup_object_in_wpaint_vert_select(ob));
2576 }
2577
2578 static int vertex_group_add_exec(bContext *C, wmOperator *UNUSED(op))
2579 {
2580         Object *ob = ED_object_context(C);
2581
2582         ED_vgroup_add(ob);
2583         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2584         WM_event_add_notifier(C, NC_GEOM | ND_DATA, ob->data);
2585         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2586         
2587         return OPERATOR_FINISHED;
2588 }
2589
2590 void OBJECT_OT_vertex_group_add(wmOperatorType *ot)
2591 {
2592         /* identifiers */
2593         ot->name = "Add Vertex Group";
2594         ot->idname = "OBJECT_OT_vertex_group_add";
2595         ot->description = "Add a new vertex group to the active object";
2596         
2597         /* api callbacks */
2598         ot->poll = vertex_group_poll;
2599         ot->exec = vertex_group_add_exec;
2600
2601         /* flags */
2602         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2603 }
2604
2605 static int vertex_group_remove_exec(bContext *C, wmOperator *op)
2606 {
2607         Object *ob = ED_object_context(C);
2608
2609         if (RNA_boolean_get(op->ptr, "all"))
2610                 vgroup_delete_all(ob);
2611         else
2612                 vgroup_delete(ob);
2613
2614         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2615         WM_event_add_notifier(C, NC_GEOM | ND_DATA, ob->data);
2616         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2617         
2618         return OPERATOR_FINISHED;
2619 }
2620
2621 void OBJECT_OT_vertex_group_remove(wmOperatorType *ot)
2622 {
2623         /* identifiers */
2624         ot->name = "Remove Vertex Group";
2625         ot->idname = "OBJECT_OT_vertex_group_remove";
2626         ot->description = "Delete the active vertex group";
2627         
2628         /* api callbacks */
2629         ot->poll = vertex_group_poll;
2630         ot->exec = vertex_group_remove_exec;
2631
2632         /* flags */
2633         /* redo operator will fail in this case because vertex groups aren't stored
2634          * in local edit mode stack and toggling "all" property will lead to
2635          * all groups deleted without way to restore them (see [#29527], sergey) */
2636         ot->flag = /*OPTYPE_REGISTER|*/ OPTYPE_UNDO;
2637
2638         /* properties */
2639         RNA_def_boolean(ot->srna, "all", 0, "All", "Remove from all vertex groups");
2640 }
2641
2642 static int vertex_group_assign_exec(bContext *C, wmOperator *op)
2643 {
2644         ToolSettings *ts = CTX_data_tool_settings(C);
2645         Object *ob = ED_object_context(C);
2646
2647         if (RNA_boolean_get(op->ptr, "new"))
2648                 ED_vgroup_add(ob);
2649
2650         vgroup_assign_verts(ob, ts->vgroup_weight);
2651         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2652         WM_event_add_notifier(C, NC_GEOM | ND_DATA, ob->data);
2653         
2654         return OPERATOR_FINISHED;
2655 }
2656
2657 void OBJECT_OT_vertex_group_assign(wmOperatorType *ot)
2658 {
2659         /* identifiers */
2660         ot->name = "Assign Vertex Group";
2661         ot->idname = "OBJECT_OT_vertex_group_assign";
2662         ot->description = "Assign the selected vertices to the current (or a new) vertex group";
2663         
2664         /* api callbacks */
2665         ot->poll = vertex_group_poll_edit_or_wpaint_vert_select;
2666         ot->exec = vertex_group_assign_exec;
2667
2668         /* flags */
2669         /* redo operator will fail in this case because vertex group assignment
2670          * isn't stored in local edit mode stack and toggling "new" property will
2671          * lead to creating plenty of new vertex groups (see [#29527], sergey) */
2672         ot->flag = /*OPTYPE_REGISTER|*/ OPTYPE_UNDO;
2673
2674         /* properties */
2675         RNA_def_boolean(ot->srna, "new", 0, "New", "Assign vertex to new vertex group");
2676 }
2677
2678 static int vertex_group_remove_from_exec(bContext *C, wmOperator *op)
2679 {
2680         Object *ob = ED_object_context(C);
2681
2682         if (RNA_boolean_get(op->ptr, "all"))
2683                 vgroup_remove_verts(ob, 0);
2684         else {
2685                 bDeformGroup *dg = BLI_findlink(&ob->defbase, ob->actdef - 1);
2686
2687                 if (dg == NULL) {
2688                         return OPERATOR_CANCELLED;
2689                 }
2690
2691                 vgroup_active_remove_verts(ob, FALSE, dg);
2692         }
2693
2694         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2695         WM_event_add_notifier(C, NC_GEOM | ND_DATA, ob->data);
2696
2697         return OPERATOR_FINISHED;
2698 }
2699
2700 void OBJECT_OT_vertex_group_remove_from(wmOperatorType *ot)
2701 {
2702         /* identifiers */
2703         ot->name = "Remove from Vertex Group";
2704         ot->idname = "OBJECT_OT_vertex_group_remove_from";
2705         ot->description = "Remove the selected vertices from the active vertex group";
2706
2707         /* api callbacks */
2708         ot->poll = vertex_group_poll_edit_or_wpaint_vert_select;
2709         ot->exec = vertex_group_remove_from_exec;
2710
2711         /* flags */
2712         /* redo operator will fail in this case because vertex groups assignment
2713          * isn't stored in local edit mode stack and toggling "all" property will lead to
2714          * removing vertices from all groups (see [#29527], sergey) */
2715         ot->flag = /*OPTYPE_REGISTER|*/ OPTYPE_UNDO;
2716
2717         /* properties */
2718         RNA_def_boolean(ot->srna, "all", 0, "All", "Remove from all vertex groups");
2719 }
2720
2721 static int vertex_group_select_exec(bContext *C, wmOperator *UNUSED(op))
2722 {
2723         Object *ob = ED_object_context(C);
2724
2725         if (!ob || ob->id.lib)
2726                 return OPERATOR_CANCELLED;
2727
2728         vgroup_select_verts(ob, 1);
2729         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, ob->data);
2730
2731         return OPERATOR_FINISHED;
2732 }
2733
2734 void OBJECT_OT_vertex_group_select(wmOperatorType *ot)
2735 {
2736         /* identifiers */
2737         ot->name = "Select Vertex Group";
2738         ot->idname = "OBJECT_OT_vertex_group_select";
2739         ot->description = "Select all the vertices assigned to the active vertex group";
2740
2741         /* api callbacks */
2742         ot->poll = vertex_group_poll_edit_or_wpaint_vert_select;
2743         ot->exec = vertex_group_select_exec;
2744
2745         /* flags */
2746         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2747 }
2748
2749 static int vertex_group_deselect_exec(bContext *C, wmOperator *UNUSED(op))
2750 {
2751         Object *ob = ED_object_context(C);
2752
2753         vgroup_select_verts(ob, 0);
2754         WM_event_add_notifier(C, NC_GEOM | ND_SELECT, ob->data);
2755
2756         return OPERATOR_FINISHED;
2757 }
2758
2759 void OBJECT_OT_vertex_group_deselect(wmOperatorType *ot)
2760 {
2761         /* identifiers */
2762         ot->name = "Deselect Vertex Group";
2763         ot->idname = "OBJECT_OT_vertex_group_deselect";
2764         ot->description = "Deselect all selected vertices assigned to the active vertex group";
2765
2766         /* api callbacks */
2767         ot->poll = vertex_group_poll_edit_or_wpaint_vert_select;
2768         ot->exec = vertex_group_deselect_exec;
2769
2770         /* flags */
2771         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2772 }
2773
2774 static int vertex_group_copy_exec(bContext *C, wmOperator *UNUSED(op))
2775 {
2776         Object *ob = ED_object_context(C);
2777
2778         vgroup_duplicate(ob);
2779         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2780         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2781         WM_event_add_notifier(C, NC_GEOM | ND_DATA, ob->data);
2782
2783         return OPERATOR_FINISHED;
2784 }
2785
2786 void OBJECT_OT_vertex_group_copy(wmOperatorType *ot)
2787 {
2788         /* identifiers */
2789         ot->name = "Copy Vertex Group";
2790         ot->idname = "OBJECT_OT_vertex_group_copy";
2791         ot->description = "Make a copy of the active vertex group";
2792
2793         /* api callbacks */
2794         ot->poll = vertex_group_poll;
2795         ot->exec = vertex_group_copy_exec;
2796
2797         /* flags */
2798         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2799 }
2800
2801 static int vertex_group_levels_exec(bContext *C, wmOperator *op)
2802 {
2803         Object *ob = ED_object_context(C);
2804         
2805         float offset = RNA_float_get(op->ptr, "offset");
2806         float gain = RNA_float_get(op->ptr, "gain");
2807         
2808         vgroup_levels(ob, offset, gain);
2809         
2810         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2811         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2812         WM_event_add_notifier(C, NC_GEOM | ND_DATA, ob->data);
2813         
2814         return OPERATOR_FINISHED;
2815 }
2816
2817 void OBJECT_OT_vertex_group_levels(wmOperatorType *ot)
2818 {
2819         /* identifiers */
2820         ot->name = "Vertex Group Levels";
2821         ot->idname = "OBJECT_OT_vertex_group_levels";
2822         ot->description = "Add some offset and multiply with some gain the weights of the active vertex group";
2823         
2824         /* api callbacks */
2825         ot->poll = vertex_group_poll;
2826         ot->exec = vertex_group_levels_exec;
2827         
2828         /* flags */
2829         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2830         
2831         RNA_def_float(ot->srna, "offset", 0.f, -1.0, 1.0, "Offset", "Value to add to weights", -1.0f, 1.f);
2832         RNA_def_float(ot->srna, "gain", 1.f, 0.f, FLT_MAX, "Gain", "Value to multiply weights by", 0.0f, 10.f);
2833 }
2834
2835 static int vertex_group_normalize_exec(bContext *C, wmOperator *UNUSED(op))
2836 {
2837         Object *ob = ED_object_context(C);
2838
2839         vgroup_normalize(ob);
2840
2841         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2842         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2843         WM_event_add_notifier(C, NC_GEOM | ND_DATA, ob->data);
2844
2845         return OPERATOR_FINISHED;
2846 }
2847
2848 void OBJECT_OT_vertex_group_normalize(wmOperatorType *ot)
2849 {
2850         /* identifiers */
2851         ot->name = "Normalize Vertex Group";
2852         ot->idname = "OBJECT_OT_vertex_group_normalize";
2853         ot->description = "Normalize weights of the active vertex group, so that the highest ones are now 1.0";
2854
2855         /* api callbacks */
2856         ot->poll = vertex_group_poll;
2857         ot->exec = vertex_group_normalize_exec;
2858
2859         /* flags */
2860         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2861 }
2862
2863 static int vertex_group_normalize_all_exec(bContext *C, wmOperator *op)
2864 {
2865         Object *ob = ED_object_context(C);
2866         int lock_active = RNA_boolean_get(op->ptr, "lock_active");
2867
2868         vgroup_normalize_all(ob, lock_active);
2869
2870         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2871         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2872         WM_event_add_notifier(C, NC_GEOM | ND_DATA, ob->data);
2873
2874         return OPERATOR_FINISHED;
2875 }
2876
2877 void OBJECT_OT_vertex_group_normalize_all(wmOperatorType *ot)
2878 {
2879         /* identifiers */
2880         ot->name = "Normalize All Vertex Groups";
2881         ot->idname = "OBJECT_OT_vertex_group_normalize_all";
2882         ot->description = "Normalize all weights of all vertex groups, "
2883                           "so that for each vertex, the sum of all weights is 1.0";
2884
2885         /* api callbacks */
2886         ot->poll = vertex_group_poll;
2887         ot->exec = vertex_group_normalize_all_exec;
2888
2889         /* flags */
2890         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2891
2892         RNA_def_boolean(ot->srna, "lock_active", TRUE, "Lock Active",
2893                         "Keep the values of the active group while normalizing others");
2894 }
2895
2896 static int vertex_group_fix_exec(bContext *C, wmOperator *op)
2897 {
2898         Object *ob = CTX_data_active_object(C);
2899         Scene *scene = CTX_data_scene(C);
2900         
2901         float distToBe = RNA_float_get(op->ptr, "dist");
2902         float strength = RNA_float_get(op->ptr, "strength");
2903         float cp = RNA_float_get(op->ptr, "accuracy");
2904         ModifierData *md = ob->modifiers.first;
2905
2906         while (md) {
2907                 if (md->type == eModifierType_Mirror && (md->mode & eModifierMode_Realtime)) {
2908                         break;
2909                 }
2910                 md = md->next;
2911         }
2912         
2913         if (md && md->type == eModifierType_Mirror) {
2914                 BKE_report(op->reports, RPT_ERROR_INVALID_CONTEXT, "This operator does not support an active mirror modifier");
2915                 return OPERATOR_CANCELLED;
2916         }
2917         vgroup_fix(scene, ob, distToBe, strength, cp);
2918         
2919         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2920         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2921         WM_event_add_notifier(C, NC_GEOM | ND_DATA, ob->data);
2922         
2923         return OPERATOR_FINISHED;
2924 }
2925
2926 void OBJECT_OT_vertex_group_fix(wmOperatorType *ot)
2927 {
2928         /* identifiers */
2929         ot->name = "Fix Vertex Group Deform";
2930         ot->idname = "OBJECT_OT_vertex_group_fix";
2931         ot->description = "Modify the position of selected vertices by changing only their respective "
2932                           "groups' weights (this tool may be slow for many vertices)";
2933         
2934         /* api callbacks */
2935         ot->poll = vertex_group_poll;
2936         ot->exec = vertex_group_fix_exec;
2937         
2938         /* flags */
2939         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2940         RNA_def_float(ot->srna, "dist", 0.0f, -FLT_MAX, FLT_MAX, "Distance", "The distance to move to", -10.0f, 10.0f);
2941         RNA_def_float(ot->srna, "strength", 1.f, -2.0f, FLT_MAX, "Strength",
2942                       "The distance moved can be changed by this multiplier", -2.0f, 2.0f);
2943         RNA_def_float(ot->srna, "accuracy", 1.0f, 0.05f, FLT_MAX, "Change Sensitivity",
2944                       "Change the amount weights are altered with each iteration: lower values are slower", 0.05f, 1.f);
2945 }
2946
2947
2948 static int vertex_group_lock_exec(bContext *C, wmOperator *op)
2949 {
2950         Object *ob = CTX_data_active_object(C);
2951
2952         int action = RNA_enum_get(op->ptr, "action");
2953
2954         vgroup_lock_all(ob, action);
2955
2956         return OPERATOR_FINISHED;
2957 }
2958
2959 void OBJECT_OT_vertex_group_lock(wmOperatorType *ot)
2960 {
2961         /* identifiers */
2962         ot->name = "Change the Lock On Vertex Groups";
2963         ot->idname = "OBJECT_OT_vertex_group_lock";
2964         ot->description = "Change the lock state of all vertex groups of active object";
2965
2966         /* api callbacks */
2967         ot->poll = vertex_group_poll;
2968         ot->exec = vertex_group_lock_exec;
2969
2970         /* flags */
2971         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
297