unity-formats 0.2.1

Reads Unity games' data files: SerializedFiles, scenes, meshes, textures, shader programs and Animator data
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
//! A scene's hierarchy: GameObjects, their Transforms (local TRS composed to world matrices in Unity's frame), and
//! its mesh renderers (skinned ones with their bones), LODGroups, colliders, lights and terrains, each whatever its
//! state.
//!
//! State is data: each object carries its [`OffFlag`]s, the GameObjects on its Transform chain stored inactive and the
//! component itself stored disabled; Unity draws or uses it when it has none. A LODGroup lists its levels' renderers
//! ([`LodGroup`]); which level draws is Unity's choice by screen size. A static-batched renderer draws a slice of a
//! combined mesh whose vertices are already in world space (its matrix is the identity). A RectTransform's local x
//! and y come from its anchors (the stored position can be stale): the parent rect's minimum plus its size times the
//! anchors interpolated at the pivot, plus the anchored position.

use std::collections::BTreeMap;

use serde::Serialize;

use crate::bump;
use crate::player::{ObjRef, Player};
use crate::value::{Array, Value};
use crate::{Result, invalid};

/// A MonoBehaviour as stored: its script (namespace and class) and the script's serialized fields, kept as bytes
/// (a stripped build has no type tree for them).
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct UnityBehaviour {
    /// The MonoBehaviour object.
    pub behaviour: ObjRef,
    /// The script's class, `namespace.class`; empty when the script cannot be resolved.
    pub script: String,
    /// `m_Enabled`.
    pub enabled: bool,
    /// The script's serialized fields, as bytes.
    #[serde(skip)]
    pub data: Vec<u8>,
}

/// A scene's ambient lighting as RenderSettings stores it: `mode` (`m_AmbientMode`: 0 skybox, 1 trilight, a gradient
/// of the sky, equator and ground colours, 3 flat, the sky colour alone, 4 custom), the three colours as stored,
/// `intensity` (`m_AmbientIntensity`) and the ambient probe as stored (`m_AmbientProbe`, Unity's SphericalHarmonicsL2:
/// nine coefficients per channel, red 0..8, green 9..17, blue 18..26; `None` when the RenderSettings store none). The
/// probe is what the editor last generated: all zeros when it never did, and not necessarily from the colours stored
/// beside it.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct UnityAmbient {
    /// `m_AmbientMode`.
    pub mode: i64,
    /// `m_AmbientSkyColor`, RGBA.
    pub sky: [f32; 4],
    /// `m_AmbientEquatorColor`, RGBA.
    pub equator: [f32; 4],
    /// `m_AmbientGroundColor`, RGBA.
    pub ground: [f32; 4],
    /// `m_AmbientIntensity`.
    pub intensity: f32,
    /// `m_AmbientProbe`: 27 coefficients, red then green then blue; `None` when none is stored.
    pub probe: Option<[f32; 27]>,
}

/// The scene's fog as RenderSettings stores it: whether it is on (`m_Fog`), its `mode` (`m_FogMode`: 1 linear, 2
/// exponential, 3 exponential squared), its colour, `density` (exponential modes) and the linear mode's `start` and
/// `end`.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct UnityFog {
    /// `m_Fog`.
    pub enabled: bool,
    /// `m_FogMode`.
    pub mode: i64,
    /// `m_FogColor`, RGBA.
    pub color: [f32; 4],
    /// `m_FogDensity`.
    pub density: f32,
    /// `m_LinearFogStart`.
    pub start: f32,
    /// `m_LinearFogEnd`.
    pub end: f32,
}

/// A 4x4 matrix, rows of columns (`m[row][col]`), column vectors: Unity's `Matrix4x4` layout, in f64.
pub type Matrix = [[f64; 4]; 4];

/// The identity matrix.
pub const IDENTITY: Matrix = [
    [1.0, 0.0, 0.0, 0.0],
    [0.0, 1.0, 0.0, 0.0],
    [0.0, 0.0, 1.0, 0.0],
    [0.0, 0.0, 0.0, 1.0],
];

/// The product `a * b`.
pub fn mul(a: &Matrix, b: &Matrix) -> Matrix {
    let mut m = [[0.0; 4]; 4];
    for (row, a_row) in m.iter_mut().zip(a) {
        for (j, x) in row.iter_mut().enumerate() {
            *x = a_row
                .iter()
                .zip(b)
                .map(|(&av, b_row)| av * b_row.get(j).copied().unwrap_or(0.0))
                .sum();
        }
    }
    m
}

/// Unity's `Matrix4x4.TRS`: translation, rotation (the quaternion as stored), scale.
pub fn trs(p: [f64; 3], q: [f64; 4], s: [f64; 3]) -> Matrix {
    let [x, y, z, w] = q;
    let r = [
        [
            1.0 - 2.0 * (y * y + z * z),
            2.0 * (x * y - z * w),
            2.0 * (x * z + y * w),
        ],
        [
            2.0 * (x * y + z * w),
            1.0 - 2.0 * (x * x + z * z),
            2.0 * (y * z - x * w),
        ],
        [
            2.0 * (x * z - y * w),
            2.0 * (y * z + x * w),
            1.0 - 2.0 * (x * x + y * y),
        ],
    ];
    let mut m = IDENTITY;
    // the rotation's three rows scaled by column; the fourth row stays (0, 0, 0, 1)
    for ((row, r_row), &position) in m.iter_mut().zip(&r).zip(&p) {
        for ((x, &rv), &sv) in row.iter_mut().zip(r_row).zip(&s) {
            *x = rv * sv;
        }
        if let Some(last) = row.get_mut(3) {
            *last = position;
        }
    }
    m
}

fn num(v: &Value, k: &str) -> Result<f64> {
    v.get(k)
        .and_then(Value::as_f32)
        .map(f64::from)
        .ok_or_else(|| invalid(format!("no float {k}")))
}

fn vec3(v: &Value, k: &str) -> Result<[f64; 3]> {
    let x = v.get(k).ok_or_else(|| invalid(format!("no {k}")))?;
    Ok([num(x, "x")?, num(x, "y")?, num(x, "z")?])
}

fn vec2(v: &Value, k: &str) -> Result<[f64; 2]> {
    let x = v.get(k).ok_or_else(|| invalid(format!("no {k}")))?;
    Ok([num(x, "x")?, num(x, "y")?])
}

/// A flag stored as a bool or as an integer (`m_IsActive` and `m_Enabled` are `UInt8` in some layouts).
fn flag_value(v: &Value) -> bool {
    match v {
        Value::Bool(b) => *b,
        x => x.as_i64().is_some_and(|i| i != 0),
    }
}

fn flag(v: &Value, k: &str) -> Result<bool> {
    match v.get(k) {
        Some(Value::Bool(b)) => Ok(*b),
        Some(x) => x
            .as_i64()
            .map(|i| i != 0)
            .ok_or_else(|| invalid(format!("{k} is not a flag"))),
        None => Err(invalid(format!("no {k}"))),
    }
}

fn path_id(v: &Value, k: &str) -> Result<i64> {
    v.at(&[k, "m_PathID"])
        .and_then(Value::as_i64)
        .ok_or_else(|| invalid(format!("no {k}.m_PathID")))
}

fn values<'a>(v: &'a Value, k: &str) -> Result<&'a [Value]> {
    match v.get(k) {
        Some(Value::Array(Array::Values(items))) => Ok(items),
        Some(Value::Array(a)) if a.is_empty() => Ok(&[]),
        _ => Err(invalid(format!("no list {k}"))),
    }
}

/// A GameObject as stored.
#[derive(Clone, Debug)]
pub struct GameObject {
    /// `m_Name`.
    pub name: String,
    /// `m_IsActive`.
    pub active: bool,
    /// `m_Layer`.
    pub layer: u32,
    /// Its components' path ids, in order.
    pub components: Vec<i64>,
}

/// A stored "off" between an object and being drawn or used: a GameObject on its Transform chain stored inactive
/// (`m_IsActive`), or the component itself stored disabled (`m_Enabled`); path ids in the scene's file.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum OffFlag {
    /// The GameObject (path id) is stored inactive.
    Inactive(i64),
    /// The component (path id) is stored disabled.
    Disabled(i64),
}

