Welcome to mirror list, hosted at ThFree Co, Russian Federation.

deform.c « intern « blenkernel « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f7ef84728b63049894b99332ce1d40d4cfbcfc4f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
 * All rights reserved.
 */

/** \file
 * \ingroup bke
 */

#include <ctype.h>
#include <math.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

#include "MEM_guardedalloc.h"

#include "DNA_gpencil_types.h"
#include "DNA_lattice_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"

#include "BLI_listbase.h"
#include "BLI_math.h"
#include "BLI_string.h"
#include "BLI_string_utils.h"
#include "BLI_utildefines.h"

#include "BLT_translation.h"

#include "BKE_customdata.h"
#include "BKE_data_transfer.h"
#include "BKE_deform.h" /* own include */
#include "BKE_mesh.h"
#include "BKE_mesh_mapping.h"
#include "BKE_object.h"
#include "BKE_object_deform.h"

#include "BLO_read_write.h"

#include "data_transfer_intern.h"

bDeformGroup *BKE_object_defgroup_new(Object *ob, const char *name)
{
  bDeformGroup *defgroup;

  BLI_assert(OB_TYPE_SUPPORT_VGROUP(ob->type));

  defgroup = MEM_callocN(sizeof(bDeformGroup), __func__);

  BLI_strncpy(defgroup->name, name, sizeof(defgroup->name));

  ListBase *defbase = BKE_object_defgroup_list_mutable(ob);

  BLI_addtail(defbase, defgroup);
  BKE_object_defgroup_unique_name(defgroup, ob);

  BKE_object_batch_cache_dirty_tag(ob);

  return defgroup;
}

void BKE_defgroup_copy_list(ListBase *outbase, const ListBase *inbase)
{
  bDeformGroup *defgroup, *defgroupn;

  BLI_listbase_clear(outbase);

  for (defgroup = inbase->first; defgroup; defgroup = defgroup->next) {
    defgroupn = BKE_defgroup_duplicate(defgroup);
    BLI_addtail(outbase, defgroupn);
  }
}

bDeformGroup *BKE_defgroup_duplicate(const bDeformGroup *ingroup)
{
  bDeformGroup *outgroup;

  if (!ingroup) {
    BLI_assert(0);
    return NULL;
  }

  outgroup = MEM_callocN(sizeof(bDeformGroup), "copy deformGroup");

  /* For now, just copy everything over. */
  memcpy(outgroup, ingroup, sizeof(bDeformGroup));

  outgroup->next = outgroup->prev = NULL;

  return outgroup;
}

/**
 * Overwrite weights filtered by vgroup_subset.
 * - do nothing if neither are set.
 * - add destination weight if needed
 */
void BKE_defvert_copy_subset(MDeformVert *dvert_dst,
                             const MDeformVert *dvert_src,
                             const bool *vgroup_subset,
                             const int vgroup_tot)
{
  int defgroup;
  for (defgroup = 0; defgroup < vgroup_tot; defgroup++) {
    if (vgroup_subset[defgroup]) {
      BKE_defvert_copy_index(dvert_dst, defgroup, dvert_src, defgroup);
    }
  }
}

/**
 * Overwrite weights filtered by vgroup_subset and with mirroring specified by the flip map
 * - do nothing if neither are set.
 * - add destination weight if needed
 */
void BKE_defvert_mirror_subset(MDeformVert *dvert_dst,
                               const MDeformVert *dvert_src,
                               const bool *vgroup_subset,
                               const int vgroup_tot,
                               const int *flip_map,
                               const int flip_map_len)
{
  int defgroup;
  for (defgroup = 0; defgroup < vgroup_tot && defgroup < flip_map_len; defgroup++) {
    if (vgroup_subset[defgroup] && (dvert_dst != dvert_src || flip_map[defgroup] != defgroup)) {
      BKE_defvert_copy_index(dvert_dst, flip_map[defgroup], dvert_src, defgroup);
    }
  }
}

void BKE_defvert_copy(MDeformVert *dvert_dst, const MDeformVert *dvert_src)
{
  if (dvert_dst->totweight == dvert_src->totweight) {
    if (dvert_src->totweight) {
      memcpy(dvert_dst->dw, dvert_src->dw, dvert_src->totweight * sizeof(MDeformWeight));
    }
  }
  else {
    if (dvert_dst->dw) {
      MEM_freeN(dvert_dst->dw);
    }

    if (dvert_src->totweight) {
      dvert_dst->dw = MEM_dupallocN(dvert_src->dw);
    }
    else {
      dvert_dst->dw = NULL;
    }

    dvert_dst->totweight = dvert_src->totweight;
  }
}

/**
 * Copy an index from one dvert to another.
 * - do nothing if neither are set.
 * - add destination weight if needed.
 */
void BKE_defvert_copy_index(MDeformVert *dvert_dst,
                            const int defgroup_dst,
                            const MDeformVert *dvert_src,
                            const int defgroup_src)
{
  MDeformWeight *dw_src, *dw_dst;

  dw_src = BKE_defvert_find_index(dvert_src, defgroup_src);

  if (dw_src) {
    /* Source is valid, ensure destination is created. */
    dw_dst = BKE_defvert_ensure_index(dvert_dst, defgroup_dst);
    dw_dst->weight = dw_src->weight;
  }
  else {
    /* Source was NULL, assign zero (could also remove). */
    dw_dst = BKE_defvert_find_index(dvert_dst, defgroup_dst);

    if (dw_dst) {
      dw_dst->weight = 0.0f;
    }
  }
}

/**
 * Only sync over matching weights, don't add or remove groups
 * warning, loop within loop.
 */
void BKE_defvert_sync(MDeformVert *dvert_dst, const MDeformVert *dvert_src, const bool use_ensure)
{
  if (dvert_src->totweight && dvert_dst->totweight) {
    MDeformWeight *dw_src = dvert_src->dw;
    for (int i = 0; i < dvert_src->totweight; i++, dw_src++) {
      MDeformWeight *dw_dst;
      if (use_ensure) {
        dw_dst = BKE_defvert_ensure_index(dvert_dst, dw_src->def_nr);
      }
      else {
        dw_dst = BKE_defvert_find_index(dvert_dst, dw_src->def_nr);
      }

      if (dw_dst) {
        dw_dst->weight = dw_src->weight;
      }
    }
  }
}

/**
 * be sure all flip_map values are valid
 */
