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