#[derive(Clone, Debug)]
struct Node {
    game_object: i64,
    father: i64,
    local: Matrix,
    /// The stored local position, rotation (a quaternion `[x, y, z, w]`) and scale (a RectTransform's `local`
    /// position comes from its anchors instead).
    trs: ([f64; 3], [f64; 4], [f64; 3]),
}

/// A Transform as a joint of a skeleton: its GameObject's name, its father (a Transform's path id) and its local
/// position, rotation (`[x, y, z, w]`) and scale as stored, in Unity's frame.
#[derive(Clone, Debug, PartialEq)]
pub struct SceneJoint {
    /// The GameObject's name.
    pub name: String,
    /// The parent Transform's path id; `None` for a root.
    pub father: Option<i64>,
    /// Local position.
    pub translation: [f64; 3],
    /// Local rotation, a quaternion `[x, y, z, w]`.
    pub rotation: [f64; 4],
    /// Local scale.
    pub scale: [f64; 3],
}

/// An Animator component: the GameObject it animates (its Transform is the root of the paths its clips name), the
/// controller that lists its clips and its avatar; a null pointer is `None`.
#[derive(Clone, Debug, PartialEq)]
pub struct Animator {
    /// The Animator object.
    pub animator: ObjRef,
    /// The path id of the GameObject it animates.
    pub game_object: i64,
    /// That GameObject's path from the scene root, names joined by `/`.
    pub path: String,
    /// `m_Controller`.
    pub controller: Option<ObjRef>,
    /// `m_Avatar`.
    pub avatar: Option<ObjRef>,
    /// `m_Enabled` (true when the Animator does not store one).
    pub enabled: bool,
    /// `m_ApplyRootMotion`.
    pub apply_root_motion: bool,
}

/// A character: an Animator with skinned renderers on its GameObject or below it.
#[derive(Clone, Debug, PartialEq)]
pub struct Character {
    /// The Animator.
    pub animator: Animator,
    /// The SkinnedMeshRenderers on the Animator's GameObject and its descendants.
    pub skinned_renderers: usize,
}

/// A skinned renderer's bones: the Transforms (path ids in the renderer's file) its mesh's bone slots name, in slot
/// order, and its root bone; a null entry stays `None`.
#[derive(Clone, Debug, PartialEq)]
pub struct RendererSkin {
    /// `m_Bones`: the bone Transforms (path ids) in slot order.
    pub bones: Vec<Option<i64>>,
    /// `m_RootBone`.
    pub root_bone: Option<i64>,
    /// `m_BlendShapeWeights`: the weight of each of the mesh's blend shape channels (0 to 100 for a full shape).
    pub blend_weights: Vec<f32>,
}

/// A mesh renderer with a mesh, whatever its state.
#[derive(Clone, Debug, PartialEq)]
pub struct Renderer {
    /// The renderer object.
    pub renderer: ObjRef,
    /// Its GameObject, in the scene file.
    pub game_object: i64,
    /// The GameObject path, names from the root joined by `/`.
    pub path: String,
    /// Its GameObject's layer.
    pub layer: u32,
    /// The mesh (a SkinnedMeshRenderer's own, else its MeshFilter's).
    pub mesh: ObjRef,
    /// `m_Materials`, one entry per submesh slot; `None` for a null pointer.
    pub materials: Vec<Option<ObjRef>>,
    /// World matrix in Unity's frame (the identity for a static-batched renderer).
    pub world: Matrix,
    /// A static-batched renderer's slice of its combined mesh: first submesh, count.
    pub submeshes: Option<(u32, u32)>,
    /// `m_CastShadows`: 0 off, 1 on, 2 two-sided, 3 shadows only (1 when absent, Unity's default).
    pub cast_shadows: i64,
    /// `m_ReceiveShadows`, when stored.
    pub receive_shadows: Option<bool>,
    /// What keeps it from being drawn; drawn when empty.
    pub off: Vec<OffFlag>,
    /// A SkinnedMeshRenderer's bones; `None` for a MeshRenderer.
    pub skin: Option<RendererSkin>,
}

/// A LODGroup: its levels' renderers (path ids in the scene's file, a level's in stored order, null entries left out),
/// finest first; whether the component is enabled (a disabled LODGroup switches no level off) and its own off flags.
#[derive(Clone, Debug, PartialEq)]
pub struct LodGroup {
    /// The LODGroup object.
    pub group: ObjRef,
    /// Its GameObject's path from the scene root, names joined by `/`.
    pub path: String,
    /// `m_Enabled`.
    pub enabled: bool,
    /// What keeps the group from switching levels.
    pub off: Vec<OffFlag>,
    /// Per level, the path ids of its renderers.
    pub levels: Vec<Vec<i64>>,
}

/// The deepest chain of parents a scene may have. A Unity hierarchy is a few dozen deep.
const MAX_DEPTH: usize = 1024;

/// What the scene reading skipped, by reason.
pub type Skipped = std::collections::BTreeMap<&'static str, u64>;

/// A scene file's hierarchy: its GameObjects and Transforms, and from them the paths and world matrices of what the
/// scene holds.
#[derive(Debug)]
pub struct Scene {
    /// The scene's file (`level1`).
    pub file: String,
    /// The scene's GameObjects by path id.
    pub game_objects: BTreeMap<i64, GameObject>,
    nodes: BTreeMap<i64, Node>,
    /// GameObject -> its Transform.
    transform_of: BTreeMap<i64, i64>,
    world: std::sync::Mutex<BTreeMap<i64, Matrix>>,
}

/// The chains of parents are at most [`MAX_DEPTH`] long (a loop is a chain that does not end): a path, a world matrix
/// and the off flags are walked up the chain for each node, so a chain of d transforms costs d^2 of them and d paths
/// of d names.
/// A GameObject's `m_Layer`: 0 when it states none; a stored value outside 32 bits unsigned is refused.
fn layer_of(g: &Value) -> Result<u32> {
    let layer = g.get("m_Layer").and_then(Value::as_i64).unwrap_or(0);
    u32::try_from(layer).map_err(|_| invalid(format!("m_Layer {layer} is not a 32-bit unsigned number")))
}

/// A component's `m_CullingMask.m_Bits`: every layer when it states none. The 32 bits may be stored unsigned or as a
/// signed `int` (-1 is every layer); a number that fits neither is refused, not wrapped.
fn culling_mask(c: &Value, path_id: i64) -> Result<u32> {
    match c.at(&["m_CullingMask", "m_Bits"]).and_then(Value::as_i64) {
        None => Ok(u32::MAX),
        Some(bits) => u32::try_from(bits)
            .or_else(|_| i32::try_from(bits).map(|signed| u32::from_ne_bytes(signed.to_ne_bytes())))
            .map_err(|_| {
                invalid(format!(
                    "object {path_id}: m_CullingMask {bits} does not fit 32 bits"
                ))
            }),
    }
}

fn check_depth(nodes: &BTreeMap<i64, Node>) -> Result<()> {
    let mut depths: BTreeMap<i64, usize> = BTreeMap::new();
    for &start in nodes.keys() {
        let mut chain = Vec::new();
        let mut t = start;
        let base = loop {
            if let Some(&d) = depths.get(&t) {
                break d;
            }
            let Some(n) = nodes.get(&t) else { break 0 };
            chain.push(t);
            if chain.len() > MAX_DEPTH {
                return Err(invalid(format!(
                    "transform {start}: its parents are deeper than {MAX_DEPTH} (or loop)"
                )));
            }
            if n.father == 0 {
                break 0;
            }
            t = n.father;
        };
        if base.saturating_add(chain.len()) > MAX_DEPTH {
            return Err(invalid(format!(
                "transform {start}: its parents are deeper than {MAX_DEPTH}"
            )));
        }
        for (k, &t) in chain.iter().rev().enumerate() {
            depths.insert(t, base.saturating_add(k).saturating_add(1));
        }
    }
    Ok(())
}