void BKE_defvert_sync_mapped(MDeformVert *dvert_dst,
                             const MDeformVert *dvert_src,
                             const int *flip_map,
                             const int flip_map_len,
                             const bool use_ensure)
{
  if (dvert_src->totweight && dvert_dst->totweight) {
    MDeformWeight *dw_src = dvert_src->dw;
    for (int i = 0; i < dvert_src->totweight; i++, dw_src++) {
      if (dw_src->def_nr < flip_map_len) {
        MDeformWeight *dw_dst;
        if (use_ensure) {
          dw_dst = BKE_defvert_ensure_index(dvert_dst, flip_map[dw_src->def_nr]);
        }
        else {
          dw_dst = BKE_defvert_find_index(dvert_dst, flip_map[dw_src->def_nr]);
        }

        if (dw_dst) {
          dw_dst->weight = dw_src->weight;
        }
      }
    }
  }
}

/**
 * be sure all flip_map values are valid
 */
void BKE_defvert_remap(MDeformVert *dvert, const int *map, const int map_len)
{
  MDeformWeight *dw = dvert->dw;
  for (int i = dvert->totweight; i != 0; i--, dw++) {
    if (dw->def_nr < map_len) {
      BLI_assert(map[dw->def_nr] >= 0);

      dw->def_nr = map[dw->def_nr];
    }
  }
}

/**
 * Same as #BKE_defvert_normalize but takes a bool array.
 */
void BKE_defvert_normalize_subset(MDeformVert *dvert,
                                  const bool *vgroup_subset,
                                  const int vgroup_tot)
{
  if (dvert->totweight == 0) {
    /* nothing */
  }
  else if (dvert->totweight == 1) {
    MDeformWeight *dw = dvert->dw;
    if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
      dw->weight = 1.0f;
    }
  }
  else {
    MDeformWeight *dw = dvert->dw;
    float tot_weight = 0.0f;
    for (int i = dvert->totweight; i != 0; i--, dw++) {
      if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
        tot_weight += dw->weight;
      }
    }

    if (tot_weight > 0.0f) {
      float scalar = 1.0f / tot_weight;
      dw = dvert->dw;
      for (int i = dvert->totweight; i != 0; i--, dw++) {
        if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
          dw->weight *= scalar;

          /* in case of division errors with very low weights */
          CLAMP(dw->weight, 0.0f, 1.0f);
        }
      }
    }
  }
}

void BKE_defvert_normalize(MDeformVert *dvert)
{
  if (dvert->totweight == 0) {
    /* nothing */
  }
  else if (dvert->totweight == 1) {
    dvert->dw[0].weight = 1.0f;
  }
  else {
    MDeformWeight *dw;
    unsigned int i;
    float tot_weight = 0.0f;

    for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
      tot_weight += dw->weight;
    }

    if (tot_weight > 0.0f) {
      float scalar = 1.0f / tot_weight;
      for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
        dw->weight *= scalar;

        /* in case of division errors with very low weights */
        CLAMP(dw->weight, 0.0f, 1.0f);
      }
    }
  }
}

/**
 * Same as BKE_defvert_normalize() if the locked vgroup is not a member of the subset
 */
void BKE_defvert_normalize_lock_single(MDeformVert *dvert,
                                       const bool *vgroup_subset,
                                       const int vgroup_tot,
                                       const uint def_nr_lock)
{
  if (dvert->totweight == 0) {
    /* nothing */
  }
  else if (dvert->totweight == 1) {
    MDeformWeight *dw = dvert->dw;
    if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
      if (def_nr_lock != dw->def_nr) {
        dw->weight = 1.0f;
      }
    }
  }
  else {
    MDeformWeight *dw_lock = NULL;
    MDeformWeight *dw;
    unsigned int i;
    float tot_weight = 0.0f;
    float lock_iweight = 1.0f;

    for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
      if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
        if (dw->def_nr != def_nr_lock) {
          tot_weight += dw->weight;
        }
        else {
          dw_lock = dw;
          lock_iweight = (1.0f - dw_lock->weight);
          CLAMP(lock_iweight, 0.0f, 1.0f);
        }
      }
    }

    if (tot_weight > 0.0f) {
      /* paranoid, should be 1.0 but in case of float error clamp anyway */

      float scalar = (1.0f / tot_weight) * lock_iweight;
      for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
        if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
          if (dw != dw_lock) {
            dw->weight *= scalar;

            /* in case of division errors with very low weights */
            CLAMP(dw->weight, 0.0f, 1.0f);
          }
        }
      }
    }
  }
}

/**
 * Same as BKE_defvert_normalize() if no locked vgroup is a member of the subset
 */
void BKE_defvert_normalize_lock_map(MDeformVert *dvert,
                                    const bool *vgroup_subset,
                                    const int vgroup_tot,
                                    const bool *lock_flags,
                                    const int defbase_tot)
{
  if (dvert->totweight == 0) {
    /* nothing */
  }
  else if (dvert->totweight == 1) {
    MDeformWeight *dw = dvert->dw;
    if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
      if ((dw->def_nr < defbase_tot) && (lock_flags[dw->def_nr] == false)) {
        dw->weight = 1.0f;
      }
    }
  }
  else {
    MDeformWeight *dw;
    unsigned int i;
    float tot_weight = 0.0f;
    float lock_iweight = 0.0f;

    for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
      if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
        if ((dw->def_nr < defbase_tot) && (lock_flags[dw->def_nr] == false)) {
          tot_weight += dw->weight;
        }
        else {
          /* invert after */
          lock_iweight += dw->weight;
        }
      }
    }

    lock_iweight = max_ff(0.0f, 1.0f - lock_iweight);

    if (tot_weight > 0.0f) {
      /* paranoid, should be 1.0 but in case of float error clamp anyway */

      float scalar = (1.0f / tot_weight) * lock_iweight;
      for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
        if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
          if ((dw->def_nr < defbase_tot) && (lock_flags[dw->def_nr] == false)) {
            dw->weight *= scalar;

            /* in case of division errors with very low weights */
            CLAMP(dw->weight, 0.0f, 1.0f);
          }
        }
      }
    }
  }
}

void BKE_defvert_flip(MDeformVert *dvert, const int *flip_map, const int flip_map_len)
{
  MDeformWeight *dw;
  int i;

  for (dw = dvert->dw, i = 0; i < dvert->totweight; dw++, i++) {
    if (dw->def_nr < flip_map_len) {
      if (flip_map[dw->def_nr] >= 0) {
        dw->def_nr = flip_map[dw->def_nr];
      }
    }
  }
}

