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