impl Scene {
    /// The hierarchy of the scene file `file` (`level1`).
    pub fn read(player: &Player, file: &str) -> Result<Scene> {
        let f = player.file(file)?;
        let r = |file: &str, pid: i64| ObjRef {
            file: file.to_owned(),
            path_id: pid,
        };
        let name_of =
            |o: &crate::serialized::ObjectInfo| player.class_name(&r(file, o.path_id)).unwrap_or("");
        let mut nodes = BTreeMap::new();
        let mut rects: BTreeMap<i64, Value> = BTreeMap::new();
        let mut game_objects = BTreeMap::new();
        for o in &f.objects {
            match name_of(o) {
                "Transform" | "RectTransform" => {
                    let t = player.decode(&r(file, o.path_id))?;
                    let p = vec3(&t, "m_LocalPosition")?;
                    let q = t
                        .get("m_LocalRotation")
                        .ok_or_else(|| invalid("no m_LocalRotation"))?;
                    let q = [num(q, "x")?, num(q, "y")?, num(q, "z")?, num(q, "w")?];
                    let s = vec3(&t, "m_LocalScale")?;
                    nodes.insert(
                        o.path_id,
                        Node {
                            game_object: path_id(&t, "m_GameObject")?,
                            father: path_id(&t, "m_Father")?,
                            local: trs(p, q, s),
                            trs: (p, q, s),
                        },
                    );
                    if name_of(o) == "RectTransform" {
                        rects.insert(o.path_id, t);
                    }
                }
                "GameObject" => {
                    let g = player.decode(&r(file, o.path_id))?;
                    let components = values(&g, "m_Component")?
                        .iter()
                        .map(|c| path_id(c, "component"))
                        .collect::<Result<Vec<_>>>()?;
                    game_objects.insert(
                        o.path_id,
                        GameObject {
                            name: g.get("m_Name").and_then(Value::as_str).unwrap_or("").to_owned(),
                            active: flag(&g, "m_IsActive")?,
                            layer: layer_of(&g)?,
                            components,
                        },
                    );
                }
                _ => {}
            }
        }
        check_depth(&nodes)?;
        // RectTransforms: local x, y from the anchors
        let mut sizes: BTreeMap<i64, ([f64; 2], [f64; 2])> = BTreeMap::new();
        fn rect_size(
            tp: i64,
            rects: &BTreeMap<i64, Value>,
            nodes: &BTreeMap<i64, Node>,
            sizes: &mut BTreeMap<i64, ([f64; 2], [f64; 2])>,
            depth: u32,
        ) -> Result<([f64; 2], [f64; 2])> {
            if let Some(s) = sizes.get(&tp) {
                return Ok(*s);
            }
            let Some(t) = rects.get(&tp) else {
                return Ok(([0.0; 2], [0.0; 2]));
            };
            if depth > 4096 {
                return Err(invalid("RectTransform parents loop"));
            }
            let (sd, amin, amax, piv) = (
                vec2(t, "m_SizeDelta")?,
                vec2(t, "m_AnchorMin")?,
                vec2(t, "m_AnchorMax")?,
                vec2(t, "m_Pivot")?,
            );
            let fa = nodes.get(&tp).map_or(0, |n| n.father);
            let (ps, _) = if fa != 0 {
                rect_size(fa, rects, nodes, sizes, depth.saturating_add(1))?
            } else {
                ([0.0; 2], [0.0; 2])
            };
            let s = (
                [
                    ps[0] * (amax[0] - amin[0]) + sd[0],
                    ps[1] * (amax[1] - amin[1]) + sd[1],
                ],
                piv,
            );
            sizes.insert(tp, s);
            Ok(s)
        }
        let rect_ids: Vec<i64> = rects.keys().copied().collect();
        for tp in rect_ids {
            let missing = || invalid(format!("RectTransform {tp} is not a transform of the scene"));
            let t = rects.get(&tp).ok_or_else(missing)?;
            let fa = nodes.get(&tp).ok_or_else(missing)?.father;
            let (ps, ppiv) = if fa != 0 {
                rect_size(fa, &rects, &nodes, &mut sizes, 0)?
            } else {
                ([0.0; 2], [0.0; 2])
            };
            let (amin, amax, piv, ap) = (
                vec2(t, "m_AnchorMin")?,
                vec2(t, "m_AnchorMax")?,
                vec2(t, "m_Pivot")?,
                vec2(t, "m_AnchoredPosition")?,
            );
            let n = nodes.get_mut(&tp).ok_or_else(missing)?;
            let anchored = ppiv
                .iter()
                .zip(&ps)
                .zip(&amin)
                .zip(&amax)
                .zip(&piv)
                .zip(&ap)
                .map(|(((((&pp, &p), &lo), &hi), &pv), &a)| -pp * p + p * (lo + (hi - lo) * pv) + a);
            for (row, value) in n.local.iter_mut().zip(anchored) {
                if let Some(x) = row.get_mut(3) {
                    *x = value;
                }
            }
        }
        let transform_of = nodes.iter().map(|(&tp, n)| (n.game_object, tp)).collect();
        Ok(Scene {
            file: file.to_owned(),
            game_objects,
            nodes,
            transform_of,
            world: std::sync::Mutex::new(BTreeMap::new()),
        })
    }

    /// The MonoBehaviours of GameObject `go`, in its component order: the script (`namespace.class`, empty when it
    /// can't be resolved), `m_Enabled`, and the script's serialized fields as bytes (a stripped build has no type tree
    /// for them).
    pub fn behaviours_of(&self, player: &Player, go: i64) -> Result<Vec<UnityBehaviour>> {
        let mut out = Vec::new();
        for &c in self.game_objects.get(&go).map_or(&[][..], |g| &g.components) {
            let r = ObjRef {
                file: self.file.clone(),
                path_id: c,
            };
            if player.class_name(&r) != Some("MonoBehaviour") {
                continue;
            }
            let (base, data) = player.behaviour(&r)?;
            let script = match base.get("m_Script") {
                Some(p) => match player.resolve(&r.file, p)? {
                    Some(s) => {
                        let s = player.decode(&s)?;
                        let field = |k: &str| s.get(k).and_then(Value::as_str).unwrap_or("").to_owned();
                        let (ns, class) = (field("m_Namespace"), field("m_ClassName"));
                        if ns.is_empty() {
                            class
                        } else {
                            format!("{ns}.{class}")
                        }
                    }
                    None => String::new(),
                },
                None => String::new(),
            };
            out.push(UnityBehaviour {
                behaviour: r.clone(),
                script,
                enabled: base
                    .get("m_Enabled")
                    .and_then(Value::as_i64)
                    .is_some_and(|x| x != 0)
                    || base.get("m_Enabled").and_then(Value::as_bool) == Some(true),
                data,
            });
        }
        Ok(out)
    }

    /// Every MonoBehaviour of the scene, by GameObject (in path id order), as [`Scene::behaviours_of`] gives them.
    pub fn behaviours(&self, player: &Player) -> Result<Vec<(i64, UnityBehaviour)>> {
        let mut out = Vec::new();
        for &go in self.game_objects.keys() {
            out.extend(self.behaviours_of(player, go)?.into_iter().map(|b| (go, b)));
        }
        Ok(out)
    }

    /// The world matrices computed so far. A thread that panicked holding the lock can leave nothing half-written (an
    /// entry is inserted whole), so a poisoned lock is still a valid cache.
    fn world_cache(&self) -> std::sync::MutexGuard<'_, BTreeMap<i64, Matrix>> {
        self.world
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// The Transform of the GameObject `root` that a query is limited to; `None` for a query of the whole file. A
    /// GameObject without a Transform is an error, not an empty or an unlimited query.
    fn root_transform(&self, root: Option<i64>) -> Result<Option<i64>> {
        root.map(|go| {
            self.transform_of(go)
                .ok_or_else(|| invalid(format!("GameObject {go} has no transform")))
        })
        .transpose()
    }