void BKE_defvert_flip_merged(MDeformVert *dvert, const int *flip_map, const int flip_map_len)
{
  MDeformWeight *dw, *dw_cpy;
  float weight;
  int i, totweight = dvert->totweight;

  /* copy weights */
  for (dw = dvert->dw, i = 0; i < totweight; dw++, i++) {
    if (dw->def_nr < flip_map_len) {
      if (flip_map[dw->def_nr] >= 0) {
        /* error checkers complain of this but we'll never get NULL return */
        dw_cpy = BKE_defvert_ensure_index(dvert, flip_map[dw->def_nr]);
        dw = &dvert->dw[i]; /* in case array got realloced */

        /* distribute weights: if only one of the vertex groups was
         * assigned this will halve the weights, otherwise it gets
         * evened out. this keeps it proportional to other groups */
        weight = 0.5f * (dw_cpy->weight + dw->weight);
        dw_cpy->weight = weight;
        dw->weight = weight;
      }
    }
  }
}

bool BKE_object_supports_vertex_groups(const Object *ob)
{
  const ID *id = (const ID *)ob->data;
  if (id == NULL) {
    return false;
  }

  return ELEM(GS(id->name), ID_ME, ID_LT, ID_GD);
}

const ListBase *BKE_id_defgroup_list_get(const ID *id)
{
  switch (GS(id->name)) {
    case ID_ME: {
      const Mesh *me = (const Mesh *)id;
      return &me->vertex_group_names;
    }
    case ID_LT: {
      const Lattice *lt = (const Lattice *)id;
      return &lt->vertex_group_names;
    }
    case ID_GD: {
      const bGPdata *gpd = (const bGPdata *)id;
      return &gpd->vertex_group_names;
    }
    default: {
      BLI_assert_unreachable();
    }
  }
  return NULL;
}

static const int *object_defgroup_active_index_get_p(const Object *ob)
{
  BLI_assert(BKE_object_supports_vertex_groups(ob));
  switch (ob->type) {
    case OB_MESH: {
      const Mesh *mesh = (const Mesh *)ob->data;
      return &mesh->vertex_group_active_index;
    }
    case OB_LATTICE: {
      const Lattice *lattice = (const Lattice *)ob->data;
      return &lattice->vertex_group_active_index;
    }
    case OB_GPENCIL: {
      const bGPdata *gpd = (const bGPdata *)ob->data;
      return &gpd->vertex_group_active_index;
    }
  }
  return NULL;
}

ListBase *BKE_id_defgroup_list_get_mutable(ID *id)
{
  /* Cast away const just for the accessor. */
  return (ListBase *)BKE_id_defgroup_list_get(id);
}

bDeformGroup *BKE_object_defgroup_find_name(const Object *ob, const char *name)
{
  if (name == NULL || name[0] == '\0') {
    return NULL;
  }
  const ListBase *defbase = BKE_object_defgroup_list(ob);
  return BLI_findstring(defbase, name, offsetof(bDeformGroup, name));
}

int BKE_id_defgroup_name_index(const ID *id, const char *name)
{
  if (name == NULL || name[0] == '\0') {
    return -1;
  }
  const ListBase *defbase = BKE_id_defgroup_list_get(id);
  return BLI_findstringindex(defbase, name, offsetof(bDeformGroup, name));
}

const ListBase *BKE_object_defgroup_list(const Object *ob)
{
  BLI_assert(BKE_object_supports_vertex_groups(ob));
  return BKE_id_defgroup_list_get((const ID *)ob->data);
}

int BKE_object_defgroup_name_index(const Object *ob, const char *name)
{
  return BKE_id_defgroup_name_index((ID *)ob->data, name);
}

ListBase *BKE_object_defgroup_list_mutable(Object *ob)
{
  BLI_assert(BKE_object_supports_vertex_groups(ob));
  return BKE_id_defgroup_list_get_mutable((ID *)ob->data);
}

int BKE_object_defgroup_count(const Object *ob)
{
  return BLI_listbase_count(BKE_object_defgroup_list(ob));
}

/**
 * \note For historical reasons, the index starts at 1 rather than 0.
 */
int BKE_object_defgroup_active_index_get(const Object *ob)
{
  return *object_defgroup_active_index_get_p(ob);
}

/**
 * \note For historical reasons, the index starts at 1 rather than 0.
 */
void BKE_object_defgroup_active_index_set(Object *ob, const int new_index)
{
  /* Cast away const just for the accessor. */
  int *index = (int *)object_defgroup_active_index_get_p(ob);
  *index = new_index;
}

/**
 * \note caller must free.
 */
int *BKE_object_defgroup_flip_map(const Object *ob, int *flip_map_len, const bool use_default)
{
  const ListBase *defbase = BKE_object_defgroup_list(ob);
  int defbase_tot = *flip_map_len = BLI_listbase_count(defbase);

  if (defbase_tot == 0) {
    return NULL;
  }

  bDeformGroup *dg;
  char name_flip[sizeof(dg->name)];
  int i, flip_num, *map = MEM_mallocN(defbase_tot * sizeof(int), __func__);

  for (i = 0; i < defbase_tot; i++) {
    map[i] = -1;
  }

  for (dg = defbase->first, i = 0; dg; dg = dg->next, i++) {
    if (map[i] == -1) { /* may be calculated previously */

      /* in case no valid value is found, use this */
      if (use_default) {
        map[i] = i;
      }

      BLI_string_flip_side_name(name_flip, dg->name, false, sizeof(name_flip));

      if (!STREQ(name_flip, dg->name)) {
        flip_num = BKE_object_defgroup_name_index(ob, name_flip);
        if (flip_num >= 0) {
          map[i] = flip_num;
          map[flip_num] = i; /* save an extra lookup */
        }
      }
    }
  }
  return map;
}

/**
 * \note caller must free.
 */
int *BKE_object_defgroup_flip_map_single(const Object *ob,
                                         int *flip_map_len,
                                         const bool use_default,
                                         int defgroup)
{
  const ListBase *defbase = BKE_object_defgroup_list(ob);
  int defbase_tot = *flip_map_len = BLI_listbase_count(defbase);

  if (defbase_tot == 0) {
    return NULL;
  }

  bDeformGroup *dg;
  char name_flip[sizeof(dg->name)];
  int i, flip_num, *map = MEM_mallocN(defbase_tot * sizeof(int), __func__);

  for (i = 0; i < defbase_tot; i++) {
    map[i] = use_default ? i : -1;
  }

  dg = BLI_findlink(defbase, defgroup);

  BLI_string_flip_side_name(name_flip, dg->name, false, sizeof(name_flip));
  if (!STREQ(name_flip, dg->name)) {
    flip_num = BKE_object_defgroup_name_index(ob, name_flip);

    if (flip_num != -1) {
      map[defgroup] = flip_num;
      map[flip_num] = defgroup;
    }
  }

  return map;
}

