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