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