int BKE_object_defgroup_flip_index(const Object *ob, int index, const bool use_default)
{
  const ListBase *defbase = BKE_object_defgroup_list(ob);
  bDeformGroup *dg = BLI_findlink(defbase, index);
  int flip_index = -1;

  if (dg) {
    char name_flip[sizeof(dg->name)];
    BLI_string_flip_side_name(name_flip, dg->name, false, sizeof(name_flip));

    if (!STREQ(name_flip, dg->name)) {
      flip_index = BKE_object_defgroup_name_index(ob, name_flip);
    }
  }

  return (flip_index == -1 && use_default) ? index : flip_index;
}

static bool defgroup_find_name_dupe(const char *name, bDeformGroup *dg, Object *ob)
{
  const ListBase *defbase = BKE_object_defgroup_list(ob);
  bDeformGroup *curdef;

  for (curdef = defbase->first; curdef; curdef = curdef->next) {
    if (dg != curdef) {
      if (STREQ(curdef->name, name)) {
        return true;
      }
    }
  }

  return false;
}

static bool defgroup_unique_check(void *arg, const char *name)
{
  struct {
    Object *ob;
    void *dg;
  } *data = arg;
  return defgroup_find_name_dupe(name, data->dg, data->ob);
}

void BKE_object_defgroup_unique_name(bDeformGroup *dg, Object *ob)
{
  struct {
    Object *ob;
    void *dg;
  } data;
  data.ob = ob;
  data.dg = dg;

  BLI_uniquename_cb(defgroup_unique_check, &data, DATA_("Group"), '.', dg->name, sizeof(dg->name));
}

float BKE_defvert_find_weight(const struct MDeformVert *dvert, const int defgroup)
{
  MDeformWeight *dw = BKE_defvert_find_index(dvert, defgroup);
  return dw ? dw->weight : 0.0f;
}

/**
 * Take care with this the rationale is:
 * - if the object has no vertex group. act like vertex group isn't set and return 1.0,
 * - if the vertex group exists but the 'defgroup' isn't found on this vertex, _still_ return 0.0
 *
 * This is a bit confusing, just saves some checks from the caller.
 */
float BKE_defvert_array_find_weight_safe(const struct MDeformVert *dvert,
                                         const int index,
                                         const int defgroup)
{
  /* Invalid defgroup index means the vgroup selected is invalid,
   * does not exist, in that case it is OK to return 1.0
   * (i.e. maximum weight, as if no vgroup was selected).
   * But in case of valid defgroup and NULL dvert data pointer, it means that vgroup **is** valid,
   * and just totally empty, so we shall return '0.0' value then! */
  if (defgroup == -1) {
    return 1.0f;
  }
  if (dvert == NULL) {
    return 0.0f;
  }

  return BKE_defvert_find_weight(dvert + index, defgroup);
}

MDeformWeight *BKE_defvert_find_index(const MDeformVert *dvert, const int defgroup)
{
  if (dvert && defgroup >= 0) {
    MDeformWeight *dw = dvert->dw;
    unsigned int i;

    for (i = dvert->totweight; i != 0; i--, dw++) {
      if (dw->def_nr == defgroup) {
        return dw;
      }
    }
  }
  else {
    BLI_assert(0);
  }

  return NULL;
}

/**
 * Ensures that mv has a deform weight entry for the specified defweight group.
 *
 * \note this function is mirrored in editmesh_tools.c, for use for editvertices.
 */
MDeformWeight *BKE_defvert_ensure_index(MDeformVert *dvert, const int defgroup)
{
  MDeformWeight *dw_new;

  /* do this check always, this function is used to check for it */
  if (!dvert || defgroup < 0) {
    BLI_assert(0);
    return NULL;
  }

  dw_new = BKE_defvert_find_index(dvert, defgroup);
  if (dw_new) {
    return dw_new;
  }

  dw_new = MEM_mallocN(sizeof(MDeformWeight) * (dvert->totweight + 1), "deformWeight");
  if (dvert->dw) {
    memcpy(dw_new, dvert->dw, sizeof(MDeformWeight) * dvert->totweight);
    MEM_freeN(dvert->dw);
  }
  dvert->dw = dw_new;
  dw_new += dvert->totweight;
  dw_new->weight = 0.0f;
  dw_new->def_nr = defgroup;
  /* Group index */

  dvert->totweight++;

  return dw_new;
}

/* TODO: merge with code above! */

/**
 * Adds the given vertex to the specified vertex group, with given weight.
 *
 * \warning this does NOT check for existing, assume caller already knows its not there.
 */
void BKE_defvert_add_index_notest(MDeformVert *dvert, int defgroup, const float weight)
{
  MDeformWeight *dw_new;

  /* do this check always, this function is used to check for it */
  if (!dvert || defgroup < 0) {
    BLI_assert(0);
    return;
  }

  dw_new = MEM_callocN(sizeof(MDeformWeight) * (dvert->totweight + 1),
                       "defvert_add_to group, new deformWeight");
  if (dvert->dw) {
    memcpy(dw_new, dvert->dw, sizeof(MDeformWeight) * dvert->totweight);
    MEM_freeN(dvert->dw);
  }
  dvert->dw = dw_new;
  dw_new += dvert->totweight;
  dw_new->weight = weight;
  dw_new->def_nr = defgroup;
  dvert->totweight++;
}

/**
 * Removes the given vertex from the vertex group.
 *
 * \warning This function frees the given MDeformWeight, do not use it afterward!
 */
void BKE_defvert_remove_group(MDeformVert *dvert, MDeformWeight *dw)
{
  if (dvert && dw) {
    int i = dw - dvert->dw;

    /* Security check! */
    if (i < 0 || i >= dvert->totweight) {
      return;
    }

    dvert->totweight--;
    /* If there are still other deform weights attached to this vert then remove
     * this deform weight, and reshuffle the others.
     */
    if (dvert->totweight) {
      BLI_assert(dvert->dw != NULL);

      if (i != dvert->totweight) {
        dvert->dw[i] = dvert->dw[dvert->totweight];
      }

      dvert->dw = MEM_reallocN(dvert->dw, sizeof(MDeformWeight) * dvert->totweight);
    }
    else {
      /* If there are no other deform weights left then just remove this one. */
      MEM_freeN(dvert->dw);
      dvert->dw = NULL;
    }
  }
}