    /// A Transform's world matrix (Unity frame).
    pub fn world_of(&self, tp: i64) -> Result<Matrix> {
        let mut chain = Vec::new();
        let mut t = tp;
        let base = loop {
            if let Some(m) = self.world_cache().get(&t) {
                break *m;
            }
            let Some(n) = self.nodes.get(&t) else {
                break IDENTITY;
            };
            chain.push(t);
            if chain.len() > self.nodes.len() {
                return Err(invalid(format!("transform {tp}: parents loop")));
            }
            if n.father == 0 {
                break IDENTITY;
            }
            t = n.father;
        };
        let mut m = base;
        let mut cache = self.world_cache();
        for &t in chain.iter().rev() {
            let node = self
                .nodes
                .get(&t)
                .ok_or_else(|| invalid(format!("transform {t} on the chain of {tp} is not in the scene")))?;
            m = mul(&m, &node.local);
            cache.insert(t, m);
        }
        Ok(m)
    }

    /// The off flags of a component on Transform `tp`'s GameObject: the GameObjects stored inactive from the root down,
    /// then the component (`(path id, enabled)`) when it is stored disabled.
    pub fn off_flags(&self, tp: i64, component: Option<(i64, bool)>) -> Vec<OffFlag> {
        let mut out = Vec::new();
        let mut t = tp;
        for _ in 0..=self.nodes.len() {
            let Some(n) = self.nodes.get(&t) else { break };
            if !self.game_objects.get(&n.game_object).is_some_and(|g| g.active) {
                out.push(OffFlag::Inactive(n.game_object));
            }
            if n.father == 0 {
                break;
            }
            t = n.father;
        }
        out.reverse();
        if let Some((c, false)) = component {
            out.push(OffFlag::Disabled(c));
        }
        out
    }

    /// Whether a Transform's GameObject and all its ancestors' are active.
    pub fn active(&self, tp: i64) -> bool {
        let mut t = tp;
        for _ in 0..=self.nodes.len() {
            let Some(n) = self.nodes.get(&t) else { return true };
            if !self.game_objects.get(&n.game_object).is_some_and(|g| g.active) {
                return false;
            }
            if n.father == 0 {
                return true;
            }
            t = n.father;
        }
        false
    }

    /// The GameObject path of a Transform, names from the root joined by `/`.
    pub fn path(&self, tp: i64) -> String {
        let mut parts = Vec::new();
        let mut t = tp;
        while let Some(n) = self.nodes.get(&t) {
            parts.push(
                self.game_objects
                    .get(&n.game_object)
                    .map_or("", |g| g.name.as_str()),
            );
            if n.father == 0 || parts.len() > self.nodes.len() {
                break;
            }
            t = n.father;
        }
        parts.reverse();
        parts.join("/")
    }

    /// The Transform of a GameObject (both path ids).
    pub fn transform_of(&self, game_object: i64) -> Option<i64> {
        self.transform_of.get(&game_object).copied()
    }

    /// A GameObject and the GameObjects above it on its Transform chain, itself first, the root last; a GameObject
    /// without a Transform is alone.
    pub fn ancestors(&self, game_object: i64) -> Vec<i64> {
        let mut out = vec![game_object];
        let Some(mut t) = self.transform_of(game_object) else {
            return out;
        };
        while let Some(n) = self.nodes.get(&t) {
            if n.father == 0 || out.len() > self.nodes.len() {
                break;
            }
            t = n.father;
            match self.nodes.get(&t) {
                Some(p) => out.push(p.game_object),
                None => break,
            }
        }
        out
    }

    /// Transform `tp` as a joint ([`SceneJoint`]); `None` when it is no Transform of this file. A RectTransform's
    /// position is the one its anchors give (as in its local matrix), its rotation and scale as stored.
    pub fn joint(&self, tp: i64) -> Result<Option<SceneJoint>> {
        let Some(n) = self.nodes.get(&tp) else {
            return Ok(None);
        };
        Ok(Some(SceneJoint {
            name: self
                .game_objects
                .get(&n.game_object)
                .map_or("", |g| g.name.as_str())
                .to_owned(),
            father: (n.father != 0).then_some(n.father),
            translation: [n.local[0][3], n.local[1][3], n.local[2][3]],
            rotation: n.trs.1,
            scale: n.trs.2,
        }))
    }

    /// The characters of the file: its Animators with skinned renderers below them, in the order of its object table.
    pub fn characters(&self, player: &Player) -> Result<Vec<Character>> {
        let file = self.file.as_str();
        let r = |pid: i64| ObjRef {
            file: file.to_owned(),
            path_id: pid,
        };
        let mut skinned = Vec::new();
        for o in &player.file(file)?.objects {
            if player.class_name(&r(o.path_id)) == Some("SkinnedMeshRenderer") {
                let go = path_id(&player.decode(&r(o.path_id))?, "m_GameObject")?;
                skinned.extend(self.transform_of(go));
            }
        }
        let mut out = Vec::new();
        for animator in self.animators(player)? {
            let Some(tp) = self.transform_of(animator.game_object) else {
                continue;
            };
            let count = skinned
                .iter()
                .filter(|&&s| self.relative_to(s, tp).is_some())
                .count();
            if count > 0 {
                out.push(Character {
                    animator,
                    skinned_renderers: count,
                });
            }
        }
        Ok(out)
    }

    /// The names of the GameObjects from the child of Transform `root` down to Transform `tp` joined by `/` (empty
    /// for `root` itself): a path as an Animator's clips name their targets. `None` when `root` is not `tp` or one of
    /// its ancestors.
    pub fn path_below(&self, tp: i64, root: i64) -> Option<String> {
        let mut names = Vec::new();
        let mut t = tp;
        while t != root {
            let n = self.nodes.get(&t)?;
            names.push(
                self.game_objects
                    .get(&n.game_object)
                    .map_or("", |g| g.name.as_str()),
            );
            if n.father == 0 || names.len() > self.nodes.len() {
                return None;
            }
            t = n.father;
        }
        names.reverse();
        Some(names.join("/"))
    }

    /// The Animators of the file, in the order of its object table.
    pub fn animators(&self, player: &Player) -> Result<Vec<Animator>> {
        self.animators_under(player, None)
    }

    /// The Animators on the GameObject `root` and its descendants (a prefab's), all of the file's with `None`.
    pub fn animators_under(&self, player: &Player, root: Option<i64>) -> Result<Vec<Animator>> {
        let root_tp = self.root_transform(root)?;
        let file = self.file.as_str();
        let r = |pid: i64| ObjRef {
            file: file.to_owned(),
            path_id: pid,
        };
        let mut out = Vec::new();
        for o in &player.file(file)?.objects {
            if player.class_name(&r(o.path_id)) != Some("Animator") {
                continue;
            }
            let a = player.decode(&r(o.path_id))?;
            let go = path_id(&a, "m_GameObject")?;
            let Some(tp) = self.transform_of(go) else {
                continue;
            };
            if root_tp.is_some_and(|r| self.relative_to(tp, r).is_none()) {
                continue;
            }
            let pointer = |k: &str| -> Result<Option<ObjRef>> {
                a.get(k)
                    .map(|p| player.resolve(file, p))
                    .transpose()
                    .map(Option::flatten)
            };
            out.push(Animator {
                animator: r(o.path_id),
                game_object: go,
                path: self.path(tp),
                controller: pointer("m_Controller")?,
                avatar: pointer("m_Avatar")?,
                enabled: a.get("m_Enabled").is_none_or(flag_value),
                apply_root_motion: a.get("m_ApplyRootMotion").is_some_and(flag_value),
            });
        }
        Ok(out)
    }

    /// A Transform's local matrix.
    pub fn local_of(&self, tp: i64) -> Option<Matrix> {
        self.nodes.get(&tp).map(|n| n.local)
    }

    /// The matrix of Transform `tp` relative to its ancestor `root` (the product of the locals below `root`), or
    /// `None` when `root` is not `tp` or an ancestor of it.
    pub fn relative_to(&self, tp: i64, root: i64) -> Option<Matrix> {
        let mut chain = Vec::new();
        let mut t = tp;
        while t != root {
            let n = self.nodes.get(&t)?;
            chain.push(t);
            if n.father == 0 || chain.len() > self.nodes.len() {
                return None;
            }
            t = n.father;
        }
        chain
            .iter()
            .rev()
            .try_fold(IDENTITY, |m, t| Some(mul(&m, &self.nodes.get(t)?.local)))
    }

