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