void BKE_defvert_clear(MDeformVert *dvert)
{
  if (dvert->dw) {
    MEM_freeN(dvert->dw);
    dvert->dw = NULL;
  }

  dvert->totweight = 0;
}

/**
 * \return The first group index shared by both deform verts
 * or -1 if none are found.
 */
int BKE_defvert_find_shared(const MDeformVert *dvert_a, const MDeformVert *dvert_b)
{
  if (dvert_a->totweight && dvert_b->totweight) {
    MDeformWeight *dw = dvert_a->dw;
    unsigned int i;

    for (i = dvert_a->totweight; i != 0; i--, dw++) {
      if (dw->weight > 0.0f && BKE_defvert_find_weight(dvert_b, dw->def_nr) > 0.0f) {
        return dw->def_nr;
      }
    }
  }

  return -1;
}

/**
 * return true if has no weights
 */
bool BKE_defvert_is_weight_zero(const struct MDeformVert *dvert, const int defgroup_tot)
{
  MDeformWeight *dw = dvert->dw;
  for (int i = dvert->totweight; i != 0; i--, dw++) {
    if (dw->weight != 0.0f) {
      /* check the group is in-range, happens on rare situations */
      if (LIKELY(dw->def_nr < defgroup_tot)) {
        return false;
      }
    }
  }
  return true;
}

/**
 * \return The total weight in all groups marked in the selection mask.
 */
float BKE_defvert_total_selected_weight(const struct MDeformVert *dv,
                                        int defbase_tot,
                                        const bool *defbase_sel)
{
  float total = 0.0f;
  const MDeformWeight *dw = dv->dw;

  if (defbase_sel == NULL) {
    return total;
  }

  for (int i = dv->totweight; i != 0; i--, dw++) {
    if (dw->def_nr < defbase_tot) {
      if (defbase_sel[dw->def_nr]) {
        total += dw->weight;
      }
    }
  }

  return total;
}

/**
 * \return The representative weight of a multipaint group, used for
 * viewport colors and actual painting.
 *
 * Result equal to sum of weights with auto normalize, and average otherwise.
 * Value is not clamped, since painting relies on multiplication being always
 * commutative with the collective weight function.
 */
float BKE_defvert_multipaint_collective_weight(const struct MDeformVert *dv,
                                               int defbase_tot,
                                               const bool *defbase_sel,
                                               int defbase_tot_sel,
                                               bool is_normalized)
{
  float total = BKE_defvert_total_selected_weight(dv, defbase_tot, defbase_sel);

  /* in multipaint, get the average if auto normalize is inactive
   * get the sum if it is active */
  if (!is_normalized) {
    total /= defbase_tot_sel;
  }

  return total;
}

/**
 * Computes the display weight for the lock relative weight paint mode.
 *
 * \return weight divided by 1-locked_weight with division by zero check
 */
float BKE_defvert_calc_lock_relative_weight(float weight,
                                            float locked_weight,
                                            float unlocked_weight)
{
  /* First try normalizing unlocked weights. */
  if (unlocked_weight > 0.0f) {
    return weight / unlocked_weight;
  }

  /* If no unlocked weight exists, take locked into account. */
  if (locked_weight <= 0.0f) {
    return weight;
  }

  /* handle division by zero */
  if (locked_weight >= 1.0f - VERTEX_WEIGHT_LOCK_EPSILON) {
    if (weight != 0.0f) {
      return 1.0f;
    }

    /* resolve 0/0 to 0 */
    return 0.0f;
  }

  /* non-degenerate division */
  return weight / (1.0f - locked_weight);
}

/**
 * Computes the display weight for the lock relative weight paint mode, using weight data.
 *
 * \return weight divided by unlocked, or 1-locked_weight with division by zero check.
 */
float BKE_defvert_lock_relative_weight(float weight,
                                       const struct MDeformVert *dv,
                                       int defbase_tot,
                                       const bool *defbase_locked,
                                       const bool *defbase_unlocked)
{
  float unlocked = BKE_defvert_total_selected_weight(dv, defbase_tot, defbase_unlocked);

  if (unlocked > 0.0f) {
    return weight / unlocked;
  }

  float locked = BKE_defvert_total_selected_weight(dv, defbase_tot, defbase_locked);

  return BKE_defvert_calc_lock_relative_weight(weight, locked, unlocked);
}

/* -------------------------------------------------------------------- */
/** \name Defvert Array functions
 * \{ */

void BKE_defvert_array_copy(MDeformVert *dst, const MDeformVert *src, int totvert)
{
  /* Assumes dst is already set up */

  if (!src || !dst) {
    return;
  }

  memcpy(dst, src, totvert * sizeof(MDeformVert));

  for (int i = 0; i < totvert; i++) {
    if (src[i].dw) {
      dst[i].dw = MEM_mallocN(sizeof(MDeformWeight) * src[i].totweight, "copy_deformWeight");
      memcpy(dst[i].dw, src[i].dw, sizeof(MDeformWeight) * src[i].totweight);
    }
  }
}

void BKE_defvert_array_free_elems(MDeformVert *dvert, int totvert)
{
  /* Instead of freeing the verts directly,
   * call this function to delete any special
   * vert data */

  if (!dvert) {
    return;
  }

  /* Free any special data from the verts */
  for (int i = 0; i < totvert; i++) {
    if (dvert[i].dw) {
      MEM_freeN(dvert[i].dw);
    }
  }
}

void BKE_defvert_array_free(MDeformVert *dvert, int totvert)
{
  /* Instead of freeing the verts directly,
   * call this function to delete any special
   * vert data */
  if (!dvert) {
    return;
  }

  /* Free any special data from the verts */
  BKE_defvert_array_free_elems(dvert, totvert);

  MEM_freeN(dvert);
}

void BKE_defvert_extract_vgroup_to_vertweights(MDeformVert *dvert,
                                               const int defgroup,
                                               const int num_verts,
                                               float *r_weights,
                                               const bool invert_vgroup)
{
  if (dvert && defgroup != -1) {
    int i = num_verts;

    while (i--) {
      const float w = BKE_defvert_find_weight(&dvert[i], defgroup);
      r_weights[i] = invert_vgroup ? (1.0f - w) : w;
    }
  }
  else {
    copy_vn_fl(r_weights, num_verts, invert_vgroup ? 1.0f : 0.0f);
  }
}