    /// The mesh renderers, in the order of the scene's object table, and what was skipped (no transform, no
    /// MeshFilter, no mesh).
    pub fn renderers(&self, player: &Player) -> Result<(Vec<Renderer>, Skipped)> {
        self.renderers_under(player, None)
    }

    /// The LODGroups of the GameObject `root` and its descendants (a prefab's), all of the file's with `None`, in the
    /// order of the object table.
    pub fn lod_groups_under(&self, player: &Player, root: Option<i64>) -> Result<Vec<LodGroup>> {
        let root_tp = self.root_transform(root)?;
        let file = self.file.as_str();
        let f = player.file(file)?;
        let r = |pid: i64| ObjRef {
            file: file.to_owned(),
            path_id: pid,
        };
        let mut out = Vec::new();
        for o in f
            .objects
            .iter()
            .filter(|o| player.class_name(&r(o.path_id)) == Some("LODGroup"))
        {
            let g = player.decode(&r(o.path_id))?;
            let Some(tp) = self.transform_of(path_id(&g, "m_GameObject")?) else {
                continue;
            };
            if root_tp.is_some_and(|root| self.relative_to(tp, root).is_none()) {
                continue;
            }
            let enabled = flag(&g, "m_Enabled")?;
            let mut levels = Vec::new();
            for lod in values(&g, "m_LODs")? {
                let mut level = Vec::new();
                for x in values(lod, "renderers")? {
                    let pid = path_id(x, "renderer")?;
                    if pid != 0 {
                        level.push(pid);
                    }
                }
                levels.push(level);
            }
            out.push(LodGroup {
                group: r(o.path_id),
                path: self.path(tp),
                enabled,
                off: self.off_flags(tp, Some((o.path_id, enabled))),
                levels,
            });
        }
        Ok(out)
    }

    /// The mesh renderers of the GameObject `root` and its descendants (a prefab's), their matrices relative to
    /// `root`; all of the file's with `None`.
    pub fn renderers_under(&self, player: &Player, root: Option<i64>) -> Result<(Vec<Renderer>, Skipped)> {
        let root_tp = self.root_transform(root)?;
        let file = self.file.as_str();
        let f = player.file(file)?;
        let r = |pid: i64| ObjRef {
            file: file.to_owned(),
            path_id: pid,
        };
        let class = |pid: i64| player.class_name(&r(pid)).unwrap_or("");
        let mut out = Vec::new();
        let mut skipped = Skipped::new();
        for o in f
            .objects
            .iter()
            .filter(|o| matches!(class(o.path_id), "MeshRenderer" | "SkinnedMeshRenderer"))
        {
            let skinned = class(o.path_id) == "SkinnedMeshRenderer";
            let mr = player.decode(&r(o.path_id))?;
            let go = path_id(&mr, "m_GameObject")?;
            let Some(tp) = self.transform_of(go) else {
                bump(&mut skipped, "no transform");
                continue;
            };
            let relative = match root_tp {
                Some(root) => match self.relative_to(tp, root) {
                    Some(m) => Some(m),
                    None => continue,
                },
                None => None,
            };
            let off = self.off_flags(tp, Some((o.path_id, flag(&mr, "m_Enabled")?)));
            let g = self.game_objects.get(&go).ok_or_else(|| {
                invalid(format!(
                    "GameObject {go} of renderer {} is not in the scene",
                    o.path_id
                ))
            })?;
            // a skinned renderer holds its mesh itself; a mesh renderer's is on its MeshFilter
            let filter;
            let mesh_ptr = if skinned {
                mr.get("m_Mesh")
                    .ok_or_else(|| invalid("SkinnedMeshRenderer without m_Mesh"))?
            } else {
                let Some(&mf) = g.components.iter().find(|&&c| class(c) == "MeshFilter") else {
                    bump(&mut skipped, "no MeshFilter");
                    continue;
                };
                filter = player.decode(&r(mf))?;
                filter
                    .get("m_Mesh")
                    .ok_or_else(|| invalid("MeshFilter without m_Mesh"))?
            };
            let Some(mesh) = player.resolve(file, mesh_ptr)? else {
                bump(&mut skipped, "null mesh");
                continue;
            };
            let materials = values(&mr, "m_Materials")?
                .iter()
                .map(|m| player.resolve(file, m))
                .collect::<Result<Vec<_>>>()?;
            let sb = mr.get("m_StaticBatchInfo");
            let first = sb
                .and_then(|s| s.get("firstSubMesh"))
                .and_then(Value::as_i64)
                .unwrap_or(0);
            let count = sb
                .and_then(|s| s.get("subMeshCount"))
                .and_then(Value::as_i64)
                .unwrap_or(0);
            let submeshes = if count > 0 {
                let to_u32 = |n: i64, k: &str| {
                    u32::try_from(n).map_err(|_| {
                        invalid(format!("renderer {}: {k} {n} is not 32-bit unsigned", o.path_id))
                    })
                };
                Some((to_u32(first, "firstSubMesh")?, to_u32(count, "subMeshCount")?))
            } else {
                None
            };
            let skin = if skinned {
                let bone = |p: &Value| -> Result<Option<i64>> {
                    let pid = p
                        .get("m_PathID")
                        .and_then(Value::as_i64)
                        .ok_or_else(|| invalid("a bone pointer without m_PathID"))?;
                    if p.get("m_FileID").and_then(Value::as_i64).unwrap_or(0) != 0 {
                        return Err(invalid(format!(
                            "SkinnedMeshRenderer {}: a bone in another file",
                            o.path_id
                        )));
                    }
                    Ok((pid != 0).then_some(pid))
                };
                Some(RendererSkin {
                    bones: values(&mr, "m_Bones")?.iter().map(bone).collect::<Result<_>>()?,
                    root_bone: match mr.get("m_RootBone") {
                        Some(p) => bone(p)?,
                        None => None,
                    },
                    blend_weights: match mr.get("m_BlendShapeWeights") {
                        Some(Value::Array(Array::F32(w))) => w.clone(),
                        Some(Value::Array(a)) if a.is_empty() => Vec::new(),
                        None => Vec::new(),
                        _ => return Err(invalid("SkinnedMeshRenderer: m_BlendShapeWeights not floats")),
                    },
                })
            } else {
                None
            };
            out.push(Renderer {
                renderer: r(o.path_id),
                game_object: go,
                path: self.path(tp),
                layer: g.layer,
                mesh,
                materials,
                world: if submeshes.is_some() {
                    IDENTITY
                } else {
                    match relative {
                        Some(m) => m,
                        None => self.world_of(tp)?,
                    }
                },
                submeshes,
                cast_shadows: mr.get("m_CastShadows").and_then(Value::as_i64).unwrap_or(1),
                receive_shadows: mr.get("m_ReceiveShadows").and_then(Value::as_i64).map(|v| v != 0),
                off,
                skin,
            });
        }
        Ok((out, skipped))
    }

    /// The Rigidbody on Transform `tp`'s GameObject or its nearest ancestor's: `Some(kinematic)`.
    fn rigidbody(&self, player: &Player, tp: i64) -> Result<Option<bool>> {
        let r = |pid: i64| ObjRef {
            file: self.file.clone(),
            path_id: pid,
        };
        let mut t = tp;
        for _ in 0..=self.nodes.len() {
            let Some(n) = self.nodes.get(&t) else {
                return Ok(None);
            };
            if let Some(g) = self.game_objects.get(&n.game_object)
                && let Some(&rb) = g
                    .components
                    .iter()
                    .find(|&&c| player.class_name(&r(c)) == Some("Rigidbody"))
            {
                return Ok(Some(flag(&player.decode(&r(rb))?, "m_IsKinematic")?));
            }
            if n.father == 0 {
                return Ok(None);
            }
            t = n.father;
        }
        Ok(None)
    }

