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