/**
 * The following three make basic interpolation,
 * using temp vert_weights array to avoid looking up same weight several times.
 */
void BKE_defvert_extract_vgroup_to_edgeweights(MDeformVert *dvert,
                                               const int defgroup,
                                               const int num_verts,
                                               MEdge *edges,
                                               const int num_edges,
                                               float *r_weights,
                                               const bool invert_vgroup)
{
  if (dvert && defgroup != -1) {
    int i = num_edges;
    float *tmp_weights = MEM_mallocN(sizeof(*tmp_weights) * (size_t)num_verts, __func__);

    BKE_defvert_extract_vgroup_to_vertweights(
        dvert, defgroup, num_verts, tmp_weights, invert_vgroup);

    while (i--) {
      MEdge *me = &edges[i];

      r_weights[i] = (tmp_weights[me->v1] + tmp_weights[me->v2]) * 0.5f;
    }

    MEM_freeN(tmp_weights);
  }
  else {
    copy_vn_fl(r_weights, num_edges, 0.0f);
  }
}

void BKE_defvert_extract_vgroup_to_loopweights(MDeformVert *dvert,
                                               const int defgroup,
                                               const int num_verts,
                                               MLoop *loops,
                                               const int num_loops,
                                               float *r_weights,
                                               const bool invert_vgroup)
{
  if (dvert && defgroup != -1) {
    int i = num_loops;
    float *tmp_weights = MEM_mallocN(sizeof(*tmp_weights) * (size_t)num_verts, __func__);

    BKE_defvert_extract_vgroup_to_vertweights(
        dvert, defgroup, num_verts, tmp_weights, invert_vgroup);

    while (i--) {
      MLoop *ml = &loops[i];

      r_weights[i] = tmp_weights[ml->v];
    }

    MEM_freeN(tmp_weights);
  }
  else {
    copy_vn_fl(r_weights, num_loops, 0.0f);
  }
}

