Fix T52176: Bevel doesn't correctly work with default empty Vgroup.
[blender.git] / source / blender / blenkernel / intern / deform.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): Reevan McKay
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/deform.c
29  *  \ingroup bke
30  */
31
32
33 #include <string.h>
34 #include <math.h>
35 #include <ctype.h>
36 #include <stdlib.h>
37 #include <stddef.h>
38
39 #include "MEM_guardedalloc.h"
40
41 #include "DNA_meshdata_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_scene_types.h"
45
46 #include "BLI_listbase.h"
47 #include "BLI_math.h"
48 #include "BLI_string.h"
49 #include "BLI_string_utils.h"
50 #include "BLI_utildefines.h"
51
52 #include "BLT_translation.h"
53
54 #include "BKE_customdata.h"
55 #include "BKE_data_transfer.h"
56 #include "BKE_deform.h"  /* own include */
57 #include "BKE_mesh_mapping.h"
58 #include "BKE_object_deform.h"
59
60 #include "data_transfer_intern.h"
61
62
63 bDeformGroup *BKE_defgroup_new(Object *ob, const char *name)
64 {
65         bDeformGroup *defgroup;
66
67         BLI_assert(OB_TYPE_SUPPORT_VGROUP(ob->type));
68
69         defgroup = MEM_callocN(sizeof(bDeformGroup), __func__);
70
71         BLI_strncpy(defgroup->name, name, sizeof(defgroup->name));
72
73         BLI_addtail(&ob->defbase, defgroup);
74         defgroup_unique_name(defgroup, ob);
75
76         return defgroup;
77 }
78
79 void defgroup_copy_list(ListBase *outbase, const ListBase *inbase)
80 {
81         bDeformGroup *defgroup, *defgroupn;
82
83         BLI_listbase_clear(outbase);
84
85         for (defgroup = inbase->first; defgroup; defgroup = defgroup->next) {
86                 defgroupn = defgroup_duplicate(defgroup);
87                 BLI_addtail(outbase, defgroupn);
88         }
89 }
90
91 bDeformGroup *defgroup_duplicate(const bDeformGroup *ingroup)
92 {
93         bDeformGroup *outgroup;
94
95         if (!ingroup) {
96                 BLI_assert(0);
97                 return NULL;
98         }
99
100         outgroup = MEM_callocN(sizeof(bDeformGroup), "copy deformGroup");
101
102         /* For now, just copy everything over. */
103         memcpy(outgroup, ingroup, sizeof(bDeformGroup));
104
105         outgroup->next = outgroup->prev = NULL;
106
107         return outgroup;
108 }
109
110 /**
111  * Overwrite weights filtered by vgroup_subset.
112  * - do nothing if neither are set.
113  * - add destination weight if needed
114  */
115 void defvert_copy_subset(
116         MDeformVert *dvert_dst, const MDeformVert *dvert_src,
117         const bool *vgroup_subset, const int vgroup_tot)
118 {
119         int defgroup;
120         for (defgroup = 0; defgroup < vgroup_tot; defgroup++) {
121                 if (vgroup_subset[defgroup]) {
122                         defvert_copy_index(dvert_dst, defgroup, dvert_src, defgroup);
123                 }
124         }
125 }
126
127 /**
128  * Overwrite weights filtered by vgroup_subset and with mirroring specified by the flip map
129  * - do nothing if neither are set.
130  * - add destination weight if needed
131  */
132 void defvert_mirror_subset(
133         MDeformVert *dvert_dst, const MDeformVert *dvert_src,
134         const bool *vgroup_subset, const int vgroup_tot,
135         const int *flip_map, const int flip_map_len)
136 {
137         int defgroup;
138         for (defgroup = 0; defgroup < vgroup_tot && defgroup < flip_map_len; defgroup++) {
139                 if (vgroup_subset[defgroup] && (dvert_dst != dvert_src || flip_map[defgroup] != defgroup)) {
140                         defvert_copy_index(dvert_dst, flip_map[defgroup], dvert_src, defgroup);
141                 }
142         }
143 }
144
145 void defvert_copy(MDeformVert *dvert_dst, const MDeformVert *dvert_src)
146 {
147         if (dvert_dst->totweight == dvert_src->totweight) {
148                 if (dvert_src->totweight)
149                         memcpy(dvert_dst->dw, dvert_src->dw, dvert_src->totweight * sizeof(MDeformWeight));
150         }
151         else {
152                 if (dvert_dst->dw)
153                         MEM_freeN(dvert_dst->dw);
154
155                 if (dvert_src->totweight)
156                         dvert_dst->dw = MEM_dupallocN(dvert_src->dw);
157                 else
158                         dvert_dst->dw = NULL;
159
160                 dvert_dst->totweight = dvert_src->totweight;
161         }
162 }
163
164 /**
165  * Copy an index from one dvert to another.
166  * - do nothing if neither are set.
167  * - add destination weight if needed.
168  */
169 void defvert_copy_index(
170         MDeformVert       *dvert_dst, const int defgroup_dst,
171         const MDeformVert *dvert_src, const int defgroup_src)
172 {
173         MDeformWeight *dw_src, *dw_dst;
174
175         dw_src = defvert_find_index(dvert_src, defgroup_src);
176
177         if (dw_src) {
178                 /* source is valid, verify destination */
179                 dw_dst = defvert_verify_index(dvert_dst, defgroup_dst);
180                 dw_dst->weight = dw_src->weight;
181         }
182         else {
183                 /* source was NULL, assign zero, could also remove */
184                 dw_dst = defvert_find_index(dvert_dst, defgroup_dst);
185
186                 if (dw_dst) {
187                         dw_dst->weight = 0.0f;
188                 }
189         }
190 }
191
192 /**
193  * Only sync over matching weights, don't add or remove groups
194  * warning, loop within loop.
195  */
196 void defvert_sync(MDeformVert *dvert_dst, const MDeformVert *dvert_src, const bool use_verify)
197 {
198         if (dvert_src->totweight && dvert_dst->totweight) {
199                 int i;
200                 MDeformWeight *dw_src;
201                 for (i = 0, dw_src = dvert_src->dw; i < dvert_src->totweight; i++, dw_src++) {
202                         MDeformWeight *dw_dst;
203                         if (use_verify) dw_dst = defvert_verify_index(dvert_dst, dw_src->def_nr);
204                         else            dw_dst = defvert_find_index(dvert_dst, dw_src->def_nr);
205
206                         if (dw_dst) {
207                                 dw_dst->weight = dw_src->weight;
208                         }
209                 }
210         }
211 }
212
213 /**
214  * be sure all flip_map values are valid
215  */
216 void defvert_sync_mapped(
217         MDeformVert *dvert_dst, const MDeformVert *dvert_src,
218         const int *flip_map, const int flip_map_len, const bool use_verify)
219 {
220         if (dvert_src->totweight && dvert_dst->totweight) {
221                 int i;
222                 MDeformWeight *dw_src;
223                 for (i = 0, dw_src = dvert_src->dw; i < dvert_src->totweight; i++, dw_src++) {
224                         if (dw_src->def_nr < flip_map_len) {
225                                 MDeformWeight *dw_dst;
226                                 if (use_verify) dw_dst = defvert_verify_index(dvert_dst, flip_map[dw_src->def_nr]);
227                                 else            dw_dst = defvert_find_index(dvert_dst, flip_map[dw_src->def_nr]);
228
229                                 if (dw_dst) {
230                                         dw_dst->weight = dw_src->weight;
231                                 }
232                         }
233                 }
234         }
235 }
236
237 /**
238  * be sure all flip_map values are valid
239  */
240 void defvert_remap(MDeformVert *dvert, int *map, const int map_len)
241 {
242         MDeformWeight *dw = dvert->dw;
243         unsigned int i;
244         for (i = dvert->totweight; i != 0; i--, dw++) {
245                 if (dw->def_nr < map_len) {
246                         dw->def_nr = map[dw->def_nr];
247
248                         /* just in case */
249                         BLI_assert(dw->def_nr >= 0);
250                 }
251         }
252 }
253
254 /**
255  * Same as #defvert_normalize but takes a bool array.
256  */
257 void defvert_normalize_subset(MDeformVert *dvert,
258                               const bool *vgroup_subset, const int vgroup_tot)
259 {
260         if (dvert->totweight == 0) {
261                 /* nothing */
262         }
263         else if (dvert->totweight == 1) {
264                 MDeformWeight *dw = dvert->dw;
265                 if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
266                         dw->weight = 1.0f;
267                 }
268         }
269         else {
270                 MDeformWeight *dw;
271                 unsigned int i;
272                 float tot_weight = 0.0f;
273
274                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
275                         if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
276                                 tot_weight += dw->weight;
277                         }
278                 }
279
280                 if (tot_weight > 0.0f) {
281                         float scalar = 1.0f / tot_weight;
282                         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
283                                 if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
284                                         dw->weight *= scalar;
285
286                                         /* in case of division errors with very low weights */
287                                         CLAMP(dw->weight, 0.0f, 1.0f);
288                                 }
289                         }
290                 }
291         }
292 }
293
294 void defvert_normalize(MDeformVert *dvert)
295 {
296         if (dvert->totweight == 0) {
297                 /* nothing */
298         }
299         else if (dvert->totweight == 1) {
300                 dvert->dw[0].weight = 1.0f;
301         }
302         else {
303                 MDeformWeight *dw;
304                 unsigned int i;
305                 float tot_weight = 0.0f;
306
307                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
308                         tot_weight += dw->weight;
309                 }
310
311                 if (tot_weight > 0.0f) {
312                         float scalar = 1.0f / tot_weight;
313                         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
314                                 dw->weight *= scalar;
315
316                                 /* in case of division errors with very low weights */
317                                 CLAMP(dw->weight, 0.0f, 1.0f);
318                         }
319                 }
320         }
321 }
322
323 /**
324  * Same as defvert_normalize() if the locked vgroup is not a member of the subset
325  */
326 void defvert_normalize_lock_single(
327         MDeformVert *dvert,
328         const bool *vgroup_subset, const int vgroup_tot,
329         const int def_nr_lock)
330 {
331         if (dvert->totweight == 0) {
332                 /* nothing */
333         }
334         else if (dvert->totweight == 1) {
335                 MDeformWeight *dw = dvert->dw;
336                 if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
337                         if (def_nr_lock != 0) {
338                                 dw->weight = 1.0f;
339                         }
340                 }
341         }
342         else {
343                 MDeformWeight *dw_lock = NULL;
344                 MDeformWeight *dw;
345                 unsigned int i;
346                 float tot_weight = 0.0f;
347                 float lock_iweight = 1.0f;
348
349                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
350                         if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
351                                 if (dw->def_nr != def_nr_lock) {
352                                         tot_weight += dw->weight;
353                                 }
354                                 else {
355                                         dw_lock = dw;
356                                         lock_iweight = (1.0f - dw_lock->weight);
357                                         CLAMP(lock_iweight, 0.0f, 1.0f);
358                                 }
359                         }
360                 }
361
362                 if (tot_weight > 0.0f) {
363                         /* paranoid, should be 1.0 but in case of float error clamp anyway */
364
365                         float scalar = (1.0f / tot_weight) * lock_iweight;
366                         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
367                                 if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
368                                         if (dw != dw_lock) {
369                                                 dw->weight *= scalar;
370
371                                                 /* in case of division errors with very low weights */
372                                                 CLAMP(dw->weight, 0.0f, 1.0f);
373                                         }
374                                 }
375                         }
376                 }
377         }
378 }
379
380 /**
381  * Same as defvert_normalize() if no locked vgroup is a member of the subset
382  */
383 void defvert_normalize_lock_map(
384         MDeformVert *dvert,
385         const bool *vgroup_subset, const int vgroup_tot,
386         const bool *lock_flags, const int defbase_tot)
387 {
388         if (dvert->totweight == 0) {
389                 /* nothing */
390         }
391         else if (dvert->totweight == 1) {
392                 MDeformWeight *dw = dvert->dw;
393                 if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
394                         if ((dw->def_nr < defbase_tot) && (lock_flags[dw->def_nr] == false)) {
395                                 dw->weight = 1.0f;
396                         }
397                 }
398         }
399         else {
400                 MDeformWeight *dw;
401                 unsigned int i;
402                 float tot_weight = 0.0f;
403                 float lock_iweight = 0.0f;
404
405                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
406                         if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
407                                 if ((dw->def_nr < defbase_tot) && (lock_flags[dw->def_nr] == false)) {
408                                         tot_weight += dw->weight;
409                                 }
410                                 else {
411                                         /* invert after */
412                                         lock_iweight += dw->weight;
413                                 }
414                         }
415                 }
416
417                 lock_iweight = max_ff(0.0f, 1.0f - lock_iweight);
418
419                 if (tot_weight > 0.0f) {
420                         /* paranoid, should be 1.0 but in case of float error clamp anyway */
421
422                         float scalar = (1.0f / tot_weight) * lock_iweight;
423                         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
424                                 if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
425                                         if ((dw->def_nr < defbase_tot) && (lock_flags[dw->def_nr] == false)) {
426                                                 dw->weight *= scalar;
427
428                                                 /* in case of division errors with very low weights */
429                                                 CLAMP(dw->weight, 0.0f, 1.0f);
430                                         }
431                                 }
432                         }
433                 }
434         }
435 }
436
437 void defvert_flip(MDeformVert *dvert, const int *flip_map, const int flip_map_len)
438 {
439         MDeformWeight *dw;
440         int i;
441
442         for (dw = dvert->dw, i = 0; i < dvert->totweight; dw++, i++) {
443                 if (dw->def_nr < flip_map_len) {
444                         if (flip_map[dw->def_nr] >= 0) {
445                                 dw->def_nr = flip_map[dw->def_nr];
446                         }
447                 }
448         }
449 }
450
451 void defvert_flip_merged(MDeformVert *dvert, const int *flip_map, const int flip_map_len)
452 {
453         MDeformWeight *dw, *dw_cpy;
454         float weight;
455         int i, totweight = dvert->totweight;
456
457         /* copy weights */
458         for (dw = dvert->dw, i = 0; i < totweight; dw++, i++) {
459                 if (dw->def_nr < flip_map_len) {
460                         if (flip_map[dw->def_nr] >= 0) {
461                                 /* error checkers complain of this but we'll never get NULL return */
462                                 dw_cpy = defvert_verify_index(dvert, flip_map[dw->def_nr]);
463                                 dw = &dvert->dw[i]; /* in case array got realloced */
464
465                                 /* distribute weights: if only one of the vertex groups was
466                                  * assigned this will halve the weights, otherwise it gets
467                                  * evened out. this keeps it proportional to other groups */
468                                 weight = 0.5f * (dw_cpy->weight + dw->weight);
469                                 dw_cpy->weight = weight;
470                                 dw->weight = weight;
471                         }
472                 }
473         }
474 }
475
476 bDeformGroup *defgroup_find_name(Object *ob, const char *name)
477 {
478         return BLI_findstring(&ob->defbase, name, offsetof(bDeformGroup, name));
479 }
480
481 int defgroup_name_index(Object *ob, const char *name)
482 {
483         return (name) ? BLI_findstringindex(&ob->defbase, name, offsetof(bDeformGroup, name)) : -1;
484 }
485
486 /**
487  * \note caller must free.
488  */
489 int *defgroup_flip_map(Object *ob, int *flip_map_len, const bool use_default)
490 {
491         int defbase_tot = *flip_map_len = BLI_listbase_count(&ob->defbase);
492
493         if (defbase_tot == 0) {
494                 return NULL;
495         }
496         else {
497                 bDeformGroup *dg;
498                 char name_flip[sizeof(dg->name)];
499                 int i, flip_num, *map = MEM_mallocN(defbase_tot * sizeof(int), __func__);
500
501                 for (i = 0; i < defbase_tot; i++) {
502                         map[i] = -1;
503                 }
504
505                 for (dg = ob->defbase.first, i = 0; dg; dg = dg->next, i++) {
506                         if (map[i] == -1) { /* may be calculated previously */
507
508                                 /* in case no valid value is found, use this */
509                                 if (use_default)
510                                         map[i] = i;
511
512                                 BLI_string_flip_side_name(name_flip, dg->name, false, sizeof(name_flip));
513
514                                 if (!STREQ(name_flip, dg->name)) {
515                                         flip_num = defgroup_name_index(ob, name_flip);
516                                         if (flip_num >= 0) {
517                                                 map[i] = flip_num;
518                                                 map[flip_num] = i; /* save an extra lookup */
519                                         }
520                                 }
521                         }
522                 }
523                 return map;
524         }
525 }
526
527 /**
528  * \note caller must free.
529  */
530 int *defgroup_flip_map_single(Object *ob, int *flip_map_len, const bool use_default, int defgroup)
531 {
532         int defbase_tot = *flip_map_len = BLI_listbase_count(&ob->defbase);
533
534         if (defbase_tot == 0) {
535                 return NULL;
536         }
537         else {
538                 bDeformGroup *dg;
539                 char name_flip[sizeof(dg->name)];
540                 int i, flip_num, *map = MEM_mallocN(defbase_tot * sizeof(int), __func__);
541
542                 for (i = 0; i < defbase_tot; i++) {
543                         map[i] = use_default ? i : -1;
544                 }
545
546                 dg = BLI_findlink(&ob->defbase, defgroup);
547
548                 BLI_string_flip_side_name(name_flip, dg->name, false, sizeof(name_flip));
549                 if (!STREQ(name_flip, dg->name)) {
550                         flip_num = defgroup_name_index(ob, name_flip);
551
552                         if (flip_num != -1) {
553                                 map[defgroup] = flip_num;
554                                 map[flip_num] = defgroup;
555                         }
556                 }
557
558                 return map;
559         }
560 }
561
562 int defgroup_flip_index(Object *ob, int index, const bool use_default)
563 {
564         bDeformGroup *dg = BLI_findlink(&ob->defbase, index);
565         int flip_index = -1;
566
567         if (dg) {
568                 char name_flip[sizeof(dg->name)];
569                 BLI_string_flip_side_name(name_flip, dg->name, false, sizeof(name_flip));
570
571                 if (!STREQ(name_flip, dg->name)) {
572                         flip_index = defgroup_name_index(ob, name_flip);
573                 }
574         }
575
576         return (flip_index == -1 && use_default) ? index : flip_index;
577 }
578
579 static bool defgroup_find_name_dupe(const char *name, bDeformGroup *dg, Object *ob)
580 {
581         bDeformGroup *curdef;
582
583         for (curdef = ob->defbase.first; curdef; curdef = curdef->next) {
584                 if (dg != curdef) {
585                         if (STREQ(curdef->name, name)) {
586                                 return true;
587                         }
588                 }
589         }
590
591         return false;
592 }
593
594 static bool defgroup_unique_check(void *arg, const char *name)
595 {
596         struct {Object *ob; void *dg; } *data = arg;
597         return defgroup_find_name_dupe(name, data->dg, data->ob);
598 }
599
600 void defgroup_unique_name(bDeformGroup *dg, Object *ob)
601 {
602         struct {Object *ob; void *dg; } data;
603         data.ob = ob;
604         data.dg = dg;
605
606         BLI_uniquename_cb(defgroup_unique_check, &data, DATA_("Group"), '.', dg->name, sizeof(dg->name));
607 }
608
609 float defvert_find_weight(const struct MDeformVert *dvert, const int defgroup)
610 {
611         MDeformWeight *dw = defvert_find_index(dvert, defgroup);
612         return dw ? dw->weight : 0.0f;
613 }
614
615 /**
616  * Take care with this the rationale is:
617  * - if the object has no vertex group. act like vertex group isn't set and return 1.0,
618  * - if the vertex group exists but the 'defgroup' isn't found on this vertex, _still_ return 0.0
619  *
620  * This is a bit confusing, just saves some checks from the caller.
621  */
622 float defvert_array_find_weight_safe(const struct MDeformVert *dvert, const int index, const int defgroup)
623 {
624         /* Invalid defgroup index means the vgroup selected is invalid, does not exist, in that case it is OK to return 1.0
625          * (i.e. maximum weight, as if no vgroup was selected).
626          * But in case of valid defgroup and NULL dvert data pointer, it means that vgroup **is** valid,
627          * and just totally empty, so we shall return '0.0' value then!
628         */
629         if (defgroup == -1) {
630                 return 1.0f;
631         }
632         else if (dvert == NULL) {
633                 return 0.0f;
634         }
635
636         return defvert_find_weight(dvert + index, defgroup);
637 }
638
639
640 MDeformWeight *defvert_find_index(const MDeformVert *dvert, const int defgroup)
641 {
642         if (dvert && defgroup >= 0) {
643                 MDeformWeight *dw = dvert->dw;
644                 unsigned int i;
645
646                 for (i = dvert->totweight; i != 0; i--, dw++) {
647                         if (dw->def_nr == defgroup) {
648                                 return dw;
649                         }
650                 }
651         }
652         else {
653                 BLI_assert(0);
654         }
655
656         return NULL;
657 }
658
659 /**
660  * Ensures that mv has a deform weight entry for the specified defweight group.
661  *
662  * \note this function is mirrored in editmesh_tools.c, for use for editvertices.
663  */
664 MDeformWeight *defvert_verify_index(MDeformVert *dvert, const int defgroup)
665 {
666         MDeformWeight *dw_new;
667
668         /* do this check always, this function is used to check for it */
669         if (!dvert || defgroup < 0) {
670                 BLI_assert(0);
671                 return NULL;
672         }
673
674         dw_new = defvert_find_index(dvert, defgroup);
675         if (dw_new)
676                 return dw_new;
677
678         dw_new = MEM_mallocN(sizeof(MDeformWeight) * (dvert->totweight + 1), "deformWeight");
679         if (dvert->dw) {
680                 memcpy(dw_new, dvert->dw, sizeof(MDeformWeight) * dvert->totweight);
681                 MEM_freeN(dvert->dw);
682         }
683         dvert->dw = dw_new;
684         dw_new += dvert->totweight;
685         dw_new->weight = 0.0f;
686         dw_new->def_nr = defgroup;
687         /* Group index */
688
689         dvert->totweight++;
690
691         return dw_new;
692 }
693
694 /* TODO. merge with code above! */
695
696 /**
697  * Adds the given vertex to the specified vertex group, with given weight.
698  *
699  * \warning this does NOT check for existing, assume caller already knows its not there.
700  */
701 void defvert_add_index_notest(MDeformVert *dvert, int defgroup, const float weight)
702 {
703         MDeformWeight *dw_new;
704
705         /* do this check always, this function is used to check for it */
706         if (!dvert || defgroup < 0) {
707                 BLI_assert(0);
708                 return;
709         }
710
711         dw_new = MEM_callocN(sizeof(MDeformWeight) * (dvert->totweight + 1), "defvert_add_to group, new deformWeight");
712         if (dvert->dw) {
713                 memcpy(dw_new, dvert->dw, sizeof(MDeformWeight) * dvert->totweight);
714                 MEM_freeN(dvert->dw);
715         }
716         dvert->dw = dw_new;
717         dw_new += dvert->totweight;
718         dw_new->weight = weight;
719         dw_new->def_nr = defgroup;
720         dvert->totweight++;
721 }
722
723
724 /**
725  * Removes the given vertex from the vertex group.
726  *
727  * \warning This function frees the given MDeformWeight, do not use it afterward!
728  */
729 void defvert_remove_group(MDeformVert *dvert, MDeformWeight *dw)
730 {
731         if (dvert && dw) {
732                 int i = dw - dvert->dw;
733
734                 /* Security check! */
735                 if (i < 0 || i >= dvert->totweight) {
736                         return;
737                 }
738
739                 dvert->totweight--;
740                 /* If there are still other deform weights attached to this vert then remove
741                  * this deform weight, and reshuffle the others.
742                  */
743                 if (dvert->totweight) {
744                         BLI_assert(dvert->dw != NULL);
745
746                         if (i != dvert->totweight) {
747                                 dvert->dw[i] = dvert->dw[dvert->totweight];
748                         }
749
750                         dvert->dw = MEM_reallocN(dvert->dw, sizeof(MDeformWeight) * dvert->totweight);
751                 }
752                 else {
753                         /* If there are no other deform weights left then just remove this one. */
754                         MEM_freeN(dvert->dw);
755                         dvert->dw = NULL;
756                 }
757         }
758 }
759
760 void defvert_clear(MDeformVert *dvert)
761 {
762         if (dvert->dw) {
763                 MEM_freeN(dvert->dw);
764                 dvert->dw = NULL;
765         }
766
767         dvert->totweight = 0;
768 }
769
770 /**
771  * \return The first group index shared by both deform verts
772  * or -1 if none are found.
773  */
774 int defvert_find_shared(const MDeformVert *dvert_a, const MDeformVert *dvert_b)
775 {
776         if (dvert_a->totweight && dvert_b->totweight) {
777                 MDeformWeight *dw = dvert_a->dw;
778                 unsigned int i;
779
780                 for (i = dvert_a->totweight; i != 0; i--, dw++) {
781                         if (dw->weight > 0.0f && defvert_find_weight(dvert_b, dw->def_nr) > 0.0f) {
782                                 return dw->def_nr;
783                         }
784                 }
785         }
786
787         return -1;
788 }
789
790 /**
791  * return true if has no weights
792  */
793 bool defvert_is_weight_zero(const struct MDeformVert *dvert, const int defgroup_tot)
794 {
795         MDeformWeight *dw = dvert->dw;
796         unsigned int i;
797         for (i = dvert->totweight; i != 0; i--, dw++) {
798                 if (dw->weight != 0.0f) {
799                         /* check the group is in-range, happens on rare situations */
800                         if (LIKELY(dw->def_nr < defgroup_tot)) {
801                                 return false;
802                         }
803                 }
804         }
805         return true;
806 }
807
808
809 /**
810  * \return The representative weight of a multipaint group, used for
811  * viewport colors and actual painting.
812  *
813  * Result equal to sum of weights with auto normalize, and average otherwise.
814  * Value is not clamped, since painting relies on multiplication being always
815  * commutative with the collective weight function.
816  */
817 float BKE_defvert_multipaint_collective_weight(
818         const struct MDeformVert *dv, int defbase_tot,
819         const bool *defbase_sel, int defbase_tot_sel, bool do_autonormalize)
820 {
821         int i;
822         float total = 0.0f;
823         const MDeformWeight *dw = dv->dw;
824
825         for (i = dv->totweight; i != 0; i--, dw++) {
826                 /* in multipaint, get the average if auto normalize is inactive
827                  * get the sum if it is active */
828                 if (dw->def_nr < defbase_tot) {
829                         if (defbase_sel[dw->def_nr]) {
830                                 total += dw->weight;
831                         }
832                 }
833         }
834
835         if (do_autonormalize == false) {
836                 total /= defbase_tot_sel;
837         }
838
839         return total;
840 }
841
842
843 /* -------------------------------------------------------------------- */
844
845 /** \name Defvert Array functions
846  * \{ */
847
848 void BKE_defvert_array_copy(MDeformVert *dst, const MDeformVert *src, int copycount)
849 {
850         /* Assumes dst is already set up */
851         int i;
852
853         if (!src || !dst)
854                 return;
855
856         memcpy(dst, src, copycount * sizeof(MDeformVert));
857
858         for (i = 0; i < copycount; i++) {
859                 if (src[i].dw) {
860                         dst[i].dw = MEM_mallocN(sizeof(MDeformWeight) * src[i].totweight, "copy_deformWeight");
861                         memcpy(dst[i].dw, src[i].dw, sizeof(MDeformWeight) * src[i].totweight);
862                 }
863         }
864
865 }
866
867 void BKE_defvert_array_free_elems(MDeformVert *dvert, int totvert)
868 {
869         /* Instead of freeing the verts directly,
870          * call this function to delete any special
871          * vert data */
872         int i;
873
874         if (!dvert)
875                 return;
876
877         /* Free any special data from the verts */
878         for (i = 0; i < totvert; i++) {
879                 if (dvert[i].dw) MEM_freeN(dvert[i].dw);
880         }
881 }
882
883 void BKE_defvert_array_free(MDeformVert *dvert, int totvert)
884 {
885         /* Instead of freeing the verts directly,
886          * call this function to delete any special
887          * vert data */
888         if (!dvert)
889                 return;
890
891         /* Free any special data from the verts */
892         BKE_defvert_array_free_elems(dvert, totvert);
893
894         MEM_freeN(dvert);
895 }
896
897 void BKE_defvert_extract_vgroup_to_vertweights(
898         MDeformVert *dvert, const int defgroup, const int num_verts, float *r_weights, const bool invert_vgroup)
899 {
900         if (dvert && defgroup != -1) {
901                 int i = num_verts;
902
903                 while (i--) {
904                         const float w = defvert_find_weight(&dvert[i], defgroup);
905                         r_weights[i] = invert_vgroup ? (1.0f - w) : w;
906                 }
907         }
908         else {
909                 copy_vn_fl(r_weights, num_verts, invert_vgroup ? 1.0f : 0.0f);
910         }
911 }
912
913 /**
914  * The following three make basic interpolation,
915  * using temp vert_weights array to avoid looking up same weight several times.
916  */
917 void BKE_defvert_extract_vgroup_to_edgeweights(
918         MDeformVert *dvert, const int defgroup, const int num_verts, MEdge *edges, const int num_edges,
919         float *r_weights, const bool invert_vgroup)
920 {
921         if (dvert && defgroup != -1) {
922                 int i = num_edges;
923                 float *tmp_weights = MEM_mallocN(sizeof(*tmp_weights) * (size_t)num_verts, __func__);
924
925                 BKE_defvert_extract_vgroup_to_vertweights(dvert, defgroup, num_verts, tmp_weights, invert_vgroup);
926
927                 while (i--) {
928                         MEdge *me = &edges[i];
929
930                         r_weights[i] = (tmp_weights[me->v1] + tmp_weights[me->v2]) * 0.5f;
931                 }
932
933                 MEM_freeN(tmp_weights);
934         }
935         else {
936                 copy_vn_fl(r_weights, num_edges, 0.0f);
937         }
938 }
939
940 void BKE_defvert_extract_vgroup_to_loopweights(
941         MDeformVert *dvert, const int defgroup, const int num_verts, MLoop *loops, const int num_loops,
942         float *r_weights, const bool invert_vgroup)
943 {
944         if (dvert && defgroup != -1) {
945                 int i = num_loops;
946                 float *tmp_weights = MEM_mallocN(sizeof(*tmp_weights) * (size_t)num_verts, __func__);
947
948                 BKE_defvert_extract_vgroup_to_vertweights(dvert, defgroup, num_verts, tmp_weights, invert_vgroup);
949
950                 while (i--) {
951                         MLoop *ml = &loops[i];
952
953                         r_weights[i] = tmp_weights[ml->v];
954                 }
955
956                 MEM_freeN(tmp_weights);
957         }
958         else {
959                 copy_vn_fl(r_weights, num_loops, 0.0f);
960         }
961 }
962
963 void BKE_defvert_extract_vgroup_to_polyweights(
964         MDeformVert *dvert, const int defgroup, const int num_verts, MLoop *loops, const int UNUSED(num_loops),
965         MPoly *polys, const int num_polys, float *r_weights, const bool invert_vgroup)
966 {
967         if (dvert && defgroup != -1) {
968                 int i = num_polys;
969                 float *tmp_weights = MEM_mallocN(sizeof(*tmp_weights) * (size_t)num_verts, __func__);
970
971                 BKE_defvert_extract_vgroup_to_vertweights(dvert, defgroup, num_verts, tmp_weights, invert_vgroup);
972
973                 while (i--) {
974                         MPoly *mp = &polys[i];
975                         MLoop *ml = &loops[mp->loopstart];
976                         int j = mp->totloop;
977                         float w = 0.0f;
978
979                         for (; j--; ml++) {
980                                 w += tmp_weights[ml->v];
981                         }
982                         r_weights[i] = w / (float)mp->totloop;
983                 }
984
985                 MEM_freeN(tmp_weights);
986         }
987         else {
988                 copy_vn_fl(r_weights, num_polys, 0.0f);
989         }
990 }
991
992 /** \} */
993
994
995 /* -------------------------------------------------------------------- */
996
997 /** \name Data Transfer
998  * \{ */
999
1000 static void vgroups_datatransfer_interp(
1001         const CustomDataTransferLayerMap *laymap, void *dest,
1002         const void **sources, const float *weights, const int count, const float mix_factor)
1003 {
1004         MDeformVert **data_src = (MDeformVert **)sources;
1005         MDeformVert *data_dst = (MDeformVert *)dest;
1006         const int idx_src = laymap->data_src_n;
1007         const int idx_dst = laymap->data_dst_n;
1008
1009         const int mix_mode = laymap->mix_mode;
1010
1011         int i, j;
1012
1013         MDeformWeight *dw_src;
1014         MDeformWeight *dw_dst = defvert_find_index(data_dst, idx_dst);
1015         float weight_src = 0.0f, weight_dst = 0.0f;
1016
1017         if (sources) {
1018                 for (i = count; i--;) {
1019                         for (j = data_src[i]->totweight; j--;) {
1020                                 if ((dw_src = &data_src[i]->dw[j])->def_nr == idx_src) {
1021                                         weight_src += dw_src->weight * weights[i];
1022                                         break;
1023                                 }
1024                         }
1025                 }
1026         }
1027
1028         if (dw_dst) {
1029                 weight_dst = dw_dst->weight;
1030         }
1031         else if (mix_mode == CDT_MIX_REPLACE_ABOVE_THRESHOLD) {
1032                 return;  /* Do not affect destination. */
1033         }
1034
1035         weight_src = data_transfer_interp_float_do(mix_mode, weight_dst, weight_src, mix_factor);
1036
1037         CLAMP(weight_src, 0.0f, 1.0f);
1038
1039         if (!dw_dst) {
1040                 defvert_add_index_notest(data_dst, idx_dst, weight_src);
1041         }
1042         else {
1043                 dw_dst->weight = weight_src;
1044         }
1045 }
1046
1047 static bool data_transfer_layersmapping_vgroups_multisrc_to_dst(
1048         ListBase *r_map, const int mix_mode, const float mix_factor, const float *mix_weights,
1049         const int num_elem_dst, const bool use_create, const bool use_delete,
1050         Object *ob_src, Object *ob_dst, MDeformVert *data_src, MDeformVert *data_dst,
1051         CustomData *UNUSED(cd_src), CustomData *cd_dst, const bool UNUSED(use_dupref_dst),
1052         const int tolayers, bool *use_layers_src, const int num_layers_src)
1053 {
1054         int idx_src;
1055         int idx_dst;
1056         int tot_dst = BLI_listbase_count(&ob_dst->defbase);
1057
1058         const size_t elem_size = sizeof(*((MDeformVert *)NULL));
1059
1060         switch (tolayers) {
1061                 case DT_LAYERS_INDEX_DST:
1062                         idx_dst = tot_dst;
1063
1064                         /* Find last source actually used! */
1065                         idx_src = num_layers_src;
1066                         while (idx_src-- && !use_layers_src[idx_src]);
1067                         idx_src++;
1068
1069                         if (idx_dst < idx_src) {
1070                                 if (!use_create) {
1071                                         return false;
1072                                 }
1073                                 /* Create as much vgroups as necessary! */
1074                                 for (; idx_dst < idx_src; idx_dst++) {
1075                                         BKE_object_defgroup_add(ob_dst);
1076                                 }
1077                         }
1078                         else if (use_delete && idx_dst > idx_src) {
1079                                 while (idx_dst-- > idx_src) {
1080                                         BKE_object_defgroup_remove(ob_dst, ob_dst->defbase.last);
1081                                 }
1082                         }
1083                         if (r_map) {
1084                                 /* At this stage, we **need** a valid CD_MDEFORMVERT layer on dest!
1085                                  * Again, use_create is not relevant in this case */
1086                                 if (!data_dst) {
1087                                         data_dst = CustomData_add_layer(cd_dst, CD_MDEFORMVERT, CD_CALLOC, NULL, num_elem_dst);
1088                                 }
1089
1090                                 while (idx_src--) {
1091                                         if (!use_layers_src[idx_src]) {
1092                                                 continue;
1093                                         }
1094                                         data_transfer_layersmapping_add_item(r_map, CD_FAKE_MDEFORMVERT, mix_mode, mix_factor, mix_weights,
1095                                                                              data_src, data_dst, idx_src, idx_src,
1096                                                                              elem_size, 0, 0, 0, vgroups_datatransfer_interp, NULL);
1097                                 }
1098                         }
1099                         break;
1100                 case DT_LAYERS_NAME_DST:
1101                         {
1102                                 bDeformGroup *dg_src, *dg_dst;
1103
1104                                 if (use_delete) {
1105                                         /* Remove all unused dst vgroups first, simpler in this case. */
1106                                         for (dg_dst = ob_dst->defbase.first; dg_dst;) {
1107                                                 bDeformGroup *dg_dst_next = dg_dst->next;
1108
1109                                                 if (defgroup_name_index(ob_src, dg_dst->name) == -1) {
1110                                                         BKE_object_defgroup_remove(ob_dst, dg_dst);
1111                                                 }
1112                                                 dg_dst = dg_dst_next;
1113                                         }
1114                                 }
1115
1116                                 for (idx_src = 0, dg_src = ob_src->defbase.first;
1117                                      idx_src < num_layers_src;
1118                                      idx_src++, dg_src = dg_src->next)
1119                                 {
1120                                         if (!use_layers_src[idx_src]) {
1121                                                 continue;
1122                                         }
1123
1124                                         if ((idx_dst = defgroup_name_index(ob_dst, dg_src->name)) == -1) {
1125                                                 if (!use_create) {
1126                                                         if (r_map) {
1127                                                                 BLI_freelistN(r_map);
1128                                                         }
1129                                                         return false;
1130                                                 }
1131                                                 BKE_object_defgroup_add_name(ob_dst, dg_src->name);
1132                                                 idx_dst = ob_dst->actdef - 1;
1133                                         }
1134                                         if (r_map) {
1135                                                 /* At this stage, we **need** a valid CD_MDEFORMVERT layer on dest!
1136                                                  * use_create is not relevant in this case */
1137                                                 if (!data_dst) {
1138                                                         data_dst = CustomData_add_layer(cd_dst, CD_MDEFORMVERT, CD_CALLOC, NULL, num_elem_dst);
1139                                                 }
1140
1141                                                 data_transfer_layersmapping_add_item(
1142                                                         r_map, CD_FAKE_MDEFORMVERT, mix_mode, mix_factor, mix_weights,
1143                                                         data_src, data_dst, idx_src, idx_dst,
1144                                                         elem_size, 0, 0, 0, vgroups_datatransfer_interp, NULL);
1145                                         }
1146                                 }
1147                                 break;
1148                         }
1149                 default:
1150                         return false;
1151         }
1152
1153         return true;
1154 }
1155
1156 bool data_transfer_layersmapping_vgroups(
1157         ListBase *r_map, const int mix_mode, const float mix_factor, const float *mix_weights,
1158         const int num_elem_dst, const bool use_create, const bool use_delete, Object *ob_src, Object *ob_dst,
1159         CustomData *cd_src, CustomData *cd_dst, const bool use_dupref_dst, const int fromlayers, const int tolayers)
1160 {
1161         int idx_src, idx_dst;
1162         MDeformVert *data_src, *data_dst = NULL;
1163
1164         const size_t elem_size = sizeof(*((MDeformVert *)NULL));
1165
1166         /* Note: VGroups are a bit hairy, since their layout is defined on object level (ob->defbase), while their actual
1167          *       data is a (mesh) CD layer.
1168          *       This implies we may have to handle data layout itself while having NULL data itself,
1169          *       and even have to support NULL data_src in transfer data code (we always create a data_dst, though).
1170          */
1171
1172         if (BLI_listbase_is_empty(&ob_src->defbase)) {
1173                 if (use_delete) {
1174                         BKE_object_defgroup_remove_all(ob_dst);
1175                 }
1176                 return true;
1177         }
1178
1179         data_src = CustomData_get_layer(cd_src, CD_MDEFORMVERT);
1180
1181         data_dst = CustomData_get_layer(cd_dst, CD_MDEFORMVERT);
1182         if (data_dst && use_dupref_dst && r_map) {
1183                 /* If dest is a derivedmesh, we do not want to overwrite cdlayers of org mesh! */
1184                 data_dst = CustomData_duplicate_referenced_layer(cd_dst, CD_MDEFORMVERT, num_elem_dst);
1185         }
1186
1187         if (fromlayers == DT_LAYERS_ACTIVE_SRC || fromlayers >= 0) {
1188                 /* Note: use_delete has not much meaning in this case, ignored. */
1189
1190                 if (fromlayers >= 0) {
1191                         idx_src = fromlayers;
1192                         BLI_assert(idx_src < BLI_listbase_count(&ob_src->defbase));
1193                 }
1194                 else if ((idx_src = ob_src->actdef - 1) == -1) {
1195                         return false;
1196                 }
1197
1198                 if (tolayers >= 0) {
1199                         /* Note: in this case we assume layer exists! */
1200                         idx_dst = tolayers;
1201                         BLI_assert(idx_dst < BLI_listbase_count(&ob_dst->defbase));
1202                 }
1203                 else if (tolayers == DT_LAYERS_ACTIVE_DST) {
1204                         if ((idx_dst = ob_dst->actdef - 1) == -1) {
1205                                 bDeformGroup *dg_src;
1206                                 if (!use_create) {
1207                                         return true;
1208                                 }
1209                                 dg_src = BLI_findlink(&ob_src->defbase, idx_src);
1210                                 BKE_object_defgroup_add_name(ob_dst, dg_src->name);
1211                                 idx_dst = ob_dst->actdef - 1;
1212                         }
1213                 }
1214                 else if (tolayers == DT_LAYERS_INDEX_DST) {
1215                         int num = BLI_listbase_count(&ob_src->defbase);
1216                         idx_dst = idx_src;
1217                         if (num <= idx_dst) {
1218                                 if (!use_create) {
1219                                         return true;
1220                                 }
1221                                 /* Create as much vgroups as necessary! */
1222                                 for (; num <= idx_dst; num++) {
1223                                         BKE_object_defgroup_add(ob_dst);
1224                                 }
1225                         }
1226                 }
1227                 else if (tolayers == DT_LAYERS_NAME_DST) {
1228                         bDeformGroup *dg_src = BLI_findlink(&ob_src->defbase, idx_src);
1229                         if ((idx_dst = defgroup_name_index(ob_dst, dg_src->name)) == -1) {
1230                                 if (!use_create) {
1231                                         return true;
1232                                 }
1233                                 BKE_object_defgroup_add_name(ob_dst, dg_src->name);
1234                                 idx_dst = ob_dst->actdef - 1;
1235                         }
1236                 }
1237                 else {
1238                         return false;
1239                 }
1240
1241                 if (r_map) {
1242                         /* At this stage, we **need** a valid CD_MDEFORMVERT layer on dest!
1243                          * use_create is not relevant in this case */
1244                         if (!data_dst) {
1245                                 data_dst = CustomData_add_layer(cd_dst, CD_MDEFORMVERT, CD_CALLOC, NULL, num_elem_dst);
1246                         }
1247
1248                         data_transfer_layersmapping_add_item(r_map, CD_FAKE_MDEFORMVERT, mix_mode, mix_factor, mix_weights,
1249                                                              data_src, data_dst, idx_src, idx_dst,
1250                                                              elem_size, 0, 0, 0, vgroups_datatransfer_interp, NULL);
1251                 }
1252         }
1253         else {
1254                 int num_src, num_sel_unused;
1255                 bool *use_layers_src = NULL;
1256                 bool ret = false;
1257
1258                 switch (fromlayers) {
1259                         case DT_LAYERS_ALL_SRC:
1260                                 use_layers_src = BKE_object_defgroup_subset_from_select_type(ob_src, WT_VGROUP_ALL,
1261                                                                                              &num_src, &num_sel_unused);
1262                                 break;
1263                         case DT_LAYERS_VGROUP_SRC_BONE_SELECT:
1264                                 use_layers_src = BKE_object_defgroup_subset_from_select_type(ob_src, WT_VGROUP_BONE_SELECT,
1265                                                                                              &num_src, &num_sel_unused);
1266                                 break;
1267                         case DT_LAYERS_VGROUP_SRC_BONE_DEFORM:
1268                                 use_layers_src = BKE_object_defgroup_subset_from_select_type(ob_src, WT_VGROUP_BONE_DEFORM,
1269                                                                                              &num_src, &num_sel_unused);
1270                                 break;
1271                 }
1272
1273                 if (use_layers_src) {
1274                         ret = data_transfer_layersmapping_vgroups_multisrc_to_dst(
1275                                 r_map, mix_mode, mix_factor, mix_weights, num_elem_dst, use_create, use_delete,
1276                                 ob_src, ob_dst, data_src, data_dst, cd_src, cd_dst, use_dupref_dst,
1277                                 tolayers, use_layers_src, num_src);
1278                 }
1279
1280                 MEM_SAFE_FREE(use_layers_src);
1281                 return ret;
1282         }
1283
1284         return true;
1285 }
1286
1287 /** \} */