aada 0.1.1

纯 Rust 的 2D 骨骼动画引擎,兼容 Spine 4.x 导出格式(JSON + atlas)。求解到分层 Mesh 与各 Mesh 渲染设置为止,之后交给渲染器。
Documentation
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
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
//! 动画的序列化中间结构(store 层)与 spine 动画 JSON 解析。

use serde::{Deserialize, Serialize};

use crate::{
    data::runtime::{
        animate::{
            AnimationRT, BezierCurve, BoneChannel, Curve, Keyframe, SlotChannel, SlotKeyframe,
            SlotTimeline, Timeline,
        },
        skeleton::Skeleton,
        slot::SlotSet,
    },
    error::Error,
};

/// 存储用的动画数据,可以序列化为 JSON 文件格式
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AnimationDataStore {
    /// 动画名称(唯一标识符)
    pub name: String,
    pub timelines: Vec<TimelineDataStore>,
    /// slot 动画时间轴(颜色 / attachment 切换)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub slot_timelines: Vec<SlotTimelineDataStore>,
    /// 约束动画时间轴(ik / transform 参数覆盖)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraint_timelines: Vec<ConstraintTimelineDataStore>,
    /// 网格顶点变形时间轴(deform),帧数据保持原始(offset/vertices),转换时展开
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub deform_timelines: Vec<DeformTimelineDataStore>,
    /// 绘制顺序时间轴(draw order),帧为完整 setup slot 索引排列
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub draw_order_timeline: Option<DrawOrderTimelineDataStore>,
}

/// 约束动画时间轴(约束名 + 参数帧)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ConstraintTimelineDataStore {
    /// 约束名称,引用骨架中的约束
    pub name: String,
    pub kind: ConstraintKindStore,
    pub frames: Vec<ConstraintKeyframeDataStore>,
}

/// 约束类型
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ConstraintKindStore {
    Ik,
    Transform,
}

/// 约束参数关键帧
///
/// 帧内未出现的字段表示不覆盖(保持骨架默认值),step 语义
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum ConstraintKeyframeDataStore {
    Ik {
        time: f32,
        #[serde(default)]
        mix: Option<f32>,
        #[serde(default)]
        bend_positive: Option<bool>,
        #[serde(default)]
        compress: Option<bool>,
        #[serde(default)]
        stretch: Option<bool>,
    },
    Transform {
        time: f32,
        #[serde(default)]
        mix_rotate: Option<f32>,
        #[serde(default)]
        mix_x: Option<f32>,
        #[serde(default)]
        mix_y: Option<f32>,
        #[serde(default)]
        mix_scale_x: Option<f32>,
        #[serde(default)]
        mix_scale_y: Option<f32>,
        #[serde(default)]
        mix_shear_y: Option<f32>,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TimelineDataStore {
    /// 骨骼名称,引用骨架中的骨骼
    pub bone: String,
    pub channel: BoneChannel,
    /// 关键帧按时间升序存放,转换时会自动排序以保证正确性
    pub frames: Vec<KeyframeDataStore>,
}

/// slot 动画时间轴
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SlotTimelineDataStore {
    /// slot 名称,引用骨架中的 slot
    pub slot: String,
    pub channel: SlotChannel,
    pub frames: Vec<SlotKeyframeDataStore>,
}

/// slot 关键帧
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum SlotKeyframeDataStore {
    /// 颜色帧,RGBA 0-255(spine 原样);到下一帧之间按曲线插值
    ///
    /// spine 4.1 的 rgba 颜色时间轴支持每通道独立贝塞尔(curve 16 值 = 4 组),
    /// 4.2 起单曲线(4 值)四通道共用;解析时统一归一化为 4 条曲线
    Color {
        time: f32,
        rgba: [u8; 4],
        #[serde(default)]
        curves: [CurveStore; 4],
    },
    /// attachment 帧,None 表示移除 attachment;step 语义无曲线
    Attachment { time: f32, name: Option<String> },
}

/// 网格顶点变形时间轴(原始 spine 帧数据,展开在 to_rt 时做)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeformTimelineDataStore {
    /// 皮肤名(deform 时间轴挂在 skins 下的 attachment 上)
    pub skin: String,
    /// slot 名称
    pub slot: String,
    /// attachment 名称(逻辑名,在皮肤内查找)
    pub attachment: String,
    pub frames: Vec<DeformFrameDataStore>,
}

/// deform 帧(原始数据):vertices 只包含本帧写到的顶点(从 offset 起)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeformFrameDataStore {
    pub time: f32,
    /// 起始顶点分量索引(默认 0)
    #[serde(default)]
    pub offset: usize,
    /// 顶点分量增量(每顶点 2 个分量,x/y)
    #[serde(default)]
    pub vertices: Vec<f32>,
    /// 该帧到下一帧之间的曲线
    #[serde(default)]
    pub curve: CurveStore,
}

/// 绘制顺序时间轴
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DrawOrderTimelineDataStore {
    pub frames: Vec<DrawOrderFrameDataStore>,
}