    /// Every Box, Sphere, Capsule and Mesh collider of the GameObject `root` and its descendants (a prefab's, matrices
    /// relative to `root`), or of the whole file with `None`, in the order of the object table: those that do not
    /// collide (inactive, disabled, triggers) included, flagged.
    pub fn colliders_under(&self, player: &Player, root: Option<i64>) -> Result<Vec<ColliderComponent>> {
        let file = self.file.as_str();
        let f = player.file(file)?;
        let r = |pid: i64| ObjRef {
            file: file.to_owned(),
            path_id: pid,
        };
        let root_tp = self.root_transform(root)?;
        let v3 = |v: &Value, k: &str| -> Result<[f64; 3]> { vec3(v, k) };
        let mut out = Vec::new();
        for o in &f.objects {
            let class = player.class_name(&r(o.path_id)).unwrap_or("");
            if !matches!(
                class,
                "BoxCollider" | "SphereCollider" | "CapsuleCollider" | "MeshCollider"
            ) {
                continue;
            }
            let c = player.decode(&r(o.path_id))?;
            let go = path_id(&c, "m_GameObject")?;
            let Some(tp) = self.transform_of(go) else { continue };
            let world = match root_tp {
                Some(root) => match self.relative_to(tp, root) {
                    Some(m) => m,
                    None => continue,
                },
                None => self.world_of(tp)?,
            };
            let fl = |k: &str| -> Result<f64> { num(&c, k) };
            let shape = match class {
                "BoxCollider" => ColliderShape::Box {
                    center: v3(&c, "m_Center")?,
                    size: v3(&c, "m_Size")?,
                },
                "SphereCollider" => ColliderShape::Sphere {
                    center: v3(&c, "m_Center")?,
                    radius: fl("m_Radius")?,
                },
                "CapsuleCollider" => ColliderShape::Capsule {
                    center: v3(&c, "m_Center")?,
                    radius: fl("m_Radius")?,
                    height: fl("m_Height")?,
                    direction: match c.get("m_Direction").and_then(Value::as_i64).unwrap_or(1) {
                        d @ 0..=2 => usize::try_from(d).unwrap_or_default(),
                        d => {
                            return Err(invalid(format!(
                                "CapsuleCollider {}: m_Direction {d} is not 0, 1 or 2",
                                o.path_id
                            )));
                        }
                    },
                },
                _ => ColliderShape::Mesh {
                    mesh: match c.get("m_Mesh") {
                        Some(p) => player.resolve(file, p)?,
                        None => None,
                    },
                    convex: flag(&c, "m_Convex")?,
                },
            };
            out.push(ColliderComponent {
                collider: r(o.path_id),
                path: self.path(tp),
                layer: self.game_objects.get(&go).map_or(0, |g| g.layer),
                world,
                shape,
                off: self.off_flags(tp, Some((o.path_id, flag(&c, "m_Enabled")?))),
                trigger: c.get("m_IsTrigger").is_some_and(flag_value),
                physic_material: match c.get("m_Material") {
                    Some(p) => player.resolve(file, p)?,
                    None => None,
                },
                rigidbody: self.rigidbody(player, tp)?,
            });
        }
        Ok(out)
    }

    /// The scene's RenderSettings: the Light it names as its sun (`m_Sun`; `None` when it names none: Unity then
    /// lights its procedural sky by the brightest directional light, a choice of the engine's, not the scene's) and
    /// its ambient lighting. `None` when the scene has no RenderSettings.
    pub fn render_settings(&self, player: &Player) -> Result<Option<SceneRenderSettings>> {
        let file = self.file.as_str();
        let f = player.file(file)?;
        let r = |pid: i64| ObjRef {
            file: file.to_owned(),
            path_id: pid,
        };
        let mut found = None;
        for o in &f.objects {
            if player.class_name(&r(o.path_id)) != Some("RenderSettings") {
                continue;
            }
            if found.is_some() {
                return Err(invalid(format!("{file}: more than one RenderSettings")));
            }
            let settings = player.decode(&r(o.path_id))?;
            let sun = match settings.get("m_Sun") {
                Some(p) => player.resolve(file, p)?,
                None => None,
            };
            let rgba = |k: &str| -> Result<[f32; 4]> {
                let c = settings
                    .get(k)
                    .ok_or_else(|| invalid(format!("{file}: RenderSettings without {k}")))?;
                Ok([num(c, "r")?, num(c, "g")?, num(c, "b")?, num(c, "a")?].map(crate::narrow))
            };
            let ambient = match settings.get("m_AmbientMode").and_then(Value::as_i64) {
                None => None,
                Some(mode) => Some(UnityAmbient {
                    mode,
                    sky: rgba("m_AmbientSkyColor")?,
                    equator: rgba("m_AmbientEquatorColor")?,
                    ground: rgba("m_AmbientGroundColor")?,
                    intensity: settings
                        .get("m_AmbientIntensity")
                        .and_then(Value::as_f32)
                        .ok_or_else(|| {
                            invalid(format!("{file}: RenderSettings without m_AmbientIntensity"))
                        })?,
                    probe: match settings.get("m_AmbientProbe") {
                        None => None,
                        Some(sh) => {
                            let mut out = [0.0f32; 27];
                            for (i, c) in out.iter_mut().enumerate() {
                                // the type tree names the coefficients `sh[ 0]` .. `sh[26]`
                                *c = sh.get(&format!("sh[{i:2}]")).and_then(Value::as_f32).ok_or_else(
                                    || {
                                        invalid(format!(
                                            "{file}: RenderSettings' m_AmbientProbe without sh[{i:2}]"
                                        ))
                                    },
                                )?;
                            }
                            Some(out)
                        }
                    },
                }),
            };
            // fog: absent from a type tree that does not state it
            let fog = match settings.get("m_Fog").and_then(Value::as_bool) {
                None => None,
                Some(enabled) => Some(UnityFog {
                    enabled,
                    mode: settings
                        .get("m_FogMode")
                        .and_then(Value::as_i64)
                        .ok_or_else(|| invalid(format!("{file}: RenderSettings without m_FogMode")))?,
                    color: rgba("m_FogColor")?,
                    density: crate::narrow(num(&settings, "m_FogDensity")?),
                    start: crate::narrow(num(&settings, "m_LinearFogStart")?),
                    end: crate::narrow(num(&settings, "m_LinearFogEnd")?),
                }),
            };
            found = Some(SceneRenderSettings { sun, ambient, fog });
        }
        Ok(found)
    }

    /// The lights, whatever their state, in the order of the scene's object table.
    pub fn lights(&self, player: &Player) -> Result<Vec<LightComponent>> {
        let file = self.file.as_str();
        let f = player.file(file)?;
        let r = |pid: i64| ObjRef {
            file: file.to_owned(),
            path_id: pid,
        };
        let class = |pid: i64| player.class_name(&r(pid)).unwrap_or("");
        let mut out = Vec::new();
        for o in f.objects.iter().filter(|o| class(o.path_id) == "Light") {
            let l = player.decode(&r(o.path_id))?;
            let Some(tp) = self.transform_of(path_id(&l, "m_GameObject")?) else {
                continue;
            };
            let off = self.off_flags(tp, Some((o.path_id, flag(&l, "m_Enabled")?)));
            let fl = |k: &str| l.get(k).and_then(Value::as_f32);
            let int = |k: &str| l.get(k).and_then(Value::as_i64);
            let c = l.get("m_Color").ok_or_else(|| invalid("light: no m_Color"))?;
            let area = l.get("m_AreaSize");
            out.push(LightComponent {
                light: r(o.path_id),
                path: self.path(tp),
                world: self.world_of(tp)?,
                kind: int("m_Type").ok_or_else(|| invalid("light: no m_Type"))?,
                color: [num(c, "r")?, num(c, "g")?, num(c, "b")?, num(c, "a")?].map(crate::narrow),
                intensity: fl("m_Intensity").unwrap_or(1.0),
                range: fl("m_Range").unwrap_or(10.0),
                spot_angle: fl("m_SpotAngle").unwrap_or(30.0),
                inner_spot_angle: fl("m_InnerSpotAngle").unwrap_or(0.0),
                shadows: l
                    .at(&["m_Shadows", "m_Type"])
                    .and_then(Value::as_i64)
                    .unwrap_or(0),
                color_temperature: if l
                    .get("m_UseColorTemperature")
                    .is_some_and(|v| v.as_bool() == Some(true) || v.as_i64() == Some(1))
                {
                    fl("m_ColorTemperature")
                } else {
                    None
                },
                bounce_intensity: fl("m_BounceIntensity").unwrap_or(1.0),
                light_unit: int("m_LightUnit"),
                lux_at_distance: fl("m_LuxAtDistance"),
                area_size: [
                    area.and_then(|a| a.get("x"))
                        .and_then(Value::as_f32)
                        .unwrap_or(1.0),
                    area.and_then(|a| a.get("y"))
                        .and_then(Value::as_f32)
                        .unwrap_or(1.0),
                ],
                render_mode: int("m_RenderMode").unwrap_or(0),
                baked: l.at(&["m_BakingOutput", "isBaked"]).is_some_and(flag_value)
                    && l.at(&["m_BakingOutput", "lightmapBakeMode", "lightmapBakeType"])
                        .and_then(Value::as_i64)
                        == Some(2),
                culling_mask: culling_mask(&l, o.path_id)?,
                cookie: match l.get("m_Cookie") {
                    Some(p) => player.resolve(file, p)?,
                    None => None,
                },
                off,
            });
        }
        Ok(out)
    }