void BKE_defvert_extract_vgroup_to_polyweights(MDeformVert *dvert,
                                               const int defgroup,
                                               const int num_verts,
                                               MLoop *loops,
                                               const int UNUSED(num_loops),
                                               MPoly *polys,
                                               const int num_polys,
                                               float *r_weights,
                                               const bool invert_vgroup)
{
  if (dvert && defgroup != -1) {
    int i = num_polys;
    float *tmp_weights = MEM_mallocN(sizeof(*tmp_weights) * (size_t)num_verts, __func__);

    BKE_defvert_extract_vgroup_to_vertweights(
        dvert, defgroup, num_verts, tmp_weights, invert_vgroup);

    while (i--) {
      MPoly *mp = &polys[i];
      MLoop *ml = &loops[mp->loopstart];
      int j = mp->totloop;
      float w = 0.0f;

      for (; j--; ml++) {
        w += tmp_weights[ml->v];
      }
      r_weights[i] = w / (float)mp->totloop;
    }

    MEM_freeN(tmp_weights);
  }
  else {
    copy_vn_fl(r_weights, num_polys, 0.0f);
  }
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Data Transfer
 * \{ */

static void vgroups_datatransfer_interp(const CustomDataTransferLayerMap *laymap,
                                        void *dest,
                                        const void **sources,
                                        const float *weights,
                                        const int count,
                                        const float mix_factor)
{
  MDeformVert **data_src = (MDeformVert **)sources;
  MDeformVert *data_dst = (MDeformVert *)dest;
  const int idx_src = laymap->data_src_n;
  const int idx_dst = laymap->data_dst_n;

  const int mix_mode = laymap->mix_mode;

  int i, j;

  MDeformWeight *dw_src;
  MDeformWeight *dw_dst = BKE_defvert_find_index(data_dst, idx_dst);
  float weight_src = 0.0f, weight_dst = 0.0f;

  bool has_dw_sources = false;
  if (sources) {
    for (i = count; i--;) {
      for (j = data_src[i]->totweight; j--;) {
        if ((dw_src = &data_src[i]->dw[j])->def_nr == idx_src) {
          weight_src += dw_src->weight * weights[i];
          has_dw_sources = true;
          break;
        }
      }
    }
  }

  if (dw_dst) {
    weight_dst = dw_dst->weight;
  }
  else if (mix_mode == CDT_MIX_REPLACE_ABOVE_THRESHOLD) {
    return; /* Do not affect destination. */
  }

  weight_src = data_transfer_interp_float_do(mix_mode, weight_dst, weight_src, mix_factor);

  CLAMP(weight_src, 0.0f, 1.0f);

  /* Do not create a destination MDeformWeight data if we had no sources at all. */
  if (!has_dw_sources) {
    BLI_assert(weight_src == 0.0f);
    if (dw_dst) {
      dw_dst->weight = weight_src;
    }
  }
  else if (!dw_dst) {
    BKE_defvert_add_index_notest(data_dst, idx_dst, weight_src);
  }
  else {
    dw_dst->weight = weight_src;
  }
}

static bool data_transfer_layersmapping_vgroups_multisrc_to_dst(ListBase *r_map,
                                                                const int mix_mode,
                                                                const float mix_factor,
                                                                const float *mix_weights,
                                                                const int num_elem_dst,
                                                                const bool use_create,
                                                                const bool use_delete,
                                                                Object *ob_src,
                                                                Object *ob_dst,
                                                                MDeformVert *data_src,
                                                                MDeformVert *data_dst,
                                                                CustomData *UNUSED(cd_src),
                                                                CustomData *cd_dst,
                                                                const bool UNUSED(use_dupref_dst),
                                                                const int tolayers,
                                                                const bool *use_layers_src,
                                                                const int num_layers_src)
{
  int idx_src;
  int idx_dst;
  const ListBase *src_list = BKE_object_defgroup_list(ob_src);
  ListBase *dst_defbase = BKE_object_defgroup_list_mutable(ob_dst);

  int tot_dst = BLI_listbase_count(dst_defbase);

  const size_t elem_size = sizeof(*((MDeformVert *)NULL));

  switch (tolayers) {
    case DT_LAYERS_INDEX_DST:
      idx_dst = tot_dst;

      /* Find last source actually used! */
      idx_src = num_layers_src;
      while (idx_src-- && !use_layers_src[idx_src]) {
        /* pass */
      }
      idx_src++;

      if (idx_dst < idx_src) {
        if (use_create) {
          /* Create as much vgroups as necessary! */
          for (; idx_dst < idx_src; idx_dst++) {
            BKE_object_defgroup_add(ob_dst);
          }
        }
        else {
          /* Otherwise, just try to map what we can with existing dst vgroups. */
          idx_src = idx_dst;
        }
      }
      else if (use_delete && idx_dst > idx_src) {
        while (idx_dst-- > idx_src) {
          BKE_object_defgroup_remove(ob_dst, dst_defbase->last);
        }
      }
      if (r_map) {
        /* At this stage, we **need** a valid CD_MDEFORMVERT layer on dest!
         * Again, use_create is not relevant in this case */
        if (!data_dst) {
          data_dst = CustomData_add_layer(cd_dst, CD_MDEFORMVERT, CD_CALLOC, NULL, num_elem_dst);
        }

        while (idx_src--) {
          if (!use_layers_src[idx_src]) {
            continue;
          }
          data_transfer_layersmapping_add_item(r_map,
                                               CD_FAKE_MDEFORMVERT,
                                               mix_mode,
                                               mix_factor,
                                               mix_weights,
                                               data_src,
                                               data_dst,
                                               idx_src,
                                               idx_src,
                                               elem_size,
                                               0,
                                               0,
                                               0,
                                               vgroups_datatransfer_interp,
                                               NULL);
        }
      }
      break;
    case DT_LAYERS_NAME_DST: {
      bDeformGroup *dg_src, *dg_dst;

      if (use_delete) {
        /* Remove all unused dst vgroups first, simpler in this case. */
        for (dg_dst = dst_defbase->first; dg_dst;) {
          bDeformGroup *dg_dst_next = dg_dst->next;

          if (BKE_object_defgroup_name_index(ob_src, dg_dst->name) == -1) {
            BKE_object_defgroup_remove(ob_dst, dg_dst);
          }
          dg_dst = dg_dst_next;
        }
      }

      for (idx_src = 0, dg_src = src_list->first; idx_src < num_layers_src;
           idx_src++, dg_src = dg_src->next) {
        if (!use_layers_src[idx_src]) {
          continue;
        }

        if ((idx_dst = BKE_object_defgroup_name_index(ob_dst, dg_src->name)) == -1) {
          if (use_create) {
            BKE_object_defgroup_add_name(ob_dst, dg_src->name);
            idx_dst = BKE_object_defgroup_active_index_get(ob_dst) - 1;
          }
          else {
            /* If we are not allowed to create missing dst vgroups, just skip matching src one. */
            continue;
          }
        }
        if (r_map) {
          /* At this stage, we **need** a valid CD_MDEFORMVERT layer on dest!
           * use_create is not relevant in this case */
          if (!data_dst) {
            data_dst = CustomData_add_layer(cd_dst, CD_MDEFORMVERT, CD_CALLOC, NULL, num_elem_dst);
          }

          data_transfer_layersmapping_add_item(r_map,
                                               CD_FAKE_MDEFORMVERT,
                                               mix_mode,
                                               mix_factor,
                                               mix_weights,
                                               data_src,
                                               data_dst,
                                               idx_src,
                                               idx_dst,
                                               elem_size,
                                               0,
                                               0,
                                               0,
                                               vgroups_datatransfer_interp,
                                               NULL);
        }
      }
      break;
    }
    default:
      return false;
  }

  return true;
}

bool data_transfer_layersmapping_vgroups(ListBase *r_map,
                                         const int mix_mode,
                                         const float mix_factor,
                                         const float *mix_weights,
                                         const int num_elem_dst,
                                         const bool use_create,
                                         const bool use_delete,
                                         Object *ob_src,
                                         Object *ob_dst,
                                         CustomData *cd_src,
                                         CustomData *cd_dst,
                                         const bool use_dupref_dst,
                                         const int fromlayers,
                                         const int tolayers)
{
  int idx_src, idx_dst;
  MDeformVert *data_src, *data_dst = NULL;

  const size_t elem_size = sizeof(*((MDeformVert *)NULL));

  /* NOTE:
   * VGroups are a bit hairy, since their layout is defined on object level (ob->defbase),
   * while their actual data is a (mesh) CD layer.
   * This implies we may have to handle data layout itself while having NULL data itself,
   * and even have to support NULL data_src in transfer data code
   * (we always create a data_dst, though).
   *
   * Note: Above comment is outdated, but this function was written when that was true.
   */

  const ListBase *src_defbase = BKE_object_defgroup_list(ob_src);
  if (BLI_listbase_is_empty(src_defbase)) {
    if (use_delete) {
      BKE_object_defgroup_remove_all(ob_dst);
    }
    return true;
  }

  data_src = CustomData_get_layer(cd_src, CD_MDEFORMVERT);

  data_dst = CustomData_get_layer(cd_dst, CD_MDEFORMVERT);
  if (data_dst && use_dupref_dst && r_map) {
    /* If dest is a derivedmesh, we do not want to overwrite cdlayers of org mesh! */
    data_dst = CustomData_duplicate_referenced_layer(cd_dst, CD_MDEFORMVERT, num_elem_dst);
  }

  if (fromlayers == DT_LAYERS_ACTIVE_SRC || fromlayers >= 0) {
    /* NOTE: use_delete has not much meaning in this case, ignored. */

    if (fromlayers >= 0) {
      idx_src = fromlayers;
      if (idx_src >= BLI_listbase_count(src_defbase)) {
        /* This can happen when vgroups are removed from source object...
         * Remapping would be really tricky here, we'd need to go over all objects in
         * Main every time we delete a vgroup... for now, simpler and safer to abort. */
        return false;
      }
    }
    else if ((idx_src = BKE_object_defgroup_active_index_get(ob_src) - 1) == -1) {
      return false;
    }

    if (tolayers >= 0) {
      /* NOTE: in this case we assume layer exists! */
      idx_dst = tolayers;
      const ListBase *dst_defbase = BKE_object_defgroup_list(ob_dst);
      BLI_assert(idx_dst < BLI_listbase_count(dst_defbase));
      UNUSED_VARS_NDEBUG(dst_defbase);
    }
    else if (tolayers == DT_LAYERS_ACTIVE_DST) {
      if ((idx_dst = BKE_object_defgroup_active_index_get(ob_dst) - 1) == -1) {
        bDeformGroup *dg_src;
        if (!use_create) {
          return true;
        }
        dg_src = BLI_findlink(src_defbase, idx_src);
        BKE_object_defgroup_add_name(ob_dst, dg_src->name);
        idx_dst = BKE_object_defgroup_active_index_get(ob_dst) - 1;
      }
    }
    else if (tolayers == DT_LAYERS_INDEX_DST) {
      int num = BLI_listbase_count(src_defbase);
      idx_dst = idx_src;
      if (num <= idx_dst) {
        if (!use_create) {
          return true;
        }
        /* Create as much vgroups as necessary! */
        for (; num <= idx_dst; num++) {
          BKE_object_defgroup_add(ob_dst);
        }
      }
    }
    else if (tolayers == DT_LAYERS_NAME_DST) {
      bDeformGroup *dg_src = BLI_findlink(src_defbase, idx_src);
      if ((idx_dst = BKE_object_defgroup_name_index(ob_dst, dg_src->name)) == -1) {
        if (!use_create) {
          return true;
        }
        BKE_object_defgroup_add_name(ob_dst, dg_src->name);
        idx_dst = BKE_object_defgroup_active_index_get(ob_dst) - 1;
      }
    }
    else {
      return false;
    }

    if (r_map) {
      /* At this stage, we **need** a valid CD_MDEFORMVERT layer on dest!
       * use_create is not relevant in this case */
      if (!data_dst) {
        data_dst = CustomData_add_layer(cd_dst, CD_MDEFORMVERT, CD_CALLOC, NULL, num_elem_dst);
      }

      data_transfer_layersmapping_add_item(r_map,
                                           CD_FAKE_MDEFORMVERT,
                                           mix_mode,
                                           mix_factor,
                                           mix_weights,
                                           data_src,
                                           data_dst,
                                           idx_src,
                                           idx_dst,
                                           elem_size,
                                           0,
                                           0,
                                           0,
                                           vgroups_datatransfer_interp,
                                           NULL);
    }
  }
  else {
    int num_src, num_sel_unused;
    bool *use_layers_src = NULL;
    bool ret = false;

    switch (fromlayers) {
      case DT_LAYERS_ALL_SRC:
        use_layers_src = BKE_object_defgroup_subset_from_select_type(
            ob_src, WT_VGROUP_ALL, &num_src, &num_sel_unused);
        break;
      case DT_LAYERS_VGROUP_SRC_BONE_SELECT:
        use_layers_src = BKE_object_defgroup_subset_from_select_type(
            ob_src, WT_VGROUP_BONE_SELECT, &num_src, &num_sel_unused);
        break;
      case DT_LAYERS_VGROUP_SRC_BONE_DEFORM:
        use_layers_src = BKE_object_defgroup_subset_from_select_type(
            ob_src, WT_VGROUP_BONE_DEFORM, &num_src, &num_sel_unused);
        break;
    }

    if (use_layers_src) {
      ret = data_transfer_layersmapping_vgroups_multisrc_to_dst(r_map,
                                                                mix_mode,
                                                                mix_factor,
                                                                mix_weights,
                                                                num_elem_dst,
                                                                use_create,
                                                                use_delete,
                                                                ob_src,
                                                                ob_dst,
                                                                data_src,
                                                                data_dst,
                                                                cd_src,
                                                                cd_dst,
                                                                use_dupref_dst,
                                                                tolayers,
                                                                use_layers_src,
                                                                num_src);
    }

    MEM_SAFE_FREE(use_layers_src);
    return ret;
  }

  return true;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Various utils & helpers.
 * \{ */

void BKE_defvert_weight_to_rgb(float r_rgb[3], const float weight)
{
  const float blend = ((weight / 2.0f) + 0.5f);

  if (weight <= 0.25f) { /* blue->cyan */
    r_rgb[0] = 0.0f;
    r_rgb[1] = blend * weight * 4.0f;
    r_rgb[2] = blend;
  }
  else if (weight <= 0.50f) { /* cyan->green */
    r_rgb[0] = 0.0f;
    r_rgb[1] = blend;
    r_rgb[2] = blend * (1.0f - ((weight - 0.25f) * 4.0f));
  }
  else if (weight <= 0.75f) { /* green->yellow */
    r_rgb[0] = blend * ((weight - 0.50f) * 4.0f);
    r_rgb[1] = blend;
    r_rgb[2] = 0.0f;
  }
  else if (weight <= 1.0f) { /* yellow->red */
    r_rgb[0] = blend;
    r_rgb[1] = blend * (1.0f - ((weight - 0.75f) * 4.0f));
    r_rgb[2] = 0.0f;
  }
  else {
    /* exceptional value, unclamped or nan,
     * avoid uninitialized memory use */
    r_rgb[0] = 1.0f;
    r_rgb[1] = 0.0f;
    r_rgb[2] = 1.0f;
  }
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name .blend file I/O
 * \{ */

void BKE_defbase_blend_write(BlendWriter *writer, const ListBase *defbase)
{
  LISTBASE_FOREACH (bDeformGroup *, defgroup, defbase) {
    BLO_write_struct(writer, bDeformGroup, defgroup);
  }
}

void BKE_defvert_blend_write(BlendWriter *writer, int count, MDeformVert *dvlist)
{
  if (dvlist == NULL) {
    return;
  }

  /* Write the dvert list */
  BLO_write_struct_array(writer, MDeformVert, count, dvlist);

  /* Write deformation data for each dvert */
  for (int i = 0; i < count; i++) {
    if (dvlist[i].dw) {
      BLO_write_struct_array(writer, MDeformWeight, dvlist[i].totweight, dvlist[i].dw);
    }
  }
}

void BKE_defvert_blend_read(BlendDataReader *reader, int count, MDeformVert *mdverts)
{
  if (mdverts == NULL) {
    return;
  }

  for (int i = count; i > 0; i--, mdverts++) {
    /* Convert to vertex group allocation system. */
    MDeformWeight *dw;
    if (mdverts->dw && (dw = BLO_read_get_new_data_address(reader, mdverts->dw))) {
      const size_t dw_len = sizeof(MDeformWeight) * mdverts->totweight;
      void *dw_tmp = MEM_mallocN(dw_len, __func__);
      memcpy(dw_tmp, dw, dw_len);
      mdverts->dw = dw_tmp;
      MEM_freeN(dw);
    }
    else {
      mdverts->dw = NULL;
      mdverts->totweight = 0;
    }
  }
}

/** \} */