- remove unneeded len_v3v3 in bevel code
[blender.git] / source / blender / editors / object / object_vgroup.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): 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         MEM_freeN(upDown);
1049         MEM_freeN(changes);
1050         MEM_freeN(dists);
1051         MEM_freeN(dwIndices);
1052 }
1053
1054 /* this is used to try to smooth a surface by only adjusting the nonzero weights of a vertex 
1055  * but it could be used to raise or lower an existing 'bump.' */
1056 static void vgroup_fix(Scene *scene, Object *ob, float distToBe, float strength, float cp)
1057 {
1058         int i;
1059
1060         Mesh *me = ob->data;
1061         MVert *mvert = me->mvert;
1062         int *verts = NULL;
1063         if (!(me->editflag & ME_EDIT_VERT_SEL))
1064                 return;
1065         for (i = 0; i < me->totvert && mvert; i++, mvert++) {
1066                 if (mvert->flag & SELECT) {
1067                         int count=0;
1068                         if ((verts = getSurroundingVerts(me, i, &count))) {
1069                                 MVert m;
1070                                 MVert *p = MEM_callocN(sizeof(MVert)*(count), "deformedPoints");
1071                                 int k;
1072
1073                                 DerivedMesh *dm = mesh_get_derived_deform(scene, ob, CD_MASK_BAREMESH);
1074                                 k = count;
1075                                 while (k--) {
1076                                         dm->getVert(dm, verts[k], &m);
1077                                         p[k] = m;
1078                                 }
1079                                 
1080                                 if (count >= 3) {
1081                                         float d /*, dist */ /* UNUSED */, mag;
1082                                         float coord[3];
1083                                         float norm[3];
1084                                         getSingleCoordinate(p, count, coord);
1085                                         dm->getVert(dm, i, &m);
1086                                         sub_v3_v3v3(norm, m.co, coord);
1087                                         mag= normalize_v3(norm);
1088                                         if (mag) { /* zeros fix */
1089                                                 d = -dot_v3v3(norm, coord);
1090                                                 /* dist = (dot_v3v3(norm, m.co) + d); */ /* UNUSED */
1091                                                 moveCloserToDistanceFromPlane(scene, ob, me, i, norm, coord, d, distToBe, strength, cp);
1092                                         }
1093                                 }
1094
1095                                 MEM_freeN(verts);
1096                                 MEM_freeN(p);
1097                         }
1098                 }
1099         }
1100 }
1101
1102 static void vgroup_levels(Object *ob, float offset, float gain)
1103 {
1104         MDeformWeight *dw;
1105         MDeformVert *dv, **dvert_array=NULL;
1106         int i, dvert_tot=0;
1107         const int def_nr= ob->actdef-1;
1108
1109         const int use_vert_sel = (ob->type == OB_MESH && ((Mesh *)ob->data)->editflag & ME_EDIT_VERT_SEL) != 0;
1110
1111         if (!BLI_findlink(&ob->defbase, def_nr)) {
1112                 return;
1113         }
1114
1115         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1116
1117         if (dvert_array) {
1118                 for (i = 0; i < dvert_tot; i++) {
1119
1120                         /* in case its not selected */
1121                         if (!(dv = dvert_array[i])) {
1122                                 continue;
1123                         }
1124
1125                         dw = defvert_find_index(dv, def_nr);
1126                         if (dw) {
1127                                 dw->weight = gain * (dw->weight + offset);
1128
1129                                 CLAMP(dw->weight, 0.0f, 1.0f);
1130                         }
1131                 }
1132
1133                 MEM_freeN(dvert_array);
1134         }
1135 }
1136
1137 /* TODO - select between groups */
1138 static void vgroup_normalize_all(Object *ob, int lock_active)
1139 {
1140         MDeformVert *dv, **dvert_array=NULL;
1141         int i, dvert_tot=0;
1142         const int def_nr= ob->actdef-1;
1143
1144         const int use_vert_sel = (ob->type == OB_MESH && ((Mesh *)ob->data)->editflag & ME_EDIT_VERT_SEL) != 0;
1145
1146         if (lock_active && !BLI_findlink(&ob->defbase, def_nr)) {
1147                 return;
1148         }
1149
1150         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1151
1152         if (dvert_array) {
1153                 if (lock_active) {
1154
1155                         for (i = 0; i < dvert_tot; i++) {
1156                                 /* in case its not selected */
1157                                 if (!(dv = dvert_array[i])) {
1158                                         continue;
1159                                 }
1160
1161                                 defvert_normalize_lock(dv, def_nr);
1162                         }
1163                 }
1164                 else {
1165                         for (i = 0; i < dvert_tot; i++) {
1166
1167                                 /* in case its not selected */
1168                                 if (!(dv = dvert_array[i])) {
1169                                         continue;
1170                                 }
1171
1172                                 defvert_normalize(dv);
1173                         }
1174                 }
1175
1176                 MEM_freeN(dvert_array);
1177         }
1178 }
1179
1180
1181 static void vgroup_lock_all(Object *ob, int action)
1182 {
1183         bDeformGroup *dg;
1184
1185         if (action == SEL_TOGGLE) {
1186                 action= SEL_SELECT;
1187                 for (dg= ob->defbase.first; dg; dg= dg->next) {
1188                         if (dg->flag & DG_LOCK_WEIGHT) {
1189                                 action= SEL_DESELECT;
1190                                 break;
1191                         }
1192                 }
1193         }
1194
1195         for (dg= ob->defbase.first; dg; dg= dg->next) {
1196                 switch(action) {
1197                         case SEL_SELECT:
1198                                 dg->flag |= DG_LOCK_WEIGHT;
1199                                 break;
1200                         case SEL_DESELECT:
1201                                 dg->flag &= ~DG_LOCK_WEIGHT;
1202                                 break;
1203                         case SEL_INVERT:
1204                                 dg->flag ^= DG_LOCK_WEIGHT;
1205                                 break;
1206                 }
1207         }
1208 }
1209
1210 static void vgroup_invert(Object *ob, const short auto_assign, const short auto_remove)
1211 {
1212         MDeformWeight *dw;
1213         MDeformVert *dv, **dvert_array=NULL;
1214         int i, dvert_tot=0;
1215         const int def_nr= ob->actdef-1;
1216         const int use_vert_sel = (ob->type == OB_MESH && ((Mesh *)ob->data)->editflag & ME_EDIT_VERT_SEL) != 0;
1217
1218         if (!BLI_findlink(&ob->defbase, def_nr)) {
1219                 return;
1220         }
1221
1222         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1223
1224         if (dvert_array) {
1225                 for (i = 0; i < dvert_tot; i++) {
1226
1227                         /* in case its not selected */
1228                         if (!(dv = dvert_array[i])) {
1229                                 continue;
1230                         }
1231
1232                         if (auto_assign) {
1233                                 dw= defvert_verify_index(dv, def_nr);
1234                         }
1235                         else {
1236                                 dw= defvert_find_index(dv, def_nr);
1237                         }
1238
1239                         if (dw) {
1240                                 dw->weight = 1.0f - dw->weight;
1241
1242                                 if (auto_remove && dw->weight <= 0.0f) {
1243                                         defvert_remove_group(dv, dw);
1244                                 }
1245                         }
1246                 }
1247
1248                 MEM_freeN(dvert_array);
1249         }
1250 }
1251
1252 static void vgroup_blend(Object *ob, const float fac)
1253 {
1254         MDeformVert *dv;
1255         MDeformWeight *dw;
1256         int i, dvert_tot=0;
1257         const int def_nr= ob->actdef - 1;
1258
1259         BLI_assert(fac >= 0.0 && fac <= 1.0f);
1260
1261         if (ob->type != OB_MESH) {
1262                 return;
1263         }
1264
1265         if (BLI_findlink(&ob->defbase, def_nr)) {
1266                 const float ifac = 1.0f - fac;
1267
1268                 BMEditMesh *em = BMEdit_FromObject(ob);
1269                 BMesh *bm = em ? em->bm : NULL;
1270                 Mesh  *me = em ? NULL   : ob->data;
1271
1272                 /* bmesh only*/
1273                 BMEdge *eed;
1274                 BMVert *eve;
1275                 BMIter iter;
1276
1277                 /* mesh only */
1278                 MDeformVert *dvert_array = NULL;
1279
1280
1281                 float *vg_weights;
1282                 float *vg_users;
1283                 int sel1, sel2;
1284
1285                 if (bm) {
1286                         BM_mesh_elem_index_ensure(bm, BM_VERT);
1287                         dvert_tot = bm->totvert;
1288                 }
1289                 else {
1290                         dvert_tot = me->totvert;
1291                         dvert_array = me->dvert;
1292                 }
1293
1294                 vg_weights = MEM_callocN(sizeof(float) * dvert_tot, "vgroup_blend_f");
1295                 vg_users = MEM_callocN(sizeof(int) * dvert_tot, "vgroup_blend_i");
1296
1297                 if (bm) {
1298                         BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
1299                                 sel1 = BM_elem_flag_test(eed->v1, BM_ELEM_SELECT);
1300                                 sel2 = BM_elem_flag_test(eed->v2, BM_ELEM_SELECT);
1301
1302                                 if (sel1 != sel2) {
1303                                         int i1 /* , i2 */;
1304                                         /* i1 is always the selected one */
1305                                         if (sel1) {
1306                                                 i1= BM_elem_index_get(eed->v1);
1307                                                 /* i2= BM_elem_index_get(eed->v2); */ /* UNUSED */
1308                                                 eve= eed->v2;
1309                                         }
1310                                         else {
1311                                                 /* i2= BM_elem_index_get(eed->v1); */ /* UNUSED */
1312                                                 i1= BM_elem_index_get(eed->v2);
1313                                                 eve= eed->v1;
1314                                         }
1315
1316                                         dv = CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_MDEFORMVERT);
1317                                         dw = defvert_find_index(dv, def_nr);
1318                                         if (dw) {
1319                                                 vg_weights[i1] += dw->weight;
1320                                         }
1321                                         vg_users[i1]++;
1322                                 }
1323                         }
1324
1325                         BM_ITER_MESH_INDEX (eve, &iter, bm, BM_VERTS_OF_MESH, i) {
1326                                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT) && vg_users[i] > 0) {
1327                                         dv = CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_MDEFORMVERT);
1328
1329                                         dw = defvert_verify_index(dv, def_nr);
1330                                         dw->weight = (fac * (vg_weights[i] / (float)vg_users[i])) + (ifac * dw->weight);
1331                                         /* in case of division errors */
1332                                         CLAMP(dw->weight, 0.0f, 1.0f);
1333                                 }
1334                         }
1335                 }
1336                 else {
1337                         MEdge *ed = me->medge;
1338                         MVert *mv;
1339
1340                         for (i = 0; i < me->totedge; i++, ed++) {
1341                                 sel1 = me->mvert[ed->v1].flag & SELECT;
1342                                 sel2 = me->mvert[ed->v2].flag & SELECT;
1343
1344                                 if (sel1 != sel2) {
1345                                         int i1, i2;
1346                                         /* i1 is always the selected one */
1347                                         if (sel1) {
1348                                                 i1 = ed->v1;
1349                                                 i2 = ed->v2;
1350                                         }
1351                                         else {
1352                                                 i2 = ed->v1;
1353                                                 i1 = ed->v2;
1354                                         }
1355
1356                                         dv = &dvert_array[i2];
1357                                         dw = defvert_find_index(dv, def_nr);
1358                                         if (dw) {
1359                                                 vg_weights[i1] += dw->weight;
1360                                         }
1361                                         vg_users[i1]++;
1362                                 }
1363                         }
1364
1365                         mv = me->mvert;
1366                         dv = dvert_array;
1367
1368                         for (i = 0; i < dvert_tot; i++, mv++, dv++) {
1369                                 if ((mv->flag & SELECT) && (vg_users[i] > 0)) {
1370                                         dw = defvert_verify_index(dv, def_nr);
1371                                         dw->weight = (fac * (vg_weights[i] / (float)vg_users[i])) + (ifac * dw->weight);
1372
1373                                         /* in case of division errors */
1374                                         CLAMP(dw->weight, 0.0f, 1.0f);
1375                                 }
1376                         }
1377                 }
1378
1379                 MEM_freeN(vg_weights);
1380                 MEM_freeN(vg_users);
1381         }
1382 }
1383
1384 static void vgroup_clean(Object *ob, const float epsilon, int keep_single)
1385 {
1386         MDeformWeight *dw;
1387         MDeformVert *dv, **dvert_array=NULL;
1388         int i, dvert_tot=0;
1389         const int def_nr= ob->actdef-1;
1390         const int use_vert_sel = (ob->type == OB_MESH && ((Mesh *)ob->data)->editflag & ME_EDIT_VERT_SEL) != 0;
1391
1392         if (!BLI_findlink(&ob->defbase, def_nr)) {
1393                 return;
1394         }
1395
1396         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1397
1398         if (dvert_array) {
1399                 /* only the active group */
1400                 for (i = 0; i < dvert_tot; i++) {
1401
1402                         /* in case its not selected */
1403                         if (!(dv = dvert_array[i])) {
1404                                 continue;
1405                         }
1406
1407                         dw= defvert_find_index(dv, def_nr);
1408
1409                         if (dw) {
1410                                 if (dw->weight <= epsilon) {
1411                                         if (keep_single==FALSE || dv->totweight > 1) {
1412                                                 defvert_remove_group(dv, dw); /* dw can be NULL */
1413                                         }
1414                                 }
1415                         }
1416                 }
1417
1418                 MEM_freeN(dvert_array);
1419         }
1420 }
1421
1422 static void vgroup_clean_all(Object *ob, const float epsilon, const int keep_single)
1423 {
1424         MDeformVert **dvert_array=NULL;
1425         int i, dvert_tot = 0;
1426         const int use_vert_sel = (ob->type == OB_MESH && ((Mesh *)ob->data)->editflag & ME_EDIT_VERT_SEL) != 0;
1427
1428         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1429
1430         if (dvert_array) {
1431                 MDeformVert *dv;
1432                 MDeformWeight *dw;
1433
1434                 for (i = 0; i < dvert_tot; i++) {
1435                         int j;
1436
1437                         /* in case its not selected */
1438                         if (!(dv = dvert_array[i])) {
1439                                 continue;
1440                         }
1441
1442                         j= dv->totweight;
1443
1444                         while (j--) {
1445
1446                                 if (keep_single && dv->totweight == 1)
1447                                         break;
1448
1449                                 dw= dv->dw + j;
1450
1451                                 if (dw->weight <= epsilon) {
1452                                         defvert_remove_group(dv, dw);
1453                                 }
1454                         }
1455                 }
1456
1457                 MEM_freeN(dvert_array);
1458         }
1459 }
1460
1461
1462 static void dvert_mirror_op(MDeformVert *dvert, MDeformVert *dvert_mirr,
1463                             const char sel, const char sel_mirr,
1464                             const int *flip_map, const int flip_map_len,
1465                             const short mirror_weights, const short flip_vgroups,
1466                             const short all_vgroups, const int act_vgroup)
1467 {
1468         BLI_assert(sel || sel_mirr);
1469
1470         if (sel_mirr && sel) {
1471                 /* swap */
1472                 if (mirror_weights) {
1473                         if (all_vgroups) {
1474                                 SWAP(MDeformVert, *dvert, *dvert_mirr);
1475                         }
1476                         else {
1477                                 MDeformWeight *dw=      defvert_find_index(dvert, act_vgroup);
1478                                 MDeformWeight *dw_mirr= defvert_find_index(dvert_mirr, act_vgroup);
1479
1480                                 if (dw || dw_mirr) {
1481                                         if (dw_mirr == NULL)
1482                                                 dw_mirr= defvert_verify_index(dvert_mirr, act_vgroup);
1483                                         if (dw == NULL)
1484                                                 dw= defvert_verify_index(dvert, act_vgroup);
1485
1486                                         SWAP(float, dw->weight, dw_mirr->weight);
1487                                 }
1488                         }
1489                 }
1490
1491                 if (flip_vgroups) {
1492                         defvert_flip(dvert, flip_map, flip_map_len);
1493                         defvert_flip(dvert_mirr, flip_map, flip_map_len);
1494                 }
1495         }
1496         else {
1497                 /* dvert should always be the target, only swaps pointer */
1498                 if (sel_mirr) {
1499                         SWAP(MDeformVert *, dvert, dvert_mirr);
1500                 }
1501
1502                 if (mirror_weights) {
1503                         if (all_vgroups) {
1504                                 defvert_copy(dvert, dvert_mirr);
1505                         }
1506                         else {
1507                                 defvert_copy_index(dvert, dvert_mirr, act_vgroup);
1508                         }
1509                 }
1510
1511                 /* flip map already modified for 'all_vgroups' */
1512                 if (flip_vgroups) {
1513                         defvert_flip(dvert, flip_map, flip_map_len);
1514                 }
1515         }
1516 }
1517
1518 /* TODO, vgroup locking */
1519 /* TODO, face masking */
1520 void ED_vgroup_mirror(Object *ob, const short mirror_weights, const short flip_vgroups, const short all_vgroups)
1521 {
1522
1523 #define VGROUP_MIRR_OP                                                        \
1524         dvert_mirror_op(dvert, dvert_mirr,                                    \
1525                         sel, sel_mirr,                                        \
1526                         flip_map, flip_map_len,                               \
1527                         mirror_weights, flip_vgroups,                         \
1528                         all_vgroups, def_nr                                   \
1529                         )
1530
1531         BMVert *eve, *eve_mirr;
1532         MDeformVert *dvert, *dvert_mirr;
1533         short sel, sel_mirr;
1534         int     *flip_map, flip_map_len;
1535         const int def_nr= ob->actdef-1;
1536
1537         if ( (mirror_weights==0 && flip_vgroups==0) ||
1538              (BLI_findlink(&ob->defbase, def_nr) == NULL) )
1539         {
1540                 return;
1541         }
1542
1543         if (flip_vgroups) {
1544                 flip_map= all_vgroups ?
1545                                         defgroup_flip_map(ob, &flip_map_len, FALSE) :
1546                                         defgroup_flip_map_single(ob, &flip_map_len, FALSE, def_nr);
1547
1548                 BLI_assert(flip_map != NULL);
1549
1550                 if (flip_map == NULL) {
1551                         /* something went wrong!, possibly no groups */
1552                         return;
1553                 }
1554         }
1555         else {
1556                 flip_map= NULL;
1557                 flip_map_len= 0;
1558         }
1559
1560         /* only the active group */
1561         if (ob->type == OB_MESH) {
1562                 Mesh *me= ob->data;
1563                 BMEditMesh *em = me->edit_btmesh;
1564
1565                 if (em) {
1566                         BMIter iter;
1567
1568                         if (!CustomData_has_layer(&em->bm->vdata, CD_MDEFORMVERT)) {
1569                                 goto cleanup;
1570                         }
1571
1572                         EDBM_verts_mirror_cache_begin(em, FALSE);
1573
1574                         /* Go through the list of editverts and assign them */
1575                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1576                                 if ((eve_mirr= EDBM_verts_mirror_get(em, eve))) {
1577                                         sel= BM_elem_flag_test(eve, BM_ELEM_SELECT);
1578                                         sel_mirr= BM_elem_flag_test(eve_mirr, BM_ELEM_SELECT);
1579
1580                                         if ((sel || sel_mirr) && (eve != eve_mirr)) {
1581                                                 dvert= CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_MDEFORMVERT);
1582                                                 dvert_mirr= CustomData_bmesh_get(&em->bm->vdata, eve_mirr->head.data, CD_MDEFORMVERT);
1583                                                 if (dvert && dvert_mirr) {
1584                                                         VGROUP_MIRR_OP;
1585                                                 }
1586                                         }
1587
1588                                         /* don't use these again */
1589                                         EDBM_verts_mirror_cache_clear(em, eve);
1590                                         EDBM_verts_mirror_cache_clear(em, eve_mirr);
1591                                 }
1592                         }
1593                         EDBM_verts_mirror_cache_end(em);
1594                 }
1595                 else {
1596                         /* object mode / weight paint */
1597                         MVert *mv, *mv_mirr;
1598                         int vidx, vidx_mirr;
1599                         const int use_vert_sel = (me->editflag & ME_EDIT_VERT_SEL) != 0;
1600
1601                         if (me->dvert == NULL) {
1602                                 goto cleanup;
1603                         }
1604
1605                         if (!use_vert_sel) {
1606                                 sel= sel_mirr= TRUE;
1607                         }
1608
1609                         /* tag verts we have used */
1610                         for (vidx= 0, mv= me->mvert; vidx < me->totvert; vidx++, mv++) {
1611                                 mv->flag &= ~ME_VERT_TMP_TAG;
1612                         }
1613
1614                         for (vidx= 0, mv= me->mvert; vidx < me->totvert; vidx++, mv++) {
1615                                 if (    ((mv->flag & ME_VERT_TMP_TAG) == 0) &&
1616                                         ((vidx_mirr= mesh_get_x_mirror_vert(ob, vidx)) != -1) &&
1617                                         (vidx != vidx_mirr) &&
1618                                         ((((mv_mirr= me->mvert + vidx_mirr)->flag) & ME_VERT_TMP_TAG) == 0))
1619                                 {
1620
1621                                         if (use_vert_sel) {
1622                                                 sel= mv->flag & SELECT;
1623                                                 sel_mirr= mv_mirr->flag & SELECT;
1624                                         }
1625
1626                                         if (sel || sel_mirr) {
1627                                                 dvert= &me->dvert[vidx];
1628                                                 dvert_mirr= &me->dvert[vidx_mirr];
1629
1630                                                 VGROUP_MIRR_OP;
1631                                         }
1632
1633                                         mv->flag |= ME_VERT_TMP_TAG;
1634                                         mv_mirr->flag |= ME_VERT_TMP_TAG;
1635                                 }
1636                         }
1637                 }
1638         }
1639         else if (ob->type == OB_LATTICE) {
1640                 Lattice *lt= vgroup_edit_lattice(ob);
1641                 int i1, i2;
1642                 int u, v, w;
1643                 int pntsu_half;
1644                 /* half but found up odd value */
1645
1646                 if (lt->pntsu == 1 || lt->dvert == NULL) {
1647                         goto cleanup;
1648                 }
1649
1650                 /* unlike editmesh we know that by only looping over the first half of
1651                  * the 'u' indices it will cover all points except the middle which is
1652                  * ok in this case */
1653                 pntsu_half= lt->pntsu / 2;
1654
1655                 for (w=0; w<lt->pntsw; w++) {
1656                         for (v=0; v<lt->pntsv; v++) {
1657                                 for (u=0; u<pntsu_half; u++) {
1658                                         int u_inv= (lt->pntsu - 1) - u;
1659                                         if (u != u_inv) {
1660                                                 BPoint *bp, *bp_mirr;
1661
1662                                                 i1= LT_INDEX(lt, u, v, w);
1663                                                 i2= LT_INDEX(lt, u_inv, v, w);
1664
1665                                                 bp= &lt->def[i1];
1666                                                 bp_mirr= &lt->def[i2];
1667
1668                                                 sel= bp->f1 & SELECT;
1669                                                 sel_mirr= bp_mirr->f1 & SELECT;
1670
1671                                                 if (sel || sel_mirr) {
1672                                                         dvert= &lt->dvert[i1];
1673                                                         dvert_mirr= &lt->dvert[i2];
1674
1675                                                         VGROUP_MIRR_OP;
1676                                                 }
1677                                         }
1678                                 }
1679                         }
1680                 }
1681         }
1682
1683 cleanup:
1684         if (flip_map) MEM_freeN(flip_map);
1685
1686 #undef VGROUP_MIRR_OP
1687
1688 }
1689
1690 static void vgroup_remap_update_users(Object *ob, int *map)
1691 {
1692         ExplodeModifierData *emd;
1693         ModifierData *md;
1694         ParticleSystem *psys;
1695         ClothModifierData *clmd;
1696         ClothSimSettings *clsim;
1697         int a;
1698
1699         /* these cases don't use names to refer to vertex groups, so when
1700          * they get deleted the numbers get out of sync, this corrects that */
1701
1702         if (ob->soft)
1703                 ob->soft->vertgroup= map[ob->soft->vertgroup];
1704
1705         for (md=ob->modifiers.first; md; md=md->next) {
1706                 if (md->type == eModifierType_Explode) {
1707                         emd= (ExplodeModifierData*)md;
1708                         emd->vgroup= map[emd->vgroup];
1709                 }
1710                 else if (md->type == eModifierType_Cloth) {
1711                         clmd= (ClothModifierData*)md;
1712                         clsim= clmd->sim_parms;
1713
1714                         if (clsim) {
1715                                 clsim->vgroup_mass= map[clsim->vgroup_mass];
1716                                 clsim->vgroup_bend= map[clsim->vgroup_bend];
1717                                 clsim->vgroup_struct= map[clsim->vgroup_struct];
1718                         }
1719                 }
1720         }
1721
1722         for (psys=ob->particlesystem.first; psys; psys=psys->next) {
1723                 for (a=0; a<PSYS_TOT_VG; a++)
1724                         psys->vgroup[a]= map[psys->vgroup[a]];
1725         }
1726 }
1727
1728
1729 static void vgroup_delete_update_users(Object *ob, int id)
1730 {
1731         int i, defbase_tot= BLI_countlist(&ob->defbase) + 1;
1732         int *map= MEM_mallocN(sizeof(int) * defbase_tot, "vgroup del");
1733
1734         map[id]= map[0]= 0;
1735         for (i=1; i<id; i++) map[i]=i;
1736         for (i=id+1; i<defbase_tot; i++) map[i]=i-1;
1737
1738         vgroup_remap_update_users(ob, map);
1739         MEM_freeN(map);
1740 }
1741
1742
1743 static void vgroup_delete_object_mode(Object *ob, bDeformGroup *dg)
1744 {
1745         MDeformVert *dvert_array=NULL;
1746         int dvert_tot=0;
1747         const int def_nr= BLI_findindex(&ob->defbase, dg);
1748
1749         assert(def_nr > -1);
1750
1751         ED_vgroup_give_array(ob->data, &dvert_array, &dvert_tot);
1752
1753         if (dvert_array) {
1754                 int i, j;
1755                 MDeformVert *dv;
1756                 for (i= 0, dv= dvert_array; i < dvert_tot; i++, dv++) {
1757                         MDeformWeight *dw;
1758
1759                         dw= defvert_find_index(dv, def_nr);
1760                         defvert_remove_group(dv, dw); /* dw can be NULL */
1761
1762                         /* inline, make into a function if anything else needs to do this */
1763                         for (j = 0; j < dv->totweight; j++) {
1764                                 if (dv->dw[j].def_nr > def_nr) {
1765                                         dv->dw[j].def_nr--;
1766                                 }
1767                         }
1768                         /* done */
1769                 }
1770         }
1771
1772         vgroup_delete_update_users(ob, def_nr + 1);
1773
1774         /* Remove the group */
1775         BLI_freelinkN(&ob->defbase, dg);
1776
1777         /* Update the active deform index if necessary */
1778         if (ob->actdef > def_nr)
1779                 ob->actdef--;
1780         if (ob->actdef < 1 && ob->defbase.first)
1781                 ob->actdef= 1;
1782
1783 }
1784
1785 /* only in editmode */
1786 /* removes from active defgroup, if allverts==0 only selected vertices */
1787 static void vgroup_active_remove_verts(Object *ob, const int allverts, bDeformGroup *dg)
1788 {
1789         MDeformVert *dv;
1790         const int def_nr= BLI_findindex(&ob->defbase, dg);
1791
1792         if (ob->type == OB_MESH) {
1793                 Mesh *me= ob->data;
1794
1795                 if (me->edit_btmesh) {
1796                         BMEditMesh *em = me->edit_btmesh;
1797                         BMVert *eve;
1798                         BMIter iter;
1799
1800                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1801                                 dv= CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_MDEFORMVERT);
1802
1803                                 if (dv && dv->dw && (allverts || BM_elem_flag_test(eve, BM_ELEM_SELECT))) {
1804                                         MDeformWeight *dw = defvert_find_index(dv, def_nr);
1805                                         defvert_remove_group(dv, dw); /* dw can be NULL */
1806                                 }
1807                         }
1808                 }
1809                 else {
1810                         MVert *mv;
1811                         MDeformVert *dv;
1812                         int i;
1813
1814                         if (!me->dvert) {
1815                                 ED_vgroup_data_create(&me->id);
1816                         }
1817
1818                         mv = me->mvert;
1819                         dv = me->dvert;
1820
1821                         for (i=0; i<me->totvert; i++, mv++, dv++) {
1822                                 if (mv->flag & SELECT) {
1823                                         if (dv->dw && (allverts || (mv->flag & SELECT))) {
1824                                                 MDeformWeight *dw = defvert_find_index(dv, def_nr);
1825                                                 defvert_remove_group(dv, dw); /* dw can be NULL */
1826                                         }
1827                                 }
1828                         }
1829                 }
1830         }
1831         else if (ob->type == OB_LATTICE) {
1832                 Lattice *lt= vgroup_edit_lattice(ob);
1833                 
1834                 if (lt->dvert) {
1835                         BPoint *bp;
1836                         int i, tot= lt->pntsu*lt->pntsv*lt->pntsw;
1837                                 
1838                         for (i=0, bp= lt->def; i<tot; i++, bp++) {
1839                                 if (allverts || (bp->f1 & SELECT)) {
1840                                         MDeformWeight *dw;
1841
1842                                         dv= &lt->dvert[i];
1843
1844                                         dw = defvert_find_index(dv, def_nr);
1845                                         defvert_remove_group(dv, dw); /* dw can be NULL */
1846                                 }
1847                         }
1848                 }
1849         }
1850 }
1851
1852 static void vgroup_delete_edit_mode(Object *ob, bDeformGroup *dg)
1853 {
1854         int i;
1855         const int dg_index= BLI_findindex(&ob->defbase, dg);
1856
1857         assert(dg_index > -1);
1858
1859         /* Make sure that no verts are using this group */
1860         vgroup_active_remove_verts(ob, TRUE, dg);
1861
1862         /* Make sure that any verts with higher indices are adjusted accordingly */
1863         if (ob->type==OB_MESH) {
1864                 Mesh *me= ob->data;
1865                 BMEditMesh *em = me->edit_btmesh;
1866                 BMIter iter;
1867                 BMVert *eve;
1868                 MDeformVert *dvert;
1869                 
1870                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1871                         dvert= CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_MDEFORMVERT);
1872
1873                         if (dvert)
1874                                 for (i=0; i<dvert->totweight; i++)
1875                                         if (dvert->dw[i].def_nr > dg_index)
1876                                                 dvert->dw[i].def_nr--;
1877                 }
1878         }
1879         else if (ob->type==OB_LATTICE) {
1880                 Lattice *lt= vgroup_edit_lattice(ob);
1881                 BPoint *bp;
1882                 MDeformVert *dvert= lt->dvert;
1883                 int a, tot;
1884                 
1885                 if (dvert) {
1886                         tot= lt->pntsu*lt->pntsv*lt->pntsw;
1887                         for (a=0, bp= lt->def; a<tot; a++, bp++, dvert++) {
1888                                 for (i=0; i<dvert->totweight; i++) {
1889                                         if (dvert->dw[i].def_nr > dg_index)
1890                                                 dvert->dw[i].def_nr--;
1891                                 }
1892                         }
1893                 }
1894         }
1895
1896         vgroup_delete_update_users(ob, dg_index + 1);
1897
1898         /* Remove the group */
1899         BLI_freelinkN (&ob->defbase, dg);
1900
1901         /* Update the active deform index if necessary */
1902         if (ob->actdef > dg_index)
1903                 ob->actdef--;
1904         if (ob->actdef < 1 && ob->defbase.first)
1905                 ob->actdef= 1;
1906
1907         /* remove all dverts */
1908         if (ob->defbase.first == NULL) {
1909                 if (ob->type==OB_MESH) {
1910                         Mesh *me= ob->data;
1911                         CustomData_free_layer_active(&me->vdata, CD_MDEFORMVERT, me->totvert);
1912                         me->dvert= NULL;
1913                 }
1914                 else if (ob->type==OB_LATTICE) {
1915                         Lattice *lt= vgroup_edit_lattice(ob);
1916                         if (lt->dvert) {
1917                                 MEM_freeN(lt->dvert);
1918                                 lt->dvert= NULL;
1919                         }
1920                 }
1921         }
1922 }
1923
1924 static int vgroup_object_in_edit_mode(Object *ob)
1925 {
1926         if (ob->type == OB_MESH)
1927                 return (BMEdit_FromObject(ob) != NULL);
1928         else if (ob->type == OB_LATTICE)
1929                 return (((Lattice*)ob->data)->editlatt != NULL);
1930         
1931         return 0;
1932 }
1933
1934 static int vgroup_object_in_wpaint_vert_select(Object *ob)
1935 {
1936         if (ob->type == OB_MESH) {
1937                 Mesh *me = ob->data;
1938                 return ( (ob->mode & OB_MODE_WEIGHT_PAINT) &&
1939                          (me->edit_btmesh == NULL) &&
1940                          (ME_EDIT_PAINT_SEL_MODE(me) == SCE_SELECT_VERTEX) );
1941         }
1942
1943         return 0;
1944 }
1945
1946 static void vgroup_delete(Object *ob)
1947 {
1948         bDeformGroup *dg = BLI_findlink(&ob->defbase, ob->actdef-1);
1949         if (!dg)
1950                 return;
1951
1952         if (vgroup_object_in_edit_mode(ob))
1953                 vgroup_delete_edit_mode(ob, dg);
1954         else
1955                 vgroup_delete_object_mode(ob, dg);
1956 }
1957
1958 static void vgroup_delete_all(Object *ob)
1959 {
1960         /* Remove all DVerts */
1961         if (ob->type==OB_MESH) {
1962                 Mesh *me= ob->data;
1963                 CustomData_free_layer_active(&me->vdata, CD_MDEFORMVERT, me->totvert);
1964                 me->dvert= NULL;
1965         }
1966         else if (ob->type==OB_LATTICE) {
1967                 Lattice *lt= vgroup_edit_lattice(ob);
1968                 if (lt->dvert) {
1969                         MEM_freeN(lt->dvert);
1970                         lt->dvert= NULL;
1971                 }
1972         }
1973         
1974         /* Remove all DefGroups */
1975         BLI_freelistN(&ob->defbase);
1976         
1977         /* Fix counters/indices */
1978         ob->actdef= 0;
1979 }
1980
1981 /* only in editmode */
1982 static void vgroup_assign_verts(Object *ob, const float weight)
1983 {
1984         MDeformVert *dv;
1985         const int def_nr= ob->actdef-1;
1986
1987         if (!BLI_findlink(&ob->defbase, def_nr))
1988                 return;
1989
1990         if (ob->type == OB_MESH) {
1991                 Mesh *me= ob->data;
1992
1993                 if (me->edit_btmesh) {
1994                         BMEditMesh *em = me->edit_btmesh;
1995                         BMIter iter;
1996                         BMVert *eve;
1997
1998                         if (!CustomData_has_layer(&em->bm->vdata, CD_MDEFORMVERT))
1999                                 BM_data_layer_add(em->bm, &em->bm->vdata, CD_MDEFORMVERT);
2000
2001                         /* Go through the list of editverts and assign them */
2002                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2003                                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
2004                                         MDeformWeight *dw;
2005                                         dv= CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_MDEFORMVERT); /* can be NULL */
2006                                         dw= defvert_verify_index(dv, def_nr);
2007                                         if (dw) {
2008                                                 dw->weight= weight;
2009                                         }
2010                                 }
2011                         }
2012                 }
2013                 else {
2014                         MVert *mv;
2015                         MDeformVert *dv;
2016                         int i;
2017
2018                         if (!me->dvert) {
2019                                 ED_vgroup_data_create(&me->id);
2020                         }
2021
2022                         mv = me->mvert;
2023                         dv = me->dvert;
2024
2025                         for (i=0; i<me->totvert; i++, mv++, dv++) {
2026                                 if (mv->flag & SELECT) {
2027                                         MDeformWeight *dw;
2028                                         dw= defvert_verify_index(dv, def_nr);
2029                                         if (dw) {
2030                                                 dw->weight= weight;
2031                                         }
2032                                 }
2033                         }
2034                 }
2035         }
2036         else if (ob->type == OB_LATTICE) {
2037                 Lattice *lt= vgroup_edit_lattice(ob);
2038                 BPoint *bp;
2039                 int a, tot;
2040
2041                 if (lt->dvert==NULL)
2042                         ED_vgroup_data_create(&lt->id);
2043
2044                 dv= lt->dvert;
2045
2046                 tot= lt->pntsu*lt->pntsv*lt->pntsw;
2047                 for (a=0, bp= lt->def; a<tot; a++, bp++, dv++) {
2048                         if (bp->f1 & SELECT) {
2049                                 MDeformWeight *dw;
2050
2051                                 dw= defvert_verify_index(dv, def_nr);
2052                                 if (dw) {
2053                                         dw->weight= weight;
2054                                 }
2055                         }
2056                 }
2057         }
2058 }
2059
2060 /* only in editmode */
2061 /* removes from all defgroup, if allverts==0 only selected vertices */
2062 static void vgroup_remove_verts(Object *ob, int allverts)
2063 {
2064         /* To prevent code redundancy, we just use vgroup_active_remove_verts, but that
2065          * only operates on the active vgroup. So we iterate through all groups, by changing
2066          * active group index
2067          */
2068         bDeformGroup *dg;
2069         for (dg= ob->defbase.first; dg; dg= dg->next) {
2070                 vgroup_active_remove_verts(ob, allverts, dg);
2071         }
2072 }
2073
2074 /********************** vertex group operators *********************/
2075
2076 static int vertex_group_poll(bContext *C)
2077 {
2078         Object *ob= ED_object_context(C);
2079         ID *data= (ob)? ob->data: NULL;
2080         return (ob && !ob->id.lib && OB_TYPE_SUPPORT_VGROUP(ob->type) && data && !data->lib);
2081 }
2082
2083 static int UNUSED_FUNCTION(vertex_group_poll_edit)(bContext *C)
2084 {
2085         Object *ob= ED_object_context(C);
2086         ID *data= (ob)? ob->data: NULL;
2087
2088         if (!(ob && !ob->id.lib && data && !data->lib))
2089                 return 0;
2090
2091         return vgroup_object_in_edit_mode(ob);
2092 }
2093
2094 /* editmode _or_ weight paint vertex sel */
2095 static int vertex_group_poll_edit_or_wpaint_vert_select(bContext *C)
2096 {
2097         Object *ob= ED_object_context(C);
2098         ID *data= (ob)? ob->data: NULL;
2099
2100         if (!(ob && !ob->id.lib && data && !data->lib))
2101                 return 0;
2102
2103         return ( vgroup_object_in_edit_mode(ob) ||
2104                  vgroup_object_in_wpaint_vert_select(ob) );
2105 }
2106
2107 static int vertex_group_add_exec(bContext *C, wmOperator *UNUSED(op))
2108 {
2109         Object *ob= ED_object_context(C);
2110
2111         ED_vgroup_add(ob);
2112         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2113         WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob->data);
2114         WM_event_add_notifier(C, NC_OBJECT|ND_DRAW, ob);
2115         
2116         return OPERATOR_FINISHED;
2117 }
2118
2119 void OBJECT_OT_vertex_group_add(wmOperatorType *ot)
2120 {
2121         /* identifiers */
2122         ot->name = "Add Vertex Group";
2123         ot->idname = "OBJECT_OT_vertex_group_add";
2124         
2125         /* api callbacks */
2126         ot->poll = vertex_group_poll;
2127         ot->exec = vertex_group_add_exec;
2128
2129         /* flags */
2130         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2131 }
2132
2133 static int vertex_group_remove_exec(bContext *C, wmOperator *op)
2134 {
2135         Object *ob= ED_object_context(C);
2136
2137         if (RNA_boolean_get(op->ptr, "all"))
2138                 vgroup_delete_all(ob);
2139         else
2140                 vgroup_delete(ob);
2141
2142         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2143         WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob->data);
2144         WM_event_add_notifier(C, NC_OBJECT|ND_DRAW, ob);
2145         
2146         return OPERATOR_FINISHED;
2147 }
2148
2149 void OBJECT_OT_vertex_group_remove(wmOperatorType *ot)
2150 {
2151         /* identifiers */
2152         ot->name = "Remove Vertex Group";
2153         ot->idname = "OBJECT_OT_vertex_group_remove";
2154         
2155         /* api callbacks */
2156         ot->poll = vertex_group_poll;
2157         ot->exec = vertex_group_remove_exec;
2158
2159         /* flags */
2160         /* redo operator will fail in this case because vertex groups aren't stored
2161          * in local edit mode stack and toggling "all" property will lead to
2162          * all groups deleted without way to restore them (see [#29527], sergey) */
2163         ot->flag = /*OPTYPE_REGISTER|*/OPTYPE_UNDO;
2164
2165         /* properties */
2166         RNA_def_boolean(ot->srna, "all", 0, "All", "Remove from all vertex groups");
2167 }
2168
2169 static int vertex_group_assign_exec(bContext *C, wmOperator *op)
2170 {
2171         ToolSettings *ts= CTX_data_tool_settings(C);
2172         Object *ob= ED_object_context(C);
2173
2174         if (RNA_boolean_get(op->ptr, "new"))
2175                 ED_vgroup_add(ob);
2176
2177         vgroup_assign_verts(ob, ts->vgroup_weight);
2178         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2179         WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob->data);
2180         
2181         return OPERATOR_FINISHED;
2182 }
2183
2184 void OBJECT_OT_vertex_group_assign(wmOperatorType *ot)
2185 {
2186         /* identifiers */
2187         ot->name = "Assign Vertex Group";
2188         ot->idname = "OBJECT_OT_vertex_group_assign";
2189         
2190         /* api callbacks */
2191         ot->poll = vertex_group_poll_edit_or_wpaint_vert_select;
2192         ot->exec = vertex_group_assign_exec;
2193
2194         /* flags */
2195         /* redo operator will fail in this case because vertex group assignment
2196          * isn't stored in local edit mode stack and toggling "new" property will
2197          * lead to creating plenty of new vertex groups (see [#29527], sergey) */
2198         ot->flag = /*OPTYPE_REGISTER|*/OPTYPE_UNDO;
2199
2200         /* properties */
2201         RNA_def_boolean(ot->srna, "new", 0, "New", "Assign vertex to new vertex group");
2202 }
2203
2204 static int vertex_group_remove_from_exec(bContext *C, wmOperator *op)
2205 {
2206         Object *ob= ED_object_context(C);
2207
2208         if (RNA_boolean_get(op->ptr, "all"))
2209                 vgroup_remove_verts(ob, 0);
2210         else {
2211                 bDeformGroup *dg= BLI_findlink(&ob->defbase, ob->actdef - 1);
2212
2213                 if (dg == NULL) {
2214                         return OPERATOR_CANCELLED;
2215                 }
2216
2217                 vgroup_active_remove_verts(ob, FALSE, dg);
2218         }
2219
2220         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2221         WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob->data);
2222
2223         return OPERATOR_FINISHED;
2224 }
2225
2226 void OBJECT_OT_vertex_group_remove_from(wmOperatorType *ot)
2227 {
2228         /* identifiers */
2229         ot->name = "Remove from Vertex Group";
2230         ot->idname = "OBJECT_OT_vertex_group_remove_from";
2231
2232         /* api callbacks */
2233         ot->poll = vertex_group_poll_edit_or_wpaint_vert_select;
2234         ot->exec = vertex_group_remove_from_exec;
2235
2236         /* flags */
2237         /* redo operator will fail in this case because vertex groups assignment
2238          * isn't stored in local edit mode stack and toggling "all" property will lead to
2239          * removing vertices from all groups (see [#29527], sergey) */
2240         ot->flag = /*OPTYPE_REGISTER|*/OPTYPE_UNDO;
2241
2242         /* properties */
2243         RNA_def_boolean(ot->srna, "all", 0, "All", "Remove from all vertex groups");
2244 }
2245
2246 static int vertex_group_select_exec(bContext *C, wmOperator *UNUSED(op))
2247 {
2248         Object *ob= ED_object_context(C);
2249
2250         if (!ob || ob->id.lib)
2251                 return OPERATOR_CANCELLED;
2252
2253         vgroup_select_verts(ob, 1);
2254         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, ob->data);
2255
2256         return OPERATOR_FINISHED;
2257 }
2258
2259 void OBJECT_OT_vertex_group_select(wmOperatorType *ot)
2260 {
2261         /* identifiers */
2262         ot->name = "Select Vertex Group";
2263         ot->idname = "OBJECT_OT_vertex_group_select";
2264
2265         /* api callbacks */
2266         ot->poll = vertex_group_poll_edit_or_wpaint_vert_select;
2267         ot->exec = vertex_group_select_exec;
2268
2269         /* flags */
2270         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2271 }
2272
2273 static int vertex_group_deselect_exec(bContext *C, wmOperator *UNUSED(op))
2274 {
2275         Object *ob= ED_object_context(C);
2276
2277         vgroup_select_verts(ob, 0);
2278         WM_event_add_notifier(C, NC_GEOM|ND_SELECT, ob->data);
2279
2280         return OPERATOR_FINISHED;
2281 }
2282
2283 void OBJECT_OT_vertex_group_deselect(wmOperatorType *ot)
2284 {
2285         /* identifiers */
2286         ot->name = "Deselect Vertex Group";
2287         ot->idname = "OBJECT_OT_vertex_group_deselect";
2288
2289         /* api callbacks */
2290         ot->poll = vertex_group_poll_edit_or_wpaint_vert_select;
2291         ot->exec = vertex_group_deselect_exec;
2292
2293         /* flags */
2294         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2295 }
2296
2297 static int vertex_group_copy_exec(bContext *C, wmOperator *UNUSED(op))
2298 {
2299         Object *ob= ED_object_context(C);
2300
2301         vgroup_duplicate(ob);
2302         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2303         WM_event_add_notifier(C, NC_OBJECT|ND_DRAW, ob);
2304         WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob->data);
2305
2306         return OPERATOR_FINISHED;
2307 }
2308
2309 void OBJECT_OT_vertex_group_copy(wmOperatorType *ot)
2310 {
2311         /* identifiers */
2312         ot->name = "Copy Vertex Group";
2313         ot->idname = "OBJECT_OT_vertex_group_copy";
2314
2315         /* api callbacks */
2316         ot->poll = vertex_group_poll;
2317         ot->exec = vertex_group_copy_exec;
2318
2319         /* flags */
2320         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2321 }
2322
2323 static int vertex_group_levels_exec(bContext *C, wmOperator *op)
2324 {
2325         Object *ob= ED_object_context(C);
2326         
2327         float offset= RNA_float_get(op->ptr,"offset");
2328         float gain= RNA_float_get(op->ptr,"gain");
2329         
2330         vgroup_levels(ob, offset, gain);
2331         
2332         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2333         WM_event_add_notifier(C, NC_OBJECT|ND_DRAW, ob);
2334         WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob->data);
2335         
2336         return OPERATOR_FINISHED;
2337 }
2338
2339 void OBJECT_OT_vertex_group_levels(wmOperatorType *ot)
2340 {
2341         /* identifiers */
2342         ot->name = "Vertex Group Levels";
2343         ot->idname = "OBJECT_OT_vertex_group_levels";
2344         
2345         /* api callbacks */
2346         ot->poll = vertex_group_poll;
2347         ot->exec = vertex_group_levels_exec;
2348         
2349         /* flags */
2350         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2351         
2352         RNA_def_float(ot->srna, "offset", 0.f, -1.0, 1.0, "Offset", "Value to add to weights", -1.0f, 1.f);
2353         RNA_def_float(ot->srna, "gain", 1.f, 0.f, FLT_MAX, "Gain", "Value to multiply weights by", 0.0f, 10.f);
2354 }
2355
2356 static int vertex_group_normalize_exec(bContext *C, wmOperator *UNUSED(op))
2357 {
2358         Object *ob= ED_object_context(C);
2359
2360         vgroup_normalize(ob);
2361
2362         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2363         WM_event_add_notifier(C, NC_OBJECT|ND_DRAW, ob);
2364         WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob->data);
2365
2366         return OPERATOR_FINISHED;
2367 }
2368
2369 void OBJECT_OT_vertex_group_normalize(wmOperatorType *ot)
2370 {
2371         /* identifiers */
2372         ot->name = "Normalize Vertex Group";
2373         ot->idname = "OBJECT_OT_vertex_group_normalize";
2374
2375         /* api callbacks */
2376         ot->poll = vertex_group_poll;
2377         ot->exec = vertex_group_normalize_exec;
2378
2379         /* flags */
2380         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2381 }
2382
2383 static int vertex_group_normalize_all_exec(bContext *C, wmOperator *op)
2384 {
2385         Object *ob= ED_object_context(C);
2386         int lock_active= RNA_boolean_get(op->ptr,"lock_active");
2387
2388         vgroup_normalize_all(ob, lock_active);
2389
2390         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2391         WM_event_add_notifier(C, NC_OBJECT|ND_DRAW, ob);
2392         WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob->data);
2393
2394         return OPERATOR_FINISHED;
2395 }
2396
2397 void OBJECT_OT_vertex_group_normalize_all(wmOperatorType *ot)
2398 {
2399         /* identifiers */
2400         ot->name = "Normalize All Vertex Groups";
2401         ot->idname = "OBJECT_OT_vertex_group_normalize_all";
2402
2403         /* api callbacks */
2404         ot->poll = vertex_group_poll;
2405         ot->exec = vertex_group_normalize_all_exec;
2406
2407         /* flags */
2408         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2409
2410         RNA_def_boolean(ot->srna, "lock_active", TRUE, "Lock Active",
2411                         "Keep the values of the active group while normalizing others");
2412 }
2413
2414 static int vertex_group_fix_exec(bContext *C, wmOperator *op)
2415 {
2416         Object *ob= CTX_data_active_object(C);
2417         Scene *scene= CTX_data_scene(C);
2418         
2419         float distToBe= RNA_float_get(op->ptr, "dist");
2420         float strength= RNA_float_get(op->ptr, "strength");
2421         float cp= RNA_float_get(op->ptr, "accuracy");
2422         ModifierData *md= ob->modifiers.first;
2423
2424         while (md) {
2425                 if (md->type == eModifierType_Mirror && (md->mode&eModifierMode_Realtime)) {
2426                         break;
2427                 }
2428                 md = md->next;
2429         }
2430         
2431         if (md && md->type == eModifierType_Mirror) {
2432                 BKE_report(op->reports, RPT_ERROR_INVALID_CONTEXT, "This operator does not support an active mirror modifier");
2433                 return OPERATOR_CANCELLED;
2434         }
2435         vgroup_fix(scene, ob, distToBe, strength, cp);
2436         
2437         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2438         WM_event_add_notifier(C, NC_OBJECT|ND_DRAW, ob);
2439         WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob->data);
2440         
2441         return OPERATOR_FINISHED;
2442 }
2443
2444 void OBJECT_OT_vertex_group_fix(wmOperatorType *ot)
2445 {
2446         /* identifiers */
2447         ot->name = "Fix Vertex Group Deform";
2448         ot->idname = "OBJECT_OT_vertex_group_fix";
2449         ot->description = "Modify the position of selected vertices by changing only their respective "
2450                          "groups' weights (this tool may be slow for many vertices)";
2451         
2452         /* api callbacks */
2453         ot->poll = vertex_group_poll;
2454         ot->exec = vertex_group_fix_exec;
2455         
2456         /* flags */
2457         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2458         RNA_def_float(ot->srna, "dist", 0.0f, -FLT_MAX, FLT_MAX, "Distance", "The distance to move to", -10.0f, 10.0f);
2459         RNA_def_float(ot->srna, "strength", 1.f, -2.0f, FLT_MAX, "Strength",
2460                       "The distance moved can be changed by this multiplier", -2.0f, 2.0f);
2461         RNA_def_float(ot->srna, "accuracy", 1.0f, 0.05f, FLT_MAX, "Change Sensitivity",
2462                       "Change the amount weights are altered with each iteration: lower values are slower", 0.05f, 1.f);
2463 }
2464
2465
2466 static int vertex_group_lock_exec(bContext *C, wmOperator *op)
2467 {
2468         Object *ob= CTX_data_active_object(C);
2469
2470         int action = RNA_enum_get(op->ptr, "action");
2471
2472         vgroup_lock_all(ob, action);
2473
2474         return OPERATOR_FINISHED;
2475 }
2476
2477 void OBJECT_OT_vertex_group_lock(wmOperatorType *ot)
2478 {
2479         /* identifiers */
2480         ot->name = "Change the Lock On Vertex Groups";
2481         ot->idname = "OBJECT_OT_vertex_group_lock";
2482
2483         /* api callbacks */
2484         ot->poll = vertex_group_poll;
2485         ot->exec = vertex_group_lock_exec;
2486
2487         /* flags */
2488         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2489
2490         WM_operator_properties_select_all(ot);
2491 }
2492
2493 static int vertex_group_invert_exec(bContext *C, wmOperator *op)
2494 {
2495         Object *ob= ED_object_context(C);
2496         int auto_assign= RNA_boolean_get(op->ptr,"auto_assign");
2497         int auto_remove= RNA_boolean_get(op->ptr,"auto_remove");
2498
2499         vgroup_invert(ob, auto_assign, auto_remove);
2500         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2501         WM_event_add_notifier(C, NC_OBJECT|ND_DRAW, ob);
2502         WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob->data);
2503
2504         return OPERATOR_FINISHED;
2505 }
2506
2507 void OBJECT_OT_vertex_group_invert(wmOperatorType *ot)
2508 {
2509         /* identifiers */
2510         ot->name = "Invert Vertex Group";
2511         ot->idname = "OBJECT_OT_vertex_group_invert";
2512
2513         /* api callbacks */
2514         ot->poll = vertex_group_poll;
2515         ot->exec = vertex_group_invert_exec;
2516
2517         /* flags */
2518         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2519
2520         RNA_def_boolean(ot->srna, "auto_assign", TRUE, "Add Weights",
2521                         "Add verts from groups that have zero weight before inverting");
2522         RNA_def_boolean(ot->srna, "auto_remove", TRUE, "Remove Weights",
2523                         "Remove verts from groups that have zero weight after inverting");
2524 }
2525
2526
2527 static int vertex_group_blend_exec(bContext *C, wmOperator *op)
2528 {
2529         Object *ob = ED_object_context(C);
2530         float fac = RNA_float_get(op->ptr, "factor");
2531
2532         vgroup_blend(ob, fac);
2533
2534         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2535         WM_event_add_notifier(C, NC_OBJECT|ND_DRAW, ob);
2536         WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob->data);
2537
2538         return OPERATOR_FINISHED;
2539 }
2540
2541 /* check we have a vertex selection, either in weight paint or editmode */
2542 static int vertex_group_blend_poll(bContext *C)
2543 {
2544         Object *ob = ED_object_context(C);
2545         ID *data = (ob) ? ob->data: NULL;
2546
2547         if (!(ob && !ob->id.lib && data && !data->lib))
2548                 return FALSE;
2549
2550         if (vgroup_object_in_edit_mode(ob)) {
2551                 return TRUE;
2552         }
2553         else if ((ob->type == OB_MESH) && (ob->mode & OB_MODE_WEIGHT_PAINT)) {
2554                 if (ME_EDIT_PAINT_SEL_MODE(((Mesh *)data)) == SCE_SELECT_VERTEX) {
2555                         return TRUE;
2556                 }
2557                 else {
2558                         CTX_wm_operator_poll_msg_set(C, "Vertex select needs to be enabled in weight paint mode");
2559                         return FALSE;
2560                 }
2561
2562         }
2563         else {
2564                 return FALSE;
2565         }
2566 }
2567
2568 void OBJECT_OT_vertex_group_blend(wmOperatorType *ot)
2569 {
2570         PropertyRNA *prop;
2571
2572         /* identifiers */
2573         ot->name = "Blend Vertex Group";
2574         ot->idname = "OBJECT_OT_vertex_group_blend";
2575         ot->description = "Blend selected vertex weights with unselected for the active group";
2576
2577         /* api callbacks */
2578         ot->poll = vertex_group_blend_poll;
2579         ot->exec = vertex_group_blend_exec;
2580
2581         /* flags */
2582         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2583
2584         prop = RNA_def_property(ot->srna, "factor", PROP_FLOAT, PROP_FACTOR);
2585         RNA_def_property_ui_text(prop, "Factor", "");
2586         RNA_def_property_range(prop, 0.0f, 1.0f);
2587         RNA_def_property_float_default(prop, 1.0f);
2588 }
2589
2590
2591 static int vertex_group_clean_exec(bContext *C, wmOperator *op)
2592 {
2593         Object *ob= ED_object_context(C);
2594
2595         float limit= RNA_float_get(op->ptr,"limit");
2596         int all_groups= RNA_boolean_get(op->ptr,"all_groups");
2597         int keep_single= RNA_boolean_get(op->ptr,"keep_single");
2598
2599         if (all_groups) vgroup_clean_all(ob, limit, keep_single);
2600         else                    vgroup_clean(ob, limit, keep_single);
2601
2602         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2603         WM_event_add_notifier(C, NC_OBJECT|ND_DRAW, ob);
2604         WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob->data);
2605
2606         return OPERATOR_FINISHED;
2607 }
2608
2609 void OBJECT_OT_vertex_group_clean(wmOperatorType *ot)
2610 {
2611         /* identifiers */
2612         ot->name = "Clean Vertex Group";
2613         ot->idname = "OBJECT_OT_vertex_group_clean";
2614         ot->description = "Remove Vertex Group assignments which aren't required";
2615
2616         /* api callbacks */
2617         ot->poll = vertex_group_poll;
2618         ot->exec = vertex_group_clean_exec;
2619
2620         /* flags */
2621         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2622
2623         RNA_def_float(ot->srna, "limit", 0.01f, 0.0f, 1.0, "Limit", "Remove weights under this limit", 0.001f, 0.99f);
2624         RNA_def_boolean(ot->srna, "all_groups", FALSE, "All Groups", "Clean all vertex groups");
2625         RNA_def_boolean(ot->srna, "keep_single", FALSE, "Keep Single",
2626                         "Keep verts assigned to at least one group when cleaning");
2627 }
2628
2629
2630 static int vertex_group_mirror_exec(bContext *C, wmOperator *op)
2631 {
2632         Object *ob= ED_object_context(C);
2633
2634         ED_vgroup_mirror(ob,
2635                          RNA_boolean_get(op->ptr,"mirror_weights"),
2636                          RNA_boolean_get(op->ptr,"flip_group_names"),
2637                          RNA_boolean_get(op->ptr,"all_groups"));
2638
2639         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2640         WM_event_add_notifier(C, NC_OBJECT|ND_DRAW, ob);
2641         WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob->data);
2642
2643         return OPERATOR_FINISHED;
2644 }
2645
2646 void OBJECT_OT_vertex_group_mirror(wmOperatorType *ot)
2647 {
2648         /* identifiers */
2649         ot->name = "Mirror Vertex Group";
2650         ot->idname = "OBJECT_OT_vertex_group_mirror";
2651         ot->description = "Mirror all vertex groups, flip weights and/or names, editing only selected vertices, "
2652                          "flipping when both sides are selected otherwise copy from unselected";
2653
2654         /* api callbacks */
2655         ot->poll = vertex_group_poll;
2656         ot->exec = vertex_group_mirror_exec;
2657
2658         /* flags */
2659         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2660
2661         /* properties */
2662         RNA_def_boolean(ot->srna, "mirror_weights", TRUE, "Mirror Weights", "Mirror weights");
2663         RNA_def_boolean(ot->srna, "flip_group_names", TRUE, "Flip Groups", "Flip vertex group names");
2664         RNA_def_boolean(ot->srna, "all_groups", FALSE, "All Groups", "Mirror all vertex groups weights");
2665
2666 }
2667
2668 static int vertex_group_copy_to_linked_exec(bContext *C, wmOperator *UNUSED(op))
2669 {
2670         Scene *scene= CTX_data_scene(C);
2671         Object *ob= ED_object_context(C);
2672         Base *base;
2673         int retval= OPERATOR_CANCELLED;
2674
2675         for (base=scene->base.first; base; base= base->next) {
2676                 if (base->object->type==ob->type) {
2677                         if (base->object!=ob && base->object->data==ob->data) {
2678                                 BLI_freelistN(&base->object->defbase);
2679                                 BLI_duplicatelist(&base->object->defbase, &ob->defbase);
2680                                 base->object->actdef= ob->actdef;
2681
2682                                 DAG_id_tag_update(&base->object->id, OB_RECALC_DATA);
2683                                 WM_event_add_notifier(C, NC_OBJECT|ND_DRAW, base->object);
2684                                 WM_event_add_notifier(C, NC_GEOM|ND_DATA, base->object->data);
2685
2686                                 retval = OPERATOR_FINISHED;
2687                         }
2688                 }
2689         }
2690
2691         return retval;
2692 }
2693
2694 void OBJECT_OT_vertex_group_copy_to_linked(wmOperatorType *ot)
2695 {
2696         /* identifiers */
2697         ot->name = "Copy Vertex Groups to Linked";
2698         ot->idname = "OBJECT_OT_vertex_group_copy_to_linked";
2699         ot->description = "Copy Vertex Groups to all users of the same Geometry data";
2700
2701         /* api callbacks */
2702         ot->poll = vertex_group_poll;
2703         ot->exec = vertex_group_copy_to_linked_exec;
2704
2705         /* flags */
2706         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2707 }
2708
2709 static int vertex_group_copy_to_selected_exec(bContext *C, wmOperator *op)
2710 {
2711         Object *obact= ED_object_context(C);
2712         int change= 0;
2713         int fail= 0;
2714
2715         CTX_DATA_BEGIN(C, Object*, ob, selected_editable_objects)
2716         {
2717                 if (obact != ob) {
2718                         if (ED_vgroup_copy_array(ob, obact)) change++;
2719                         else                                fail++;
2720                 }
2721         }
2722         CTX_DATA_END;
2723
2724         if ((change == 0 && fail == 0) || fail) {
2725                 BKE_reportf(op->reports, RPT_ERROR,
2726                             "Copy to VGroups to Selected warning done %d, failed %d, object data must have matching indices",
2727                             change, fail);
2728         }
2729
2730         return OPERATOR_FINISHED;
2731 }
2732
2733
2734 void OBJECT_OT_vertex_group_copy_to_selected(wmOperatorType *ot)
2735 {
2736         /* identifiers */
2737         ot->name = "Copy Vertex Group to Selected";
2738         ot->idname = "OBJECT_OT_vertex_group_copy_to_selected";
2739         ot->description = "Copy Vertex Groups to other selected objects with matching indices";
2740
2741         /* api callbacks */
2742         ot->poll = vertex_group_poll;
2743         ot->exec = vertex_group_copy_to_selected_exec;
2744
2745         /* flags */
2746         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2747 }
2748
2749 static EnumPropertyItem vgroup_items[]= {
2750         {0, NULL, 0, NULL, NULL}};
2751
2752 static int set_active_group_exec(bContext *C, wmOperator *op)
2753 {
2754         Object *ob= ED_object_context(C);
2755         int nr= RNA_enum_get(op->ptr, "group");
2756
2757         BLI_assert(nr+1 >= 0);
2758         ob->actdef= nr+1;
2759
2760         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2761         WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob);
2762
2763         return OPERATOR_FINISHED;
2764 }
2765
2766 static EnumPropertyItem *vgroup_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), int *free)
2767 {       
2768         Object *ob= ED_object_context(C);
2769         EnumPropertyItem tmp = {0, "", 0, "", ""};
2770         EnumPropertyItem *item= NULL;
2771         bDeformGroup *def;
2772         int a, totitem= 0;
2773         
2774         if (!ob)
2775                 return vgroup_items;
2776         
2777         for (a=0, def=ob->defbase.first; def; def=def->next, a++) {
2778                 tmp.value= a;
2779                 tmp.icon= ICON_GROUP_VERTEX;
2780                 tmp.identifier= def->name;
2781                 tmp.name= def->name;
2782                 RNA_enum_item_add(&item, &totitem, &tmp);
2783         }
2784
2785         RNA_enum_item_end(&item, &totitem);
2786         *free= 1;
2787
2788         return item;
2789 }
2790
2791 void OBJECT_OT_vertex_group_set_active(wmOperatorType *ot)
2792 {
2793         PropertyRNA *prop;
2794
2795         /* identifiers */
2796         ot->name = "Set Active Vertex Group";
2797         ot->idname = "OBJECT_OT_vertex_group_set_active";
2798         ot->description = "Set the active vertex group";
2799
2800         /* api callbacks */
2801         ot->poll = vertex_group_poll;
2802         ot->exec = set_active_group_exec;
2803         ot->invoke = WM_menu_invoke;
2804
2805         /* flags */
2806         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2807
2808         /* properties */
2809         prop= RNA_def_enum(ot->srna, "group", vgroup_items, 0, "Group", "Vertex group to set as active");
2810         RNA_def_enum_funcs(prop, vgroup_itemf);
2811         ot->prop = prop;
2812 }
2813
2814 /* creates the name_array parameter for vgroup_do_remap, call this before fiddling
2815  * with the order of vgroups then call vgroup_do_remap after*/
2816 static char *vgroup_init_remap(Object *ob)
2817 {
2818         bDeformGroup *def;
2819         int defbase_tot = BLI_countlist(&ob->defbase);
2820         char *name_array= MEM_mallocN(MAX_VGROUP_NAME * sizeof(char) * defbase_tot, "sort vgroups");
2821         char *name;
2822
2823         name= name_array;
2824         for (def = ob->defbase.first; def; def=def->next) {
2825                 BLI_strncpy(name, def->name, MAX_VGROUP_NAME);
2826                 name += MAX_VGROUP_NAME;
2827         }
2828
2829         return name_array;
2830 }
2831
2832 static int vgroup_do_remap(Object *ob, char *name_array, wmOperator *op)
2833 {
2834         MDeformVert *dvert= NULL;
2835         bDeformGroup *def;
2836         int defbase_tot = BLI_countlist(&ob->defbase);
2837
2838         /* needs a dummy index at the start*/
2839         int *sort_map_update= MEM_mallocN(sizeof(int) * (defbase_tot + 1), "sort vgroups");
2840         int *sort_map= sort_map_update + 1;
2841
2842         char *name;
2843         int i;
2844
2845         name= name_array;
2846         for (def= ob->defbase.first, i=0; def; def=def->next, i++) {
2847                 sort_map[i]= BLI_findstringindex(&ob->defbase, name, offsetof(bDeformGroup, name));
2848                 name += MAX_VGROUP_NAME;
2849
2850                 BLI_assert(sort_map[i] != -1);
2851         }
2852
2853         if (ob->mode == OB_MODE_EDIT) {
2854                 if (ob->type==OB_MESH) {
2855                         BMEditMesh *em = BMEdit_FromObject(ob);
2856                         BMIter iter;
2857                         BMVert *eve;
2858
2859                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2860                                 dvert= CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_MDEFORMVERT);
2861                                 if (dvert && dvert->totweight) {
2862                                         defvert_remap(dvert, sort_map, defbase_tot);
2863                                 }
2864                         }
2865                 }
2866                 else {
2867                         BKE_report(op->reports, RPT_ERROR, "Editmode lattice isn't supported yet");
2868                         MEM_freeN(sort_map_update);
2869                         return OPERATOR_CANCELLED;
2870                 }
2871         }
2872         else {
2873                 int dvert_tot=0;
2874
2875                 ED_vgroup_give_array(ob->data, &dvert, &dvert_tot);
2876
2877                 /*create as necessary*/
2878                 while (dvert && dvert_tot--) {
2879                         if (dvert->totweight)
2880                                 defvert_remap(dvert, sort_map, defbase_tot);
2881                         dvert++;
2882                 }
2883         }
2884
2885         /* update users */
2886         for (i=0; i<defbase_tot; i++)
2887                 sort_map[i]++;
2888
2889         sort_map_update[0]= 0;
2890         vgroup_remap_update_users(ob, sort_map_update);
2891
2892         BLI_assert(sort_map_update[ob->actdef] >= 0);
2893         ob->actdef= sort_map_update[ob->actdef];
2894         
2895         MEM_freeN(sort_map_update);
2896
2897         return OPERATOR_FINISHED;
2898 }
2899
2900 static int vgroup_sort(void *def_a_ptr, void *def_b_ptr)
2901 {
2902         bDeformGroup *def_a= (bDeformGroup *)def_a_ptr;
2903         bDeformGroup *def_b= (bDeformGroup *)def_b_ptr;
2904
2905         return BLI_natstrcmp(def_a->name, def_b->name);
2906 }
2907
2908 static int vertex_group_sort_exec(bContext *C, wmOperator *op)
2909 {
2910         Object *ob= ED_object_context(C);
2911         char *name_array;
2912         int ret;
2913
2914         /*init remapping*/
2915         name_array = vgroup_init_remap(ob);
2916
2917         /*sort vgroup names*/
2918         BLI_sortlist(&ob->defbase, vgroup_sort);
2919
2920         /*remap vgroup data to map to correct names*/
2921         ret = vgroup_do_remap(ob, name_array, op);
2922
2923         if (ret != OPERATOR_CANCELLED) {
2924                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2925                 WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob);
2926         }
2927
2928         if (name_array) MEM_freeN(name_array);
2929
2930         return ret;
2931 }
2932
2933 void OBJECT_OT_vertex_group_sort(wmOperatorType *ot)
2934 {
2935         ot->name = "Sort Vertex Groups";
2936         ot->idname = "OBJECT_OT_vertex_group_sort";
2937         ot->description = "Sorts vertex groups alphabetically";
2938
2939         /* api callbacks */
2940         ot->poll = vertex_group_poll;
2941         ot->exec = vertex_group_sort_exec;
2942
2943         /* flags */
2944         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2945 }
2946
2947 static int vgroup_move_exec(bContext *C, wmOperator *op)
2948 {
2949         Object *ob= ED_object_context(C);
2950         bDeformGroup *def;
2951         char *name_array;
2952         int dir= RNA_enum_get(op->ptr, "direction"), ret;
2953
2954         def = BLI_findlink(&ob->defbase, ob->actdef - 1);
2955         if (!def) {
2956                 return OPERATOR_CANCELLED;
2957         }
2958
2959         name_array = vgroup_init_remap(ob);
2960
2961         if (dir == 1) { /*up*/
2962                 void *prev = def->prev;
2963
2964                 BLI_remlink(&ob->defbase, def);
2965                 BLI_insertlinkbefore(&ob->defbase, prev, def);
2966         }
2967         else { /*down*/
2968                 void *next = def->next;
2969
2970                 BLI_remlink(&ob->defbase, def);
2971                 BLI_insertlinkafter(&ob->defbase, next, def);
2972         }
2973
2974         ret = vgroup_do_remap(ob, name_array, op);
2975
2976         if (name_array) MEM_freeN(name_array);
2977
2978         if (ret != OPERATOR_CANCELLED) {
2979                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2980                 WM_event_add_notifier(C, NC_GEOM|ND_DATA, ob);
2981         }
2982
2983         return ret;
2984 }
2985
2986 void OBJECT_OT_vertex_group_move(wmOperatorType *ot)
2987 {
2988         static EnumPropertyItem vgroup_slot_move[] = {
2989                 {1, "UP", 0, "Up", ""},
2990                 {-1, "DOWN", 0, "Down", ""},
2991                 {0, NULL, 0, NULL, NULL}
2992         };
2993
2994         /* identifiers */
2995         ot->name = "Move Vertex Group";
2996         ot->idname = "OBJECT_OT_vertex_group_move";
2997
2998         /* api callbacks */
2999         ot->poll = vertex_group_poll;
3000         ot->exec = vgroup_move_exec;
3001
3002         /* flags */
3003         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
3004
3005         RNA_def_enum(ot->srna, "direction", vgroup_slot_move, 0, "Direction", "Direction to move, UP or DOWN");
3006 }