    /// The cameras, whatever their state, in the order of the scene's object table.
    pub fn cameras(&self, player: &Player) -> Result<Vec<CameraComponent>> {
        let file = self.file.as_str();
        let f = player.file(file)?;
        let r = |pid: i64| ObjRef {
            file: file.to_owned(),
            path_id: pid,
        };
        let class = |pid: i64| player.class_name(&r(pid)).unwrap_or("");
        let mut out = Vec::new();
        for o in f.objects.iter().filter(|o| class(o.path_id) == "Camera") {
            let c = player.decode(&r(o.path_id))?;
            let Some(tp) = self.transform_of(path_id(&c, "m_GameObject")?) else {
                continue;
            };
            out.push(CameraComponent {
                camera: r(o.path_id),
                path: self.path(tp),
                world: self.world_of(tp)?,
                culling_mask: culling_mask(&c, o.path_id)?,
                target_texture: match c.get("m_TargetTexture") {
                    Some(p) => player.resolve(file, p)?,
                    None => None,
                },
                off: self.off_flags(tp, Some((o.path_id, flag(&c, "m_Enabled")?))),
            });
        }
        Ok(out)
    }

    /// The terrains, whatever their state, in the order of the scene's object table, and what was skipped (no transform,
    /// no terrain data: a Terrain that names no TerrainData draws nothing).
    pub fn terrains(&self, player: &Player) -> Result<(Vec<TerrainComponent>, Skipped)> {
        let file = self.file.as_str();
        let f = player.file(file)?;
        let r = |pid: i64| ObjRef {
            file: file.to_owned(),
            path_id: pid,
        };
        let class = |pid: i64| player.class_name(&r(pid)).unwrap_or("");
        let mut out = Vec::new();
        let mut skipped = Skipped::new();
        for o in f.objects.iter().filter(|o| class(o.path_id) == "Terrain") {
            let t = player.decode(&r(o.path_id))?;
            let go = path_id(&t, "m_GameObject")?;
            let Some(tp) = self.transform_of(go) else {
                bump(&mut skipped, "no transform");
                continue;
            };
            let off = self.off_flags(tp, Some((o.path_id, flag(&t, "m_Enabled")?)));
            let pptr = |v: &Value, k: &str| -> Result<Option<ObjRef>> {
                match v.get(k) {
                    Some(p) => player.resolve(file, p),
                    None => Ok(None),
                }
            };
            let Some(data) = pptr(&t, "m_TerrainData")? else {
                bump(&mut skipped, "no terrain data");
                continue;
            };
            let collider = match self
                .game_objects
                .get(&go)
                .ok_or_else(|| {
                    invalid(format!(
                        "GameObject {go} of terrain {} is not in the scene",
                        o.path_id
                    ))
                })?
                .components
                .iter()
                .find(|&&c| class(c) == "TerrainCollider")
            {
                Some(&c) => {
                    let tc = player.decode(&r(c))?;
                    Some(TerrainColliderComponent {
                        collider: r(c),
                        enabled: flag(&tc, "m_Enabled")?,
                        data: pptr(&tc, "m_TerrainData")?,
                        material: pptr(&tc, "m_Material")?,
                        tree_colliders: flag(&tc, "m_EnableTreeColliders")?,
                    })
                }
                None => None,
            };
            out.push(TerrainComponent {
                terrain: r(o.path_id),
                path: self.path(tp),
                world: self.world_of(tp)?,
                data,
                material: pptr(&t, "m_MaterialTemplate")?,
                draw_heightmap: flag(&t, "m_DrawHeightmap")?,
                draw_trees: flag(&t, "m_DrawTreesAndFoliage")?,
                collider,
                off,
            });
        }
        Ok((out, skipped))
    }
}

/// A collider's shape as stored, in its GameObject's space (Unity's frame).
#[derive(Clone, Debug, PartialEq)]
pub enum ColliderShape {
    /// A box collider.
    Box {
        /// `m_Center`: the box's centre in its GameObject's space.
        center: [f64; 3],
        /// `m_Size`: the full edge lengths along x, y and z (not half-extents), before the GameObject's scale.
        size: [f64; 3],
    },
    /// A sphere collider.
    Sphere {
        /// `m_Center`: the sphere's centre in its GameObject's space.
        center: [f64; 3],
        /// `m_Radius`, before the GameObject's scale.
        radius: f64,
    },
    /// A capsule collider.
    Capsule {
        /// `m_Center`: the capsule's centre in its GameObject's space.
        center: [f64; 3],
        /// `m_Radius`, before the GameObject's scale.
        radius: f64,
        /// `m_Height`, including the caps, before the GameObject's scale.
        height: f64,
        /// `m_Direction`: the axis the height runs along (0 x, 1 y, 2 z).
        direction: usize,
    },
    /// A mesh collider.
    Mesh {
        /// `m_Mesh`; `None` for a null pointer.
        mesh: Option<ObjRef>,
        /// `m_Convex`.
        convex: bool,
    },
}

/// A collider as stored: its shape, its off flags, whether it is a trigger, its physic material, and the Rigidbody on
/// it or its nearest ancestor (`Some(true)`: kinematic).
#[derive(Clone, Debug, PartialEq)]
pub struct ColliderComponent {
    /// The collider object.
    pub collider: ObjRef,
    /// Its GameObject's path from the scene root, names joined by `/`.
    pub path: String,
    /// Its GameObject's layer.
    pub layer: u32,
    /// The matrix of its GameObject: world, or relative to `root` when one was given.
    pub world: Matrix,
    /// The shape.
    pub shape: ColliderShape,
    /// What keeps it from colliding; collides when empty.
    pub off: Vec<OffFlag>,
    /// `m_IsTrigger`.
    pub trigger: bool,
    /// `m_Material`.
    pub physic_material: Option<ObjRef>,
    /// The nearest Rigidbody: `Some(kinematic)`; `None` when there is none.
    pub rigidbody: Option<bool>,
}

