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