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