/// A light as stored: Unity's LightType (0 spot, 1 directional, 2 point, 3 rectangle, 4 disc), colour as stored
/// (gamma-encoded), intensity, range, spot angles in degrees (full cone), shadow type, colour temperature (Kelvin, when
/// used), bounce intensity, URP's light unit and lux-at-distance, area size, render mode and culling mask.
#[derive(Clone, Debug, PartialEq)]
pub struct LightComponent {
    /// The Light object.
    pub light: ObjRef,
    /// Its GameObject's path from the scene root, names joined by `/`.
    pub path: String,
    /// Its GameObject's world matrix.
    pub world: Matrix,
    /// `m_Type`.
    pub kind: i64,
    /// `m_Color`, RGBA.
    pub color: [f32; 4],
    /// `m_Intensity` (1 when not stored).
    pub intensity: f32,
    /// `m_Range` (10 when not stored).
    pub range: f32,
    /// `m_SpotAngle` (30 when not stored).
    pub spot_angle: f32,
    /// `m_InnerSpotAngle` (0 when not stored).
    pub inner_spot_angle: f32,
    /// `m_Shadows.m_Type` (0 when not stored).
    pub shadows: i64,
    /// `m_ColorTemperature`, when `m_UseColorTemperature` is on.
    pub color_temperature: Option<f32>,
    /// `m_BounceIntensity` (1 when not stored).
    pub bounce_intensity: f32,
    /// `m_LightUnit`, when stored.
    pub light_unit: Option<i64>,
    /// `m_LuxAtDistance`, when stored.
    pub lux_at_distance: Option<f32>,
    /// `m_AreaSize` (1 x 1 when not stored).
    pub area_size: [f32; 2],
    /// `m_RenderMode` (0 when not stored).
    pub render_mode: i64,
    /// Fully baked: `m_BakingOutput` says baked, as `Baked` (2), not mixed or realtime.
    pub baked: bool,
    /// `m_CullingMask`'s bits (all layers when not stored).
    pub culling_mask: u32,
    /// `m_Cookie`.
    pub cookie: Option<ObjRef>,
    /// What keeps it from shining; shines when empty.
    pub off: Vec<OffFlag>,
}

/// A camera as stored: its culling mask (`m_CullingMask`, the layers it draws; all when absent) and the texture it
/// renders into (`m_TargetTexture`; `None`: it draws to the screen).
#[derive(Clone, Debug, PartialEq)]
pub struct CameraComponent {
    /// The Camera object.
    pub camera: ObjRef,
    /// Its GameObject's path from the scene root, names joined by `/`.
    pub path: String,
    /// Its GameObject's world matrix.
    pub world: Matrix,
    /// `m_CullingMask.m_Bits`: bit n set draws layer n (all 32 bits when not stored).
    pub culling_mask: u32,
    /// `m_TargetTexture`; `None` when it draws to the screen.
    pub target_texture: Option<ObjRef>,
    /// What keeps it from drawing; draws when empty.
    pub off: Vec<OffFlag>,
}

/// A terrain's collider: its own TerrainData (which may differ from the drawn one), physic material, tree colliders.
#[derive(Clone, Debug, PartialEq)]
pub struct TerrainColliderComponent {
    /// The TerrainCollider object.
    pub collider: ObjRef,
    /// `m_Enabled`.
    pub enabled: bool,
    /// `m_TerrainData`.
    pub data: Option<ObjRef>,
    /// `m_Material`.
    pub material: Option<ObjRef>,
    /// `m_EnableTreeColliders`.
    pub tree_colliders: bool,
}

/// A terrain, whatever its state: its GameObject's path and world matrix (a terrain is placed by its position only),
/// its data, material, collider and off flags (drawn when empty).
#[derive(Clone, Debug, PartialEq)]
pub struct TerrainComponent {
    /// The Terrain object.
    pub terrain: ObjRef,
    /// Its GameObject's path from the scene root, names joined by `/`.
    pub path: String,
    /// Its GameObject's world matrix.
    pub world: Matrix,
    /// `m_TerrainData`, read with [`crate::terrain::TerrainData::read`].
    pub data: ObjRef,
    /// `m_MaterialTemplate`.
    pub material: Option<ObjRef>,
    /// `m_DrawHeightmap`.
    pub draw_heightmap: bool,
    /// `m_DrawTreesAndFoliage`.
    pub draw_trees: bool,
    /// The terrain's TerrainCollider, if its GameObject has one.
    pub collider: Option<TerrainColliderComponent>,
    /// What keeps it from being drawn; drawn when empty.
    pub off: Vec<OffFlag>,
}

/// A scene's RenderSettings as read ([`Scene::render_settings`]).
#[derive(Clone, Debug, PartialEq)]
pub struct SceneRenderSettings {
    /// `m_Sun`: the Light the scene names as its sun.
    pub sun: Option<ObjRef>,
    /// The ambient lighting; `None` when the RenderSettings state no `m_AmbientMode`.
    pub ambient: Option<UnityAmbient>,
    /// The fog; `None` when the RenderSettings state no `m_Fog`.
    pub fog: Option<UnityFog>,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn chain(len: i64) -> BTreeMap<i64, Node> {
        (1..=len)
            .map(|id| {
                let node = Node {
                    game_object: id,
                    father: if id == 1 { 0 } else { id - 1 },
                    local: IDENTITY,
                    trs: ([0.0; 3], [0.0, 0.0, 0.0, 1.0], [1.0; 3]),
                };
                (id, node)
            })
            .collect()
    }

    /// A chain of parents is as deep as it is long, and a loop or a chain past the limit is refused at the read, not
    /// walked by every node's path.
    #[test]
    fn deep_and_looping_parents_are_refused() {
        assert!(check_depth(&chain(MAX_DEPTH as i64)).is_ok());
        let e = check_depth(&chain(MAX_DEPTH as i64 + 1)).unwrap_err().to_string();
        assert!(e.contains("deeper than 1024"), "{e}");
        let mut looped = chain(3);
        looped.get_mut(&1).unwrap().father = 3;
        assert!(check_depth(&looped).is_err());
        // a father the scene does not hold ends the chain
        let mut orphan = chain(3);
        orphan.get_mut(&1).unwrap().father = 99;
        assert!(check_depth(&orphan).is_ok());
    }

    fn scene_of(nodes: BTreeMap<i64, Node>) -> Scene {
        Scene {
            file: "level0".into(),
            game_objects: BTreeMap::new(),
            transform_of: nodes.iter().map(|(&tp, n)| (n.game_object, tp)).collect(),
            nodes,
            world: std::sync::Mutex::new(BTreeMap::new()),
        }
    }

    /// A query limited to a GameObject without a Transform is an error for every query that takes a root, the LODGroup
    /// query among them, not an unlimited one.
    #[test]
    fn a_root_without_a_transform_is_refused() {
        let scene = scene_of(chain(2));
        assert_eq!(scene.root_transform(None).unwrap(), None);
        assert_eq!(scene.root_transform(Some(2)).unwrap(), Some(2));
        let e = scene.root_transform(Some(77)).unwrap_err().to_string();
        assert!(e.contains("GameObject 77 has no transform"), "{e}");
    }

    /// A panic while the world cache was locked leaves a usable cache, not a panic in every later call.
    #[test]
    fn a_poisoned_world_cache_is_still_read() {
        let scene = std::sync::Arc::new(scene_of(chain(3)));
        let held = scene.clone();
        let _ = std::thread::spawn(move || {
            let _guard = held.world.lock().unwrap();
            panic!("poison the cache");
        })
        .join();
        assert!(scene.world.is_poisoned());
        assert_eq!(scene.world_of(3).unwrap(), IDENTITY);
    }

    fn with(k: &str, v: Value) -> Value {
        Value::Struct(vec![(k.into(), v)])
    }

    /// Layers and culling masks outside 32 bits are refused, not wrapped to another layer set.
    #[test]
    fn layers_and_masks_are_not_cast() {
        assert_eq!(layer_of(&with("m_Layer", Value::Int(5))).unwrap(), 5);
        assert_eq!(layer_of(&Value::Struct(vec![])).unwrap(), 0);
        for bad in [-1, 1 << 32] {
            assert!(layer_of(&with("m_Layer", Value::Int(bad))).is_err());
        }
        let mask = |bits| culling_mask(&with("m_CullingMask", with("m_Bits", Value::Int(bits))), 9);
        assert_eq!(mask(0xffff_fff0).unwrap(), 0xffff_fff0);
        assert_eq!(mask(-1).unwrap(), u32::MAX);
        assert_eq!(culling_mask(&Value::Struct(vec![]), 9).unwrap(), u32::MAX);
        let e = mask(1 << 32).unwrap_err().to_string();
        assert!(e.contains("object 9") && e.contains("4294967296"), "{e}");
        assert!(mask(-(1 << 40)).is_err());
    }
}