/// draw order 帧:offsets 原始数据(slot 名 + 偏移),to_rt 时展开为完整 setup 索引排列
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DrawOrderFrameDataStore {
    pub time: f32,
    /// (slot 名, 偏移),按 setup 顺序递增
    #[serde(default)]
    pub offsets: Vec<(String, isize)>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct KeyframeDataStore {
    pub time: f32,
    pub value: f32,
    /// 该帧到下一帧之间的曲线,默认为线性
    #[serde(default)]
    pub curve: CurveStore,
}

/// 存储用的曲线定义
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
#[derive(Default)]
pub enum CurveStore {
    /// 线性插值
    #[default]
    Linear,
    /// 保持前一帧的值
    Step,
    /// 贝塞尔缓动,控制点归一化到 (0,0)-(1,1)
    Bezier { x1: f32, y1: f32, x2: f32, y2: f32 },
}

/// deform 展开所需网格信息(to_rt 时按 (skin, slot, attachment) 解析)
#[derive(Debug, Clone)]
pub struct DeformMeshInfo {
    /// 该附件解析出的网格索引(deform 时间轴归属,运行时按 (slot, mesh) 匹配)
    pub mesh_idx: crate::data::runtime::mesh::MeshIdx,
    /// 顶点数(每顶点 2 个分量)
    pub vertex_count: usize,
    /// 加权网格(有骨骼影响):deform 值为按 influence 展开的 delta 偏移;非加权:绝对位置 = setup + delta
    pub weighted: bool,
    /// 网格 base 顶点(局部空间,2 分量/顶点)
    pub setup: Vec<f32>,
    /// 加权网格的 deform 数组长度(2 × Σinfluence,官方按 influence 展开);非加权网格不使用
    pub deform_len: usize,
}

impl AnimationDataStore {
    /// 转换为运行时动画数据,骨骼名称解析为索引
    ///
    /// `constraints`:骨架约束名 -> 运行时约束索引,用于解析约束时间轴
    /// `deform_resolver`:(皮肤名, slot 名, attachment 名) -> 网格信息;返回 None 时 deform 时间轴跳过
    pub fn to_rt(
        self,
        skeleton: &Skeleton,
        slots: &SlotSet,
        constraints: &std::collections::HashMap<
            String,
            crate::data::runtime::constraint::ConstraintIdx,
        >,
        att_names: &std::cell::RefCell<crate::data::runtime::skin::AttachmentNames>,
        deform_resolver: &dyn Fn(&str, &str, &str) -> Option<DeformMeshInfo>,
    ) -> Result<AnimationRT, Error> {
        let mut timelines = Vec::with_capacity(self.timelines.len());
        for tl in self.timelines {
            let bone = skeleton.get_bone_index(&tl.bone).ok_or_else(|| {
                Error::InvalidData(format!("animation references unknown bone: {}", tl.bone))
            })?;
            let mut frames = tl
                .frames
                .into_iter()
                .map(|f| Keyframe {
                    time: f.time,
                    value: f.value,
                    curve: match f.curve {
                        CurveStore::Linear => Curve::Linear,
                        CurveStore::Step => Curve::Step,
                        CurveStore::Bezier { x1, y1, x2, y2 } => {
                            Curve::Bezier(BezierCurve::new(x1, y1, x2, y2), None)
                        }
                    },
                })
                .collect::<Vec<_>>();
            frames.sort_by(|a, b| a.time.total_cmp(&b.time));
            timelines.push(Timeline {
                bone,
                channel: tl.channel,
                frames,
            });
        }
        let mut slot_timelines = Vec::with_capacity(self.slot_timelines.len());
        for tl in self.slot_timelines {
            let slot = slots.get_index(&tl.slot).ok_or_else(|| {
                Error::InvalidData(format!("animation references unknown slot: {}", tl.slot))
            })?;
            let mut frames = Vec::with_capacity(tl.frames.len());
            for f in tl.frames {
                match f {
                    SlotKeyframeDataStore::Color { time, rgba, curves } => {
                        let to_curve = |c: &CurveStore| -> Curve {
                            match c {
                                CurveStore::Linear => Curve::Linear,
                                CurveStore::Step => Curve::Step,
                                CurveStore::Bezier { x1, y1, x2, y2 } => {
                                    Curve::Bezier(BezierCurve::new(*x1, *y1, *x2, *y2), None)
                                }
                            }
                        };
                        frames.push(SlotKeyframe::Color {
                            time,
                            rgba: [
                                rgba[0] as f32 / 255.0,
                                rgba[1] as f32 / 255.0,
                                rgba[2] as f32 / 255.0,
                                rgba[3] as f32 / 255.0,
                            ],
                            curves: [
                                to_curve(&curves[0]),
                                to_curve(&curves[1]),
                                to_curve(&curves[2]),
                                to_curve(&curves[3]),
                            ],
                        });
                    }
                    SlotKeyframeDataStore::Attachment { time, name } => {
                        frames.push(SlotKeyframe::Attachment {
                            time,
                            name: name.map(|n| att_names.borrow_mut().intern(slot, &n)),
                        });
                    }
                }
            }
            frames.sort_by(|a, b| a.time().total_cmp(&b.time()));
            slot_timelines.push(SlotTimeline {
                slot,
                channel: tl.channel,
                frames,
            });
        }
        // 约束时间轴:约束名解析为运行时索引
        let mut constraint_timelines = Vec::with_capacity(self.constraint_timelines.len());
        for tl in self.constraint_timelines {
            let Some(&index) = constraints.get(&tl.name) else {
                return Err(Error::InvalidData(format!(
                    "animation references unknown constraint: {}",
                    tl.name
                )));
            };
            let mut frames = Vec::with_capacity(tl.frames.len());
            for f in tl.frames {
                match f {
                    ConstraintKeyframeDataStore::Ik {
                        time,
                        mix,
                        bend_positive,
                        compress,
                        stretch,
                    } => frames.push(crate::data::runtime::animate::ConstraintKeyframe::Ik {
                        time,
                        mix,
                        bend_positive,
                        compress,
                        stretch,
                    }),
                    ConstraintKeyframeDataStore::Transform {
                        time,
                        mix_rotate,
                        mix_x,
                        mix_y,
                        mix_scale_x,
                        mix_scale_y,
                        mix_shear_y,
                    } => frames.push(
                        crate::data::runtime::animate::ConstraintKeyframe::Transform {
                            time,
                            mix_rotate,
                            mix_x,
                            mix_y,
                            mix_scale_x,
                            mix_scale_y,
                            mix_shear_y,
                        },
                    ),
                }
            }
            frames.sort_by(|a, b| a.time().total_cmp(&b.time()));
            constraint_timelines
                .push(crate::data::runtime::animate::ConstraintTimeline { index, frames });
        }
        // deform 时间轴:展开为完整顶点数组(官方 SkeletonJson 语义:
        // 加权 = 按 influence 展开的 delta(数组长度 2×Σinfluence,offset 为 float 下标);
        // 非加权 = setup 顶点 + 帧值 delta(绝对位置))
        let mut deform_timelines = Vec::with_capacity(self.deform_timelines.len());
        for tl in self.deform_timelines {
            let Some(info) = deform_resolver(&tl.skin, &tl.slot, &tl.attachment) else {
                continue;
            };
            let Some(slot) = slots.get_index(&tl.slot) else {
                return Err(Error::InvalidData(format!(
                    "animation references unknown slot: {}",
                    tl.slot
                )));
            };
            let mut frames = Vec::with_capacity(tl.frames.len());
            for f in tl.frames {
                let deform_len = if info.weighted {
                    info.deform_len
                } else {
                    info.setup.len()
                };
                let mut vertices = if info.weighted {
                    vec![0.0f32; info.deform_len]
                } else {
                    info.setup.clone()
                };
                let count = deform_len.saturating_sub(f.offset);
                for (i, v) in f.vertices.iter().take(count).enumerate() {
                    vertices[f.offset + i] += v;
                }
                frames.push(crate::data::runtime::animate::DeformFrame {
                    time: f.time,
                    vertices,
                    curve: match f.curve {
                        CurveStore::Linear => crate::data::runtime::animate::Curve::Linear,
                        CurveStore::Step => crate::data::runtime::animate::Curve::Step,
                        CurveStore::Bezier { x1, y1, x2, y2 } => {
                            crate::data::runtime::animate::Curve::Bezier(
                                crate::data::runtime::animate::BezierCurve::new(x1, y1, x2, y2),
                                None,
                            )
                        }
                    },
                });
            }
            frames.sort_by(|a, b| a.time.total_cmp(&b.time));
            deform_timelines.push(crate::data::runtime::animate::DeformTimeline {
                slot,
                mesh: info.mesh_idx,
                frames,
            });
        }
        // draw order 时间轴:offsets 展开为完整 setup slot 索引排列(官方 DrawOrderTimeline 语义)
        let draw_order_timeline = if let Some(tl) = self.draw_order_timeline {
            let slot_count = slots.data.len();
            let mut frames = Vec::with_capacity(tl.frames.len());
            for f in tl.frames {
                let order = if f.offsets.is_empty() {
                    None
                } else {
                    let mut order = vec![-1i32; slot_count];
                    let mut unchanged: Vec<i32> =
                        Vec::with_capacity(slot_count.saturating_sub(f.offsets.len()));
                    let mut original = 0usize;
                    for (name, offset) in &f.offsets {
                        let Some(idx) = slots.get_index(name) else {
                            return Err(Error::InvalidData(format!(
                                "animation references unknown slot: {name}"
                            )));
                        };
                        let idx = crate::custom_index::AsIndex::as_index(&idx);
                        while original < idx {
                            unchanged.push(original as i32);
                            original += 1;
                        }
                        let target = (original as isize + offset) as i32;
                        if target >= 0 && (target as usize) < slot_count {
                            order[target as usize] = original as i32;
                        }
                        original += 1;
                    }
                    while original < slot_count {
                        unchanged.push(original as i32);
                        original += 1;
                    }
                    for i in (0..slot_count).rev() {
                        if order[i] == -1
                            && let Some(v) = unchanged.pop()
                        {
                            order[i] = v;
                        }
                    }
                    Some(order)
                };
                frames.push(crate::data::runtime::animate::DrawOrderFrame {
                    time: f.time,
                    order,
                });
            }
            frames.sort_by(|a, b| a.time.total_cmp(&b.time));
            Some(crate::data::runtime::animate::DrawOrderTimeline { frames })
        } else {
            None
        };
        // 动画总时长 = 所有时间轴覆盖的最大时间
        let duration = timelines
            .iter()
            .flat_map(|t| t.frames.iter().map(|f| f.time))
            .chain(
                slot_timelines
                    .iter()
                    .flat_map(|t| t.frames.iter().map(|f| f.time())),
            )
            .chain(
                constraint_timelines
                    .iter()
                    .flat_map(|t| t.frames.iter().map(|f| f.time())),
            )
            .chain(
                deform_timelines
                    .iter()
                    .flat_map(|t| t.frames.iter().map(|f| f.time)),
            )
            .chain(
                draw_order_timeline
                    .iter()
                    .flat_map(|t| t.frames.iter().map(|f| f.time)),
            )
            .fold(0.0f32, f32::max);
        Ok(AnimationRT {
            name: self.name,
            duration,
            timelines,
            slot_timelines,
            constraint_timelines,
            deform_timelines,
            draw_order_timeline,
        })
    }
}

/// 从 spine 动画 JSON 解析为一个动画数据(骨骼变换 + slot 时间轴)
///
/// spine 的骨骼 transform 帧值是相对 setup pose 的偏移(delta,translate/shear 为加数、
/// scale 为乘数),这里原样存储 delta;采样后在应用阶段与 Pose 的 setup 值合成
/// ([`crate::data::runtime::animate::SampledAnimate::apply_pose`])。
/// 支持骨骼变换时间轴(rotate/translate/translateX/translateY/scale/shear)、
/// slot 时间轴(color / attachment)、约束时间轴(ik / transform)与 deform;
/// events 时间轴会被忽略。
pub fn parse_spine_animation(
    name: &str,
    anim: &serde_json::Value,
) -> Result<AnimationDataStore, Error> {
    use std::collections::HashMap;

    let mut timelines: Vec<TimelineDataStore> = Vec::new();
    // 动画中出现过的骨骼(v4.x 有一种替换模式的值列表写法,保守兼容 object/array)
    let mut used_bones: HashMap<String, ()> = HashMap::new();
    let mut slot_timelines: Vec<SlotTimelineDataStore> = Vec::new();

    let bones_map = anim.get("bones").and_then(|v| v.as_object());
    if let Some(bones_map) = bones_map {
        for (bone_name, tl_map) in bones_map {
            used_bones.insert(bone_name.clone(), ());
            let tl_map = tl_map.as_object().ok_or_else(|| {
                Error::InvalidData(format!(
                    "spine animation '{name}': bone '{bone_name}' timelines must be an object"
                ))
            })?;
            for (tl_key, frames_val) in tl_map {
                let frames = frames_val.as_array().ok_or_else(|| {
                    Error::InvalidData(format!(
                        "spine animation '{name}': bone '{bone_name}' timeline '{tl_key}' must be an array"
                    ))
                })?;
                parse_bone_timeline(name, bone_name, tl_key, frames, &mut timelines)?;
            }
        }
    }
    let _ = used_bones;

    let slots_map = anim.get("slots").and_then(|v| v.as_object());
    if let Some(slots_map) = slots_map {
        for (slot_name, tl_map) in slots_map {
            let tl_map = tl_map.as_object().ok_or_else(|| {
                Error::InvalidData(format!(
                    "spine animation '{name}': slot '{slot_name}' timelines must be an object"
                ))
            })?;
            for (tl_key, frames_val) in tl_map {
                let frames = frames_val.as_array().ok_or_else(|| {
                    Error::InvalidData(format!(
                        "spine animation '{name}': slot '{slot_name}' timeline '{tl_key}' must be an array"
                    ))
                })?;
                match tl_key.as_str() {
                    // spine 4.1 时间轴键 "rgba";4.2+ 为 "color"
                    "color" | "rgba" => {
                        parse_slot_color(name, slot_name, frames, &mut slot_timelines)?;
                    }
                    "attachment" => {
                        parse_slot_attachment(name, slot_name, frames, &mut slot_timelines)?;
                    }
                    // 其余 slot 时间轴(deform 等)忽略
                    _ => {}
                }
            }
        }
    }

    // 约束时间轴:ik / transform 参数覆盖(帧内缺省字段 = 不覆盖)
    let mut constraint_timelines: Vec<ConstraintTimelineDataStore> = Vec::new();
    if let Some(ik_map) = anim.get("ik").and_then(|v| v.as_object()) {
        for (constraint_name, frames_val) in ik_map {
            let frames = frames_val.as_array().ok_or_else(|| {
                Error::InvalidData(format!(
                    "spine animation '{name}': ik constraint '{constraint_name}' timelines must be an array"
                ))
            })?;
            let mut fs = Vec::with_capacity(frames.len());
            for f in frames {
                // 官方 4.2 SkeletonJson:帧内缺省字段按绝对默认值设置(mix=1, bendPositive=true, compress/stretch=false)
                fs.push(ConstraintKeyframeDataStore::Ik {
                    time: frame_time(f)?,
                    mix: Some(
                        f.get("mix")
                            .and_then(|v| v.as_f64())
                            .map(|v| v as f32)
                            .unwrap_or(1.0),
                    ),
                    bend_positive: Some(
                        f.get("bendPositive")
                            .and_then(|v| v.as_bool())
                            .unwrap_or(true),
                    ),
                    compress: Some(f.get("compress").and_then(|v| v.as_bool()).unwrap_or(false)),
                    stretch: Some(f.get("stretch").and_then(|v| v.as_bool()).unwrap_or(false)),
                });
            }
            if !fs.is_empty() {
                constraint_timelines.push(ConstraintTimelineDataStore {
                    name: constraint_name.to_string(),
                    kind: ConstraintKindStore::Ik,
                    frames: fs,
                });
            }
        }
    }
    if let Some(transform_map) = anim.get("transform").and_then(|v| v.as_object()) {
        for (constraint_name, frames_val) in transform_map {
            let frames = frames_val.as_array().ok_or_else(|| {
                Error::InvalidData(format!(
                    "spine animation '{name}': transform constraint '{constraint_name}' timelines must be an array"
                ))
            })?;
            let mut fs = Vec::with_capacity(frames.len());
            for f in frames {
                // 官方 4.2 SkeletonJson:帧内缺省字段按绝对默认值设置(mix 类全部 = 1)
                fs.push(ConstraintKeyframeDataStore::Transform {
                    time: frame_time(f)?,
                    mix_rotate: Some(
                        f.get("mixRotate")
                            .and_then(|v| v.as_f64())
                            .map(|v| v as f32)
                            .unwrap_or(1.0),
                    ),
                    mix_x: Some(
                        f.get("mixX")
                            .and_then(|v| v.as_f64())
                            .map(|v| v as f32)
                            .unwrap_or(1.0),
                    ),
                    mix_y: Some(
                        f.get("mixY")
                            .and_then(|v| v.as_f64())
                            .map(|v| v as f32)
                            .unwrap_or(1.0),
                    ),
                    mix_scale_x: Some(
                        f.get("mixScaleX")
                            .and_then(|v| v.as_f64())
                            .map(|v| v as f32)
                            .unwrap_or(1.0),
                    ),
                    mix_scale_y: Some(
                        f.get("mixScaleY")
                            .and_then(|v| v.as_f64())
                            .map(|v| v as f32)
                            .unwrap_or(1.0),
                    ),
                    mix_shear_y: Some(
                        f.get("mixShearY")
                            .and_then(|v| v.as_f64())
                            .map(|v| v as f32)
                            .unwrap_or(1.0),
                    ),
                });
            }
            if !fs.is_empty() {
                constraint_timelines.push(ConstraintTimelineDataStore {
                    name: constraint_name.to_string(),
                    kind: ConstraintKindStore::Transform,
                    frames: fs,
                });
            }
        }
    }

    // deform 时间轴:挂在 anim.attachments.<皮肤>.<slot>.<attachment>.deform 下(spine 4.x 格式)
    let mut deform_timelines: Vec<DeformTimelineDataStore> = Vec::new();
    if let Some(skins_map) = anim.get("attachments").and_then(|v| v.as_object()) {
        for (skin_name, skin_map) in skins_map {
            let Some(slots_map) = skin_map.as_object() else {
                continue;
            };
            for (slot_name, slot_map) in slots_map {
                let Some(attachments_map) = slot_map.as_object() else {
                    continue;
                };
                for (attachment_name, att_map) in attachments_map {
                    let Some(att_map) = att_map.as_object() else {
                        continue;
                    };
                    let Some(deform_val) = att_map.get("deform") else {
                        continue;
                    };
                    let frames = deform_val.as_array().ok_or_else(|| {
                        Error::InvalidData(format!(
                            "spine animation '{name}': slot '{slot_name}' attachment '{attachment_name}' deform timelines must be an array"
                        ))
                    })?;
                    let mut fs = Vec::with_capacity(frames.len());
                    for f in frames {
                        fs.push(DeformFrameDataStore {
                            time: frame_time(f)?,
                            offset: f.get("offset").and_then(|v| v.as_u64()).unwrap_or(0) as usize,
                            vertices: f
                                .get("vertices")
                                .and_then(|v| v.as_array())
                                .map(|arr| {
                                    arr.iter()
                                        .filter_map(|v| v.as_f64())
                                        .map(|v| v as f32)
                                        .collect()
                                })
                                .unwrap_or_default(),
                            curve: parse_curve(f.get("curve"))?,
                        });
                    }
                    if !fs.is_empty() {
                        deform_timelines.push(DeformTimelineDataStore {
                            skin: skin_name.clone(),
                            slot: slot_name.clone(),
                            attachment: attachment_name.clone(),
                            frames: fs,
                        });
                    }
                }
            }
        }
    }

    // draw order 时间轴:anim.drawOrder,帧 { time, offsets: [{slot, offset}] },step 语义
    let mut draw_order_timeline = None;
    if let Some(frames_val) = anim.get("drawOrder").and_then(|v| v.as_array()) {
        let mut frames = Vec::with_capacity(frames_val.len());
        for f in frames_val {
            let mut offsets = Vec::new();
            if let Some(offsets_val) = f.get("offsets").and_then(|v| v.as_array()) {
                for o in offsets_val {
                    let slot_name = o.get("slot").and_then(|v| v.as_str()).ok_or_else(|| {
                        Error::InvalidData(format!(
                            "spine animation '{name}': drawOrder offset missing slot name"
                        ))
                    })?;
                    offsets.push((
                        slot_name.to_string(),
                        o.get("offset").and_then(|v| v.as_i64()).unwrap_or(0) as isize,
                    ));
                }
            }
            frames.push(DrawOrderFrameDataStore {
                time: frame_time(f)?,
                offsets,
            });
        }
        draw_order_timeline = Some(DrawOrderTimelineDataStore { frames });
    }

    Ok(AnimationDataStore {
        name: name.to_string(),
        timelines,
        slot_timelines,
        constraint_timelines,
        deform_timelines,
        draw_order_timeline,
    })
}

/// 解析 slot 颜色时间轴:帧格式 { time, color: "rrggbbaa"(可带#), curve }
///
/// 时间轴键兼容 spine 4.1 的 "rgba" 与 4.2+ 的 "color"(帧内字段都是 color)
fn parse_slot_color(
    anim_name: &str,
    slot_name: &str,
    frames: &[serde_json::Value],
    out: &mut Vec<SlotTimelineDataStore>,
) -> Result<(), Error> {
    let mut fs = Vec::with_capacity(frames.len());
    for f in frames {
        let time = frame_time(f)?;
        let color = f.get("color").and_then(|v| v.as_str()).ok_or_else(|| {
            Error::InvalidData(format!(
                "spine animation '{anim_name}': slot '{slot_name}' color frame missing color string"
            ))
        })?;
        let rgba = parse_color_hex(color).map_err(|e| {
            Error::InvalidData(format!(
                "spine animation '{anim_name}': slot '{slot_name}' {e}"
            ))
        })?;
        let curves = parse_color_curves(f.get("curve")).map_err(|e| {
            Error::InvalidData(format!(
                "spine animation '{anim_name}': slot '{slot_name}' {e}"
            ))
        })?;
        fs.push(SlotKeyframeDataStore::Color { time, rgba, curves });
    }
    if !fs.is_empty() {
        out.push(SlotTimelineDataStore {
            slot: slot_name.to_string(),
            channel: SlotChannel::Color,
            frames: fs,
        });
    }
    Ok(())
}

/// 解析颜色帧曲线:None -> 全 Linear;"stepped" -> 全 Step;
/// 4 值数组 -> 四通道共用同一贝塞尔(spine 4.2);16 值数组 -> 每通道独立贝塞尔(spine 4.1)
fn parse_color_curves(v: Option<&serde_json::Value>) -> Result<[CurveStore; 4], String> {
    let v = match v {
        Some(v) => v,
        None => return Ok([CurveStore::Linear; 4]),
    };
    if let Some(s) = v.as_str() {
        return match s {
            "stepped" => Ok([CurveStore::Step; 4]),
            "linear" => Ok([CurveStore::Linear; 4]),
            other => Err(format!("unknown curve type '{other}'")),
        };
    }
    let arr = v
        .as_array()
        .ok_or_else(|| "curve must be a string or array".to_string())?;
    let vals: Vec<f32> = arr
        .iter()
        .map(|x| x.as_f64().unwrap_or(0.0) as f32)
        .collect();
    let mk = |i: usize| CurveStore::Bezier {
        x1: vals[i * 4],
        y1: vals[i * 4 + 1],
        x2: vals[i * 4 + 2],
        y2: vals[i * 4 + 3],
    };
    match vals.len() {
        4 => {
            let b = mk(0);
            Ok([b, b, b, b])
        }
        16 => Ok([mk(0), mk(1), mk(2), mk(3)]),
        n => Err(format!("color curve must have 4 or 16 values, got {n}")),
    }
}

/// 解析 slot attachment 时间轴:帧格式 { time, name: string|null }
fn parse_slot_attachment(
    anim_name: &str,
    slot_name: &str,
    frames: &[serde_json::Value],
    out: &mut Vec<SlotTimelineDataStore>,
) -> Result<(), Error> {
    let mut fs = Vec::with_capacity(frames.len());
    for f in frames {
        let time = frame_time(f)?;
        let name = match f.get("name") {
            Some(v) if v.is_null() => None,
            Some(v) => Some(v.as_str().ok_or_else(|| {
                Error::InvalidData(format!(
                    "spine animation '{anim_name}': slot '{slot_name}' attachment name must be a string"
                ))
            })?.to_string()),
            None => None,
        };
        fs.push(SlotKeyframeDataStore::Attachment { time, name });
    }
    if !fs.is_empty() {
        out.push(SlotTimelineDataStore {
            slot: slot_name.to_string(),
            channel: SlotChannel::Attachment,
            frames: fs,
        });
    }
    Ok(())
}

/// 解析 "rrggbbaa" 颜色字符串(可带 # 前缀),返回 RGBA 0-255
fn parse_color_hex(s: &str) -> Result<[u8; 4], String> {
    let s = s.trim_start_matches('#');
    if s.len() != 8 {
        return Err(format!("color must be 8 hex digits, got '{s}'"));
    }
    let mut out = [0u8; 4];
    for (i, byte) in out.iter_mut().enumerate() {
        *byte = u8::from_str_radix(&s[i * 2..i * 2 + 2], 16)
            .map_err(|_| format!("invalid hex color '{s}'"))?;
    }
    Ok(out)
}

fn parse_bone_timeline(
    anim_name: &str,
    bone_name: &str,
    tl_key: &str,
    frames: &[serde_json::Value],
    out: &mut Vec<TimelineDataStore>,
) -> Result<(), Error> {
    match tl_key {
        "rotate" => {
            let mut fs = Vec::with_capacity(frames.len());
            for f in frames {
                let time = frame_time(f)?;
                let value = frame_value(f)?;
                let curve = parse_curve(f.get("curve"))?;
                fs.push(KeyframeDataStore {
                    time,
                    value,
                    curve,
                });
            }
            if !fs.is_empty() {
                out.push(TimelineDataStore {
                    bone: bone_name.to_string(),
                    channel: BoneChannel::Rotate,
                    frames: fs,
                });
            }
        }
        "translate" => {
            parse_dual_axis(
                anim_name,
                bone_name,
                frames,
                out,
                "x",
                "y",
                BoneChannel::TranslateX,
                BoneChannel::TranslateY,
                false,
            )?;
        }
        "translatex" | "translateX" => {
            parse_single_axis(anim_name, bone_name, frames, false, BoneChannel::TranslateX, out)?;
        }
        "translatey" | "translateY" => {
            parse_single_axis(anim_name, bone_name, frames, false, BoneChannel::TranslateY, out)?;
        }
        "scale" => {
            parse_dual_axis(
                anim_name,
                bone_name,
                frames,
                out,
                "x",
                "y",
                BoneChannel::ScaleX,
                BoneChannel::ScaleY,
                true,
            )?;
        }
        "scalex" | "scaleX" => {
            parse_single_axis(anim_name, bone_name, frames, true, BoneChannel::ScaleX, out)?;
        }
        "scaley" | "scaleY" => {
            parse_single_axis(anim_name, bone_name, frames, true, BoneChannel::ScaleY, out)?;
        }
        "shear" => {
            parse_dual_axis(
                anim_name,
                bone_name,
                frames,
                out,
                "x",
                "y",
                BoneChannel::ShearX,
                BoneChannel::ShearY,
                false,
            )?;
        }
        "shearx" | "shearX" => {
            parse_single_axis(anim_name, bone_name, frames, false, BoneChannel::ShearX, out)?;
        }
        "sheary" | "shearY" => {
            parse_single_axis(anim_name, bone_name, frames, false, BoneChannel::ShearY, out)?;
        }
        // 其余时间轴(deform/attachment 等不在 bones 下)忽略
        _ => {}
    }
    Ok(())
}

/// 双轴时间轴(translate/scale/shear):按 x/y 字段拆成两条单通道时间轴
///
/// spine 语义:帧中省略的轴视为相对 setup 的默认值(translate/shear 的 delta 为 0,scale 的 delta 为 1),
/// 必须为每个轴生成完整帧序列;仅当某轴全程都是默认值(从未变化)时才跳过该轴
#[allow(clippy::too_many_arguments)]
fn parse_dual_axis(
    anim_name: &str,
    bone_name: &str,
    frames: &[serde_json::Value],
    out: &mut Vec<TimelineDataStore>,
    x_key: &str,
    y_key: &str,
    x_channel: BoneChannel,
    y_channel: BoneChannel,
    multiplicative: bool,
) -> Result<(), Error> {
    let default = if multiplicative { 1.0 } else { 0.0 };
    let mut x_frames = Vec::new();
    let mut y_frames = Vec::new();
    let mut x_changed = false;
    let mut y_changed = false;
    for f in frames {
        let time = frame_time(f)?;
        let (xc, yc) = parse_dual_curve(f.get("curve"))?;
        let x = f
            .get(x_key)
            .and_then(|v| v.as_f64())
            .map(|v| v as f32)
            .unwrap_or(default);
        let y = f
            .get(y_key)
            .and_then(|v| v.as_f64())
            .map(|v| v as f32)
            .unwrap_or(default);
        if x != default {
            x_changed = true;
        }
        if y != default {
            y_changed = true;
        }
        x_frames.push(KeyframeDataStore {
            time,
            value: x,
            curve: xc,
        });
        y_frames.push(KeyframeDataStore {
            time,
            value: y,
            curve: yc,
        });
    }
    if x_changed && !x_frames.is_empty() {
        out.push(TimelineDataStore {
            bone: bone_name.to_string(),
            channel: x_channel,
            frames: x_frames,
        });
    }
    if y_changed && !y_frames.is_empty() {
        out.push(TimelineDataStore {
            bone: bone_name.to_string(),
            channel: y_channel,
            frames: y_frames,
        });
    }
    let _ = anim_name;
    Ok(())
}

/// 单轴时间轴(translatex/translatey/scalex/shearx...),帧值在 "value" 字段
fn parse_single_axis(
    anim_name: &str,
    bone_name: &str,
    frames: &[serde_json::Value],
    _multiplicative: bool,
    channel: BoneChannel,
    out: &mut Vec<TimelineDataStore>,
) -> Result<(), Error> {
    let mut fs = Vec::with_capacity(frames.len());
    for f in frames {
        let time = frame_time(f)?;
        let value = frame_value(f)?;
        let curve = parse_curve(f.get("curve"))?;
        fs.push(KeyframeDataStore {
            time,
            value,
            curve,
        });
    }
    if !fs.is_empty() {
        out.push(TimelineDataStore {
            bone: bone_name.to_string(),
            channel,
            frames: fs,
        });
    }
    let _ = anim_name;
    Ok(())
}

fn frame_time(frame: &serde_json::Value) -> Result<f32, Error> {
    Ok(frame.get("time").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32)
}

/// 帧值:rotate 用 "value"/"angle",单轴时间轴用 "value"
fn frame_value(frame: &serde_json::Value) -> Result<f32, Error> {
    if let Some(v) = frame.get("value").and_then(|v| v.as_f64()) {
        return Ok(v as f32);
    }
    if let Some(v) = frame.get("angle").and_then(|v| v.as_f64()) {
        return Ok(v as f32);
    }
    // 省略视为 0(保持 setup)
    Ok(0.0)
}

/// 解析单个曲线:缺省=Linear,"stepped"=Step,[4]=Bezier,[8] 取前 4 个(单轴防御)
fn parse_curve(curve: Option<&serde_json::Value>) -> Result<CurveStore, Error> {
    let Some(curve) = curve else {
        return Ok(CurveStore::Linear);
    };
    if let Some(s) = curve.as_str() {
        if s == "stepped" {
            return Ok(CurveStore::Step);
        }
        return Err(Error::InvalidData(format!("unknown curve string: {s}")));
    }
    if let Some(arr) = curve.as_array() {
        return curve_from_arr(&arr[..arr.len().min(4)]);
    }
    Err(Error::InvalidData("invalid curve value".to_string()))
}

/// 解析双轴曲线:缺省=双 Linear,"stepped"=双 Step,[4]=双轴同曲线,[8]=x/y 各一条
fn parse_dual_curve(curve: Option<&serde_json::Value>) -> Result<(CurveStore, CurveStore), Error> {
    let Some(curve) = curve else {
        return Ok((CurveStore::Linear, CurveStore::Linear));
    };
    if let Some(s) = curve.as_str() {
        if s == "stepped" {
            return Ok((CurveStore::Step, CurveStore::Step));
        }
        return Err(Error::InvalidData(format!("unknown curve string: {s}")));
    }
    if let Some(arr) = curve.as_array() {
        if arr.len() >= 8 {
            let xc = curve_from_arr(&arr[0..4])?;
            let yc = curve_from_arr(&arr[4..8])?;
            return Ok((xc, yc));
        }
        let c = curve_from_arr(arr)?;
        return Ok((c, c));
    }
    Err(Error::InvalidData("invalid curve value".to_string()))
}

fn curve_from_arr(arr: &[serde_json::Value]) -> Result<CurveStore, Error> {
    if arr.len() != 4 {
        return Err(Error::InvalidData(format!(
            "curve must have 4 elements, got {}",
            arr.len()
        )));
    }
    let mut n = [0.0f32; 4];
    for (i, v) in arr.iter().enumerate() {
        n[i] = v
            .as_f64()
            .ok_or_else(|| Error::InvalidData("curve element must be a number".to_string()))?
            as f32;
    }
    Ok(CurveStore::Bezier {
        x1: n[0],
        y1: n[1],
        x2: n[2],
        y2: n[3],
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        data::runtime::{
            animate::{AnimateConfig, DEFAULT_CURVE_SAMPLING},
            skeleton::BoneDataStatic,
            slot::{SlotData, SlotSet},
        },
        utils::default,
    };

    /// 无约束骨架下的约束名映射(空)
    fn empty_constraint_map()
    -> std::collections::HashMap<String, crate::data::runtime::constraint::ConstraintIdx> {
        std::collections::HashMap::new()
    }

    fn build_skeleton() -> Skeleton {
        let mut skeleton = Skeleton::new();
        skeleton.insert_bone("root", default()).unwrap();
        skeleton
            .insert_bone("arm", BoneDataStatic::default())
            .unwrap();
        skeleton
    }

    fn build_slots() -> SlotSet {
        let mut slots = SlotSet::new();
        for name in ["a", "b", "c", "face", "hair"] {
            slots.insert(
                name,
                SlotData {
                    name: name.to_string(),
                    bone: unsafe { crate::custom_index::AsIndex::from_index(0) },
                    default_attachment: None,
                    default_attachment_idx: None,
                    color: [1.0, 1.0, 1.0, 1.0],
                },
            );
        }
        slots
    }

    fn att_names(
        slots: &SlotSet,
    ) -> std::cell::RefCell<crate::data::runtime::skin::AttachmentNames> {
        std::cell::RefCell::new(crate::data::runtime::skin::AttachmentNames::new(
            slots.data.len(),
        ))
    }

    #[test]
    fn serde_roundtrip_and_sample() {
        let json = r#"{
            "name": "wave",
            "timelines": [
                {
                    "bone": "arm",
                    "channel": "Rotate",
                    "frames": [
                        { "time": 0.0, "value": 0.0 },
                        { "time": 1.0, "value": 90.0, "curve": { "type": "bezier", "x1": 0.25, "y1": 0.1, "x2": 0.75, "y2": 0.9 } }
                    ]
                }
            ]
        }"#;
        let store: AnimationDataStore = serde_json::from_str(json).unwrap();
        let skeleton = build_skeleton();
        let mut anim = store
            .to_rt(
                &skeleton,
                &build_slots(),
                &empty_constraint_map(),
                &att_names(&build_slots()),
                &|_, _, _| None,
            )
            .unwrap();
        anim.prebuild_curves(DEFAULT_CURVE_SAMPLING);
        assert_eq!(anim.name, "wave");
        assert_eq!(anim.duration, 1.0);
        // 最后一帧(无下一帧)曲线未被预采样
        assert!(matches!(
            anim.timelines[0].frames[1].curve,
            Curve::Bezier(_, None)
        ));
    }

    #[test]
    fn unknown_bone_error() {
        let json = r#"{
            "name": "bad",
            "timelines": [
                { "bone": "nope", "channel": "TranslateX", "frames": [ { "time": 0.0, "value": 0.0 } ] }
            ]
        }"#;
        let store: AnimationDataStore = serde_json::from_str(json).unwrap();
        let err = store
            .to_rt(
                &build_skeleton(),
                &build_slots(),
                &empty_constraint_map(),
                &att_names(&build_slots()),
                &|_, _, _| None,
            )
            .unwrap_err();
        assert!(matches!(err, Error::InvalidData(_)));
    }

    #[test]
    fn frames_auto_sorted_and_duration_derived() {
        let json = r#"{
            "name": "sort",
            "timelines": [
                { "bone": "arm", "channel": "TranslateX",
                  "frames": [
                    { "time": 1.0, "value": 10.0 },
                    { "time": 0.0, "value": 0.0 },
                    { "time": 2.0, "value": 20.0 }
                  ] }
            ]
        }"#;
        let store: AnimationDataStore = serde_json::from_str(json).unwrap();
        let anim = store
            .to_rt(
                &build_skeleton(),
                &build_slots(),
                &empty_constraint_map(),
                &att_names(&build_slots()),
                &|_, _, _| None,
            )
            .unwrap();
        assert_eq!(anim.duration, 2.0);
        let times: Vec<f32> = anim.timelines[0].frames.iter().map(|f| f.time).collect();
        assert_eq!(times, vec![0.0, 1.0, 2.0]);

        let mut set = crate::data::runtime::animate::AnimateSet::new();
        let idx = set.insert("sort", anim.clone());
        let mut config = AnimateConfig::new();
        let s = set.sample(idx, &mut config, 0.5);
        assert_eq!(s.values[0].2, 5.0);
    }

    #[test]
    fn curve_store_default_is_linear() {
        assert_eq!(CurveStore::default(), CurveStore::Linear);
        // 未知/缺失字段(含已移除的 curve_sample_points)应能正常反序列化
        let json = r#"{"name":"n","timelines":[]}"#;
        let _store: AnimationDataStore = serde_json::from_str(json).unwrap();
    }

    #[test]
    fn parse_spine_slot_timelines_full() {
        let spine = serde_json::json!({
            "slots": {
                "hair": {
                    "color": [
                        { "color": "ff0000ff", "curve": [0.25, 0, 0.75, 1] },
                        { "time": 1.0, "color": "#00ff00ff" }
                    ],
                    "attachment": [
                        {},
                        { "time": 0.5, "name": "long" },
                        { "time": 0.8, "name": null }
                    ]
                }
            }
        });
        let store = parse_spine_animation("walk", &spine).unwrap();
        assert_eq!(store.slot_timelines.len(), 2);

        let color = store
            .slot_timelines
            .iter()
            .find(|t| t.channel == SlotChannel::Color)
            .unwrap();
        assert_eq!(color.slot, "hair");
        assert_eq!(color.frames.len(), 2);
        let SlotKeyframeDataStore::Color { rgba, curves, .. } = color.frames[0] else {
            panic!("expected color frame");
        };
        assert_eq!(rgba, [0xff, 0x00, 0x00, 0xff]);
        assert_eq!(
            curves,
            [CurveStore::Bezier {
                x1: 0.25,
                y1: 0.0,
                x2: 0.75,
                y2: 1.0
            }; 4]
        );
        let SlotKeyframeDataStore::Color { rgba, .. } = color.frames[1] else {
            panic!("expected color frame");
        };
        assert_eq!(rgba, [0x00, 0xff, 0x00, 0xff]);

        let att = store
            .slot_timelines
            .iter()
            .find(|t| t.channel == SlotChannel::Attachment)
            .unwrap();
        assert_eq!(att.frames.len(), 3);
        let SlotKeyframeDataStore::Attachment { name, .. } = &att.frames[0] else {
            panic!("expected attachment frame");
        };
        assert!(name.is_none());
        let SlotKeyframeDataStore::Attachment { name, .. } = &att.frames[1] else {
            panic!("expected attachment frame");
        };
        assert_eq!(name.as_deref(), Some("long"));
        let SlotKeyframeDataStore::Attachment { name, .. } = &att.frames[2] else {
            panic!("expected attachment frame");
        };
        assert!(name.is_none());
    }

    #[test]
    fn parse_spine_slot_timeline_to_rt_and_sample() {
        let spine = serde_json::json!({
            "slots": {
                "hair": {
                    "color": [
                        { "color": "ff0000ff" },
                        { "time": 1.0, "color": "0000ffff" }
                    ],
                    "attachment": [
                        { "name": "short" },
                        { "time": 0.5, "name": "long" }
                    ]
                }
            }
        });
        let store = parse_spine_animation("walk", &spine).unwrap();
        let mut anim = store
            .to_rt(
                &build_skeleton(),
                &build_slots(),
                &empty_constraint_map(),
                &att_names(&build_slots()),
                &|_, _, _| None,
            )
            .unwrap();
        anim.prebuild_curves(DEFAULT_CURVE_SAMPLING);
        assert_eq!(anim.duration, 1.0);

        let mut set = crate::data::runtime::animate::AnimateSet::new();
        let idx = set.insert("walk", anim);
        let mut config = AnimateConfig::new();
        // 中途:颜色线性插值(红 -> 蓝),attachment 已切换为 long
        let s = set.sample(idx, &mut config, 0.5);
        let mut found_color = false;
        let mut found_att = false;
        for (_, channel, value) in &s.slot_values {
            match (channel, value) {
                (
                    SlotChannel::Color,
                    crate::data::runtime::animate::SampledSlotValue::Color(Some(c)),
                ) => {
                    found_color = true;
                    assert!((c[0] - 0.5).abs() < 1e-3, "r={}", c[0]);
                    assert!((c[2] - 0.5).abs() < 1e-3, "b={}", c[2]);
                    assert_eq!(c[1], 0.0);
                    assert_eq!(c[3], 1.0);
                }
                (
                    SlotChannel::Attachment,
                    crate::data::runtime::animate::SampledSlotValue::Attachment(
                        crate::data::runtime::animate::SampledAttachment::Set(name),
                    ),
                ) => {
                    found_att = true;
                    // "hair" slot 内逻辑名 "short"/"long" 的索引为 0/1(解析期 intern)
                    assert_eq!(
                        *name,
                        Some(unsafe {
                            crate::custom_index::AsIndex::from_index(1)
                        })
                    );
                }
                _ => panic!("unexpected slot value"),
            }
        }
        assert!(found_color && found_att);
    }

    #[test]
    fn parse_spine_slot_unknown_slot_errors() {
        let spine = serde_json::json!({
            "slots": { "nope": { "attachment": [ { "name": "x" } ] } }
        });
        let store = parse_spine_animation("walk", &spine).unwrap();
        let err = store
            .to_rt(
                &build_skeleton(),
                &build_slots(),
                &empty_constraint_map(),
                &att_names(&build_slots()),
                &|_, _, _| None,
            )
            .unwrap_err();
        assert!(matches!(err, Error::InvalidData(_)));
    }

    #[test]
    fn parse_spine_invalid_color_errors() {
        let spine = serde_json::json!({
            "slots": { "hair": { "color": [ { "color": "red" } ] } }
        });
        let err = parse_spine_animation("walk", &spine).unwrap_err();
        assert!(matches!(err, Error::InvalidData(_)));
    }

    #[test]
    fn serde_roundtrip_slot_timeline() {
        let store = AnimationDataStore {
            name: "s".to_string(),
            timelines: vec![],
            slot_timelines: vec![SlotTimelineDataStore {
                slot: "hair".to_string(),
                channel: SlotChannel::Color,
                frames: vec![SlotKeyframeDataStore::Color {
                    time: 0.0,
                    rgba: [1, 2, 3, 4],
                    curves: [CurveStore::Linear; 4],
                }],
            }],
            constraint_timelines: vec![],
            deform_timelines: vec![],
            draw_order_timeline: None,
        };
        let json = serde_json::to_string(&store).unwrap();
        let back: AnimationDataStore = serde_json::from_str(&json).unwrap();
        assert_eq!(back, store);
        assert!(json.contains("\"slot_timelines\""));
        assert!(json.contains("\"kind\":\"color\""));
    }

    #[test]
    fn parse_spine_slot_timelines() {
        let spine = serde_json::json!({
            "bones": {
                "arm": {
                    "rotate": [ { "value": 15, "curve": [0.25, 0, 0.75, 1] } ],
                    "translate": [ { "x": 5 } ],
                    "translatey": [ { "value": -2, "curve": "stepped" } ],
                    "scale": [ { "x": 1.1, "y": 0.9, "curve": [0.1, 0, 0.9, 1, 0.2, 0, 0.8, 1] } ]
                }
            }
        });
        let store = parse_spine_animation("walk", &spine).unwrap();
        assert_eq!(store.name, "walk");
        assert_eq!(store.timelines.len(), 5);

        let rot = store
            .timelines
            .iter()
            .find(|t| t.channel == BoneChannel::Rotate)
            .unwrap();
        assert_eq!(rot.frames.len(), 1);
        assert!((rot.frames[0].value - 15.0).abs() < 1e-5); // delta 15(相对 setup 30)
        assert!(matches!(rot.frames[0].curve, CurveStore::Bezier { .. }));

        let tx = store
            .timelines
            .iter()
            .find(|t| t.channel == BoneChannel::TranslateX)
            .unwrap();
        assert!((tx.frames[0].value - 5.0).abs() < 1e-5); // delta 5(相对 setup 10)

        let ty = store
            .timelines
            .iter()
            .find(|t| t.channel == BoneChannel::TranslateY)
            .unwrap();
        assert!((ty.frames[0].value - -2.0).abs() < 1e-5); // delta -2
        assert_eq!(ty.frames[0].curve, CurveStore::Step);

        let sx = store
            .timelines
            .iter()
            .find(|t| t.channel == BoneChannel::ScaleX)
            .unwrap();
        assert!((sx.frames[0].value - 1.1).abs() < 1e-5); // delta ×1.1
        let sy = store
            .timelines
            .iter()
            .find(|t| t.channel == BoneChannel::ScaleY)
            .unwrap();
        assert!((sy.frames[0].value - 0.9).abs() < 1e-5);
    }

    #[test]
    fn parse_spine_missing_x_axis_in_translate_skips_timeline() {
        let spine = serde_json::json!({
            "bones": { "arm": { "translate": [ { "y": -8 } ] } }
        });
        let store = parse_spine_animation("t", &spine).unwrap();
        // x 全程默认值被跳过,只生成 TranslateY;帧值 = delta
        assert_eq!(store.timelines.len(), 1);
        assert_eq!(store.timelines[0].channel, BoneChannel::TranslateY);
        assert!((store.timelines[0].frames[0].value - -8.0).abs() < 1e-5);
    }

    #[test]
    fn parse_spine_partial_axis_frames_fill_defaults() {
        // 中间帧才有值,首尾省略(spine 的"部分轴"写法):
        // y 轴必须生成完整 3 帧序列,省略帧 = setup 值(delta 0)
        let spine = serde_json::json!({
            "bones": { "arm": { "translate": [
                { "curve": [0.25, 0.0, 0.375, 2.0] },
                { "time": 0.5, "y": 2.0 },
                { "time": 1.0 }
            ] } }
        });
        let store = parse_spine_animation("t", &spine).unwrap();
        assert_eq!(store.timelines.len(), 1);
        let ty = &store.timelines[0];
        assert_eq!(ty.channel, BoneChannel::TranslateY);
        assert_eq!(ty.frames.len(), 3);
        assert!((ty.frames[0].value - 0.0).abs() < 1e-5); // 省略帧 delta 0
        assert!((ty.frames[1].value - 2.0).abs() < 1e-5); // delta 2
        assert!((ty.frames[2].value - 0.0).abs() < 1e-5); // 省略帧 delta 0
        // 中间时刻采样应在 0 和 2 之间(插值),而不是恒定 2
        let skeleton = {
            use crate::data::runtime::skeleton::BoneDataStatic;
            let mut s = crate::data::runtime::skeleton::Skeleton::new();
            s.insert_bone("arm", BoneDataStatic::default()).unwrap();
            s
        };
        let mut anim = store
            .to_rt(
                &skeleton,
                &build_slots(),
                &empty_constraint_map(),
                &att_names(&build_slots()),
                &|_, _, _| None,
            )
            .unwrap();
        anim.prebuild_curves(DEFAULT_CURVE_SAMPLING);
        let mut set = crate::data::runtime::animate::AnimateSet::new();
        let idx = set.insert("t", anim);
        let mut config = AnimateConfig::new();
        let s = set.sample(idx, &mut config, 0.25);
        assert!(
            s.values[0].2 > 0.5 && s.values[0].2 < 1.5,
            "t=0.25 y={}",
            s.values[0].2
        );
    }

    #[test]
    #[ignore = "requires assets/1.json (spine export) and assets/1_bones.json, not in repo"]
    fn parse_real_spine_file_and_sample() {
        use crate::data::store::skeleton::BoneDataStore;

        let file = std::fs::read_to_string("assets/1.json").unwrap();
        let root: serde_json::Value = serde_json::from_str(&file).unwrap();
        let bones_file = std::fs::read_to_string("assets/1_bones.json").unwrap();
        let bones: Vec<BoneDataStore> = serde_json::from_str(&bones_file).unwrap();
        let skeleton = Skeleton::from_bone_data_list(&bones).unwrap();

        // 真实 slots:动画会引用骨架中的任意槽(Elbow_L 等),测试辅助 build_slots 只有精简集
        let mut slots = crate::data::runtime::slot::SlotSet::new();
        if let Some(slot_arr) = root["slots"].as_array() {
            for s in slot_arr {
                let store: crate::data::store::slot::SlotDataStore =
                    serde_json::from_value(s.clone()).unwrap();
                let rt = store.to_rt(&skeleton).unwrap();
                slots.insert(rt.name.clone(), rt);
            }
        }

        // 真实约束映射:动画约束时间轴按名称引用骨架约束
        let constraint_store: crate::data::store::constraint::ConstraintDataStore =
            serde_json::from_value({
                let mut v = serde_json::json!({});
                if let Some(ik) = root.get("ik") {
                    v["ik"] = ik.clone();
                }
                if let Some(transform) = root.get("transform") {
                    v["transform"] = transform.clone();
                }
                v
            })
            .unwrap();
        let mut constraint_map = std::collections::HashMap::new();
        for (i, c) in constraint_store.ik.iter().enumerate() {
            constraint_map.insert(
                c.name.clone(),
                crate::data::runtime::constraint::ConstraintIdx::Ik(i as u32),
            );
        }
        for (i, c) in constraint_store.transform.iter().enumerate() {
            constraint_map.insert(
                c.name.clone(),
                crate::data::runtime::constraint::ConstraintIdx::Transform(i as u32),
            );
        }

        let anims = root["animations"].as_object().unwrap();
        let mut total = 0usize;
        for (name, anim) in anims {
            let store = parse_spine_animation(name, anim).unwrap();
            let mut anim_rt = store
                .to_rt(
                    &skeleton,
                    &slots,
                    &constraint_map,
                    &att_names(&slots),
                    &|_, _, _| None,
                )
                .unwrap();
            anim_rt.prebuild_curves(DEFAULT_CURVE_SAMPLING);
            let duration = anim_rt.duration;
            let mut set = crate::data::runtime::animate::AnimateSet::new();
            let idx = set.insert(anim_rt.name.clone(), anim_rt);
            let mut config = AnimateConfig::new();
            // 采样几个时间点,不 panic 即通过
            for t in [0.0f32, duration * 0.5, duration] {
                let _ = set.sample(idx, &mut config, t);
            }
            total += 1;
        }
        assert!(total > 0, "no animations found in spine file");
        eprintln!("parsed and sampled {total} animations from real spine file");
    }

    /// deform 解析 + 展开(加权:delta 补 0;非加权:setup + delta)+ 采样插值
    #[test]
    fn parse_deform_and_sample() {
        let spine = serde_json::json!({
            "attachments": {
                "default": {
                    "face": {
                        "mesh1": {
                            "deform": [
                                { "time": 0.0, "vertices": [10.0, 20.0, 30.0, 40.0] },
                                { "time": 1.0, "vertices": [0.0, 0.0, 0.0, 0.0] }
                            ]
                        }
                    }
                }
            }
        });
        let store = parse_spine_animation("deform_test", &spine).unwrap();
        assert_eq!(store.deform_timelines.len(), 1);
        let tl = &store.deform_timelines[0];
        assert_eq!(tl.skin, "default");
        assert_eq!(tl.slot, "face");
        assert_eq!(tl.attachment, "mesh1");
        assert_eq!(tl.frames[0].vertices, vec![10.0, 20.0, 30.0, 40.0]);
        // 展开:加权(按 influence 展开的 delta),4 顶点网格
        let info = DeformMeshInfo {
            mesh_idx: unsafe { crate::custom_index::AsIndex::from_index(0) },
            vertex_count: 4,
            weighted: true,
            setup: vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0],
            deform_len: 8,
        };
        let skeleton = build_skeleton();
        let slots = build_slots();
        let anim = store
            .to_rt(
                &skeleton,
                &slots,
                &empty_constraint_map(),
                &att_names(&slots),
                &|_, _, _| {
                    Some(info.clone())
                },
            )
            .unwrap();
        assert_eq!(anim.deform_timelines.len(), 1);
        assert_eq!(anim.deform_timelines[0].frames[0].vertices.len(), 8);
        assert_eq!(
            &anim.deform_timelines[0].frames[0].vertices,
            &[10.0, 20.0, 30.0, 40.0, 0.0, 0.0, 0.0, 0.0]
        );
        // 采样:t=0.5 线性插值 = 帧0 与帧1 中点
        let mut set = crate::data::runtime::animate::AnimateSet::new();
        let idx = set.insert(anim.name.clone(), anim);
        let mut config = AnimateConfig::new();
        let sampled = set.sample(idx, &mut config, 0.5);
        assert_eq!(sampled.deform_values.len(), 1);
        let (_, _, v) = &sampled.deform_values[0];
        assert_eq!(v, &[5.0, 10.0, 15.0, 20.0, 0.0, 0.0, 0.0, 0.0]);
        // t 无命中帧:不输出
        let sampled = set.sample(idx, &mut config, -1.0);
        assert!(sampled.deform_values.is_empty());
    }

    /// 非加权 deform:展开 = setup + delta(绝对位置)
    #[test]
    fn parse_deform_unweighted_expands_setup() {
        let spine = serde_json::json!({
            "attachments": {
                "default": {
                    "face": {
                        "mesh1": {
                            "deform": [
                                { "time": 0.0, "vertices": [10.0, 20.0] }
                            ]
                        }
                    }
                }
            }
        });
        let store = parse_spine_animation("t", &spine).unwrap();
        let info = DeformMeshInfo {
            mesh_idx: unsafe { crate::custom_index::AsIndex::from_index(0) },
            vertex_count: 2,
            weighted: false,
            setup: vec![100.0, 200.0, 300.0, 400.0],
            deform_len: 4,
        };
        let skeleton = build_skeleton();
        let slots = build_slots();
        let anim = store
            .to_rt(
                &skeleton,
                &slots,
                &empty_constraint_map(),
                &att_names(&slots),
                &|_, _, _| {
                    Some(info.clone())
                },
            )
            .unwrap();
        assert_eq!(
            &anim.deform_timelines[0].frames[0].vertices,
            &[110.0, 220.0, 300.0, 400.0]
        );
    }
    /// draw order:offsets 展开为完整 setup 索引排列 + step 采样
    #[test]
    fn parse_draw_order_and_sample() {
        let spine = serde_json::json!({
            "drawOrder": [
                { "time": 0.0, "offsets": [ { "slot": "a", "offset": 1 }, { "slot": "c", "offset": 0 } ] },
                { "time": 1.0 }
            ]
        });
        let store = parse_spine_animation("t", &spine).unwrap();
        let skeleton = build_skeleton();
        let slots = build_slots();
        let anim = store
            .to_rt(
                &skeleton,
                &slots,
                &empty_constraint_map(),
                &att_names(&slots),
                &|_, _, _| None,
            )
            .unwrap();
        let tl = anim.draw_order_timeline.clone().unwrap();
        assert_eq!(tl.frames.len(), 2);
        // slots: a(0) b(1) c(2) face(3) hair(4)
        // offsets(setup 递增):a->位置 1,c->位置 2
        // 官方算法:unchanged=[b],order = [b, a, c, face, hair]
        let order = tl.frames[0].order.clone().unwrap();
        eprintln!("draw order frame0 = {order:?}");
        assert_eq!(order, vec![1, 0, 2, 3, 4]);
        // 帧 2(t=1.0 无 offsets):setup 顺序(None)
        assert!(tl.frames[1].order.is_none());
        // step 采样:t=0.5 命中第一帧
        let mut set = crate::data::runtime::animate::AnimateSet::new();
        let idx = set.insert(anim.name.clone(), anim);
        let mut config = AnimateConfig::new();
        let sampled = set.sample(idx, &mut config, 0.5);
        assert_eq!(sampled.draw_order.as_deref(), Some(&[1, 0, 2, 3, 4][..]));
        let sampled = set.sample(idx, &mut config, 1.5);
        assert!(sampled.draw_order.is_none());
    }
}