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