catwalk3d 1.0.0

Headless model thumbnails rendered entirely in Rust
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
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
//! Static XCAF documents, decoded from native OCAF/BinTools binary records.
//! Layout facts follow the primary OCCT serializers, not an ASCII alias:
//! <https://github.com/Open-Cascade-SAS/OCCT/tree/V7_9_0/src/BinTools>
//! <https://github.com/Open-Cascade-SAS/OCCT/tree/V7_9_0/src/BinLDrivers>
use super::transform::Transform;
use crate::{
    Result,
    scene::{Scene, Vec3},
};
use std::{
    collections::{HashMap, HashSet},
    fmt::Write as _,
    path::Path,
};

/// Maximum native binary CAD document byte length.
const MAX_BYTES: usize = 16 * 1024 * 1024;
/// Maximum native table records or expanded occurrences.
const MAX_RECORDS: usize = 100_000;
/// Maximum recursive reference, geometry or partition depth.
const MAX_DEPTH: usize = 64;
/// Maximum aggregate native geometry components.
const MAX_COMPONENTS: usize = 1_000_000;

/// Native topology occurrence, including table index, location and orientation.
#[derive(Clone, Copy, Debug)]
struct ShapeRef {
    /// Zero-based native shape-table index.
    node: usize,
    /// Native placement index; zero selects identity.
    location: usize,
    /// Native topology orientation code for this occurrence.
    orientation: u8,
}

/// One native topology record with its geometry and child references.
struct Shape {
    /// Native schema or topology kind selecting the record interpretation.
    kind: u8,
    /// Validated shape geometry encoded in ASCII BREP syntax.
    geometry: String,
    /// Native topology flags retained in the BREP translation.
    flags: u8,
    /// Native child shape occurrences with their locations and orientations.
    children: Vec<ShapeRef>,
}

/// Decoded native geometry/topology tables and quick-part offset indices.
#[derive(Default)]
struct Tables {
    /// Decoded native placement table.
    locations: Vec<Transform>,
    /// Decoded three-dimensional curves in ASCII BREP syntax.
    curves: Vec<String>,
    /// Decoded two-dimensional parameter curves in ASCII BREP syntax.
    pcurves: Vec<String>,
    /// Decoded surface records in ASCII BREP syntax.
    surfaces: Vec<String>,
    /// Decoded native topology records.
    shapes: Vec<Shape>,
    /// Quick-part byte offsets mapped to decoded shape indices.
    shape_positions: HashMap<usize, usize>,
    /// Quick-part byte offsets mapped to decoded location indices.
    location_positions: HashMap<usize, usize>,
    /// Typed quick-part byte offsets mapped to decoded geometry indices.
    geometry_positions: HashMap<(u8, usize), usize>,
}

/// Bounds-checked cursor over one binary document payload.
struct Cursor<'a> {
    /// Borrowed binary input payload.
    bytes: &'a [u8],
    /// Byte offset of the next unread native field.
    pos: usize,
}
impl<'a> Cursor<'a> {
    /// Start a bounds-checked cursor at the beginning of a binary payload.
    fn new(bytes: &'a [u8]) -> Self {
        Self { bytes, pos: 0 }
    }
    /// Consume an exact byte range and advance the cursor.
    ///
    /// # Errors
    ///
    /// The range overflows or the input is truncated.
    fn take(&mut self, size: usize) -> Result<&'a [u8]> {
        let end = self.pos.checked_add(size).ok_or("XBF offset overflow")?;
        let data = self
            .bytes
            .get(self.pos..end)
            .ok_or("truncated XBF record")?;
        self.pos = end;
        Ok(data)
    }
    /// Read one byte from the binary document.
    ///
    /// # Errors
    ///
    /// The input is truncated.
    fn byte(&mut self) -> Result<u8> {
        Ok(self.take(1)?[0])
    }
    /// Read a native boolean encoded as zero or one.
    ///
    /// # Errors
    ///
    /// The input is truncated or the flag uses another value.
    fn boolean(&mut self) -> Result<u8> {
        let value = self.byte()?;
        if value > 1 {
            return Err("invalid XBF boolean".into());
        }
        Ok(value)
    }
    /// Read a little-endian signed 32-bit value.
    ///
    /// # Errors
    ///
    /// The input is truncated.
    fn i32(&mut self) -> Result<i32> {
        Ok(i32::from_le_bytes(self.take(4)?.try_into()?))
    }
    /// Read a little-endian unsigned 64-bit value.
    ///
    /// # Errors
    ///
    /// The input is truncated.
    fn u64(&mut self) -> Result<u64> {
        Ok(u64::from_le_bytes(self.take(8)?.try_into()?))
    }
    /// Read a nonnegative count bounded by the supplied limit.
    ///
    /// # Errors
    ///
    /// The input is truncated, the count is negative or it exceeds the limit.
    fn count(&mut self, limit: usize) -> Result<usize> {
        let count = usize::try_from(self.i32()?).map_err(|_| "negative XBF count")?;
        if count > limit {
            return Err("XBF count exceeds preview limit".into());
        }
        Ok(count)
    }
    /// Read a bounded nonnegative native table index.
    ///
    /// # Errors
    ///
    /// The value is truncated, negative or outside the supplied index limit.
    fn index(&mut self, limit: usize) -> Result<usize> {
        let index = self.count(limit)?;
        if index == 0 {
            return Err("XBF geometry has a null table reference".into());
        }
        Ok(index)
    }
    /// Read a finite little-endian binary64 value.
    ///
    /// # Errors
    ///
    /// The input is truncated or the value is non-finite.
    fn real(&mut self) -> Result<f64> {
        let value = f64::from_le_bytes(self.take(8)?.try_into()?);
        if !value.is_finite() {
            return Err("XBF geometry contains non-finite values".into());
        }
        Ok(value)
    }
    /// Advance to the next native four-byte attribute alignment boundary.
    ///
    /// # Errors
    ///
    /// Alignment would advance beyond the payload.
    fn align(&mut self) -> Result<()> {
        let size = (4 - self.pos % 4) % 4;
        self.take(size)?;
        Ok(())
    }
    /// Decode a bounded string using native one-byte or UTF-16 storage.
    ///
    /// # Errors
    ///
    /// Length/encoding is invalid or the string payload is truncated.
    fn string(&mut self, width: usize) -> Result<String> {
        let size = self.count(MAX_COMPONENTS)?;
        let data = self.take(size.checked_mul(width).ok_or("XBF string overflow")?)?;
        if width == 1 {
            Ok(std::str::from_utf8(data)?.trim_end_matches('\0').to_owned())
        } else {
            let data: Vec<u16> = data
                .as_chunks::<2>()
                .0
                .iter()
                .map(|b| u16::from_le_bytes([b[0], b[1]]))
                .collect();
            Ok(String::from_utf16(&data)?.trim_end_matches('\0').to_owned())
        }
    }
    /// Read and validate a named native geometry-table header.
    ///
    /// # Errors
    ///
    /// The name, record count or table extent is invalid or unsupported.
    fn table_header(&mut self, expected: &str) -> Result<usize> {
        while self
            .bytes
            .get(self.pos)
            .is_some_and(u8::is_ascii_whitespace)
        {
            self.pos += 1;
        }
        let start = self.pos;
        while self.bytes.get(self.pos).is_some_and(|b| *b != b'\n') {
            self.pos += 1;
        }
        let line = std::str::from_utf8(
            self.bytes
                .get(start..self.pos)
                .ok_or("truncated XBF table")?,
        )?;
        self.take(1)?;
        let mut words = line.split_whitespace();
        if words.next() != Some(expected) {
            return Err(format!("XBF expected {expected} table").into());
        }
        let count = words
            .next()
            .ok_or("XBF table lacks a count")?
            .parse::<usize>()?;
        if count > MAX_RECORDS || words.next().is_some() {
            return Err("invalid or oversized XBF table".into());
        }
        Ok(count)
    }
    /// Read a bounded native quick-part back-reference.
    ///
    /// # Errors
    ///
    /// The reference type, offset or cursor position is invalid.
    fn reference(&mut self, kind: u8) -> Result<usize> {
        let start = self.pos.checked_sub(1).ok_or("invalid XBF reference")?;
        let delta = match kind {
            1 => u64::from(self.byte()?),
            2 => u64::from(u16::from_le_bytes(self.take(2)?.try_into()?)),
            3 => u64::from(u32::from_le_bytes(self.take(4)?.try_into()?)),
            4 => self.u64()?,
            _ => return Err("invalid XBF reference type".into()),
        };
        let delta = usize::try_from(delta)?;
        if delta == 0 {
            return Err("zero XBF backward reference".into());
        }
        start
            .checked_sub(delta)
            .ok_or_else(|| "XBF reference precedes the file".into())
    }
}

/// Append finite native real values in the ASCII BREP interchange syntax.
///
/// # Errors
///
/// The binary values are truncated/non-finite or formatting fails.
fn real_text(cursor: &mut Cursor<'_>, output: &mut String, count: usize) -> Result<()> {
    if count > MAX_COMPONENTS {
        return Err("XBF geometry exceeds one million components".into());
    }
    for _ in 0..count {
        write!(output, "{} ", cursor.real()?)?;
    }
    if output.len() > MAX_BYTES {
        return Err("decoded XBF geometry exceeds 16 MiB".into());
    }
    Ok(())
}

/// Read a supported bounded spline degree.
///
/// # Errors
///
/// The degree is truncated, invalid or exceeds the supported bound.
fn degree(cursor: &mut Cursor<'_>) -> Result<usize> {
    let degree = usize::from(u16::from_le_bytes(cursor.take(2)?.try_into()?));
    if !(1..=64).contains(&degree) {
        return Err("XBF spline degree is outside 1..64".into());
    }
    Ok(degree)
}

/// `BinTools` curve payloads have the same actual geometry as their BREP records.
fn curve(cursor: &mut Cursor<'_>, dimension: usize, depth: usize) -> Result<String> {
    if depth > MAX_DEPTH {
        return Err("XBF nested curves exceed 64 levels".into());
    }
    let kind = cursor.byte()?;
    let mut out = format!("{kind} ");
    match kind {
        1 => real_text(cursor, &mut out, dimension * 2)?,
        2..=5 => {
            real_text(cursor, &mut out, if dimension == 2 { 6 } else { 12 })?;
            real_text(cursor, &mut out, if matches!(kind, 3 | 5) { 2 } else { 1 })?;
        }
        6 | 7 => {
            let rational = cursor.boolean()?;
            let periodic = if kind == 7 { cursor.boolean()? } else { 0 };
            let degree = degree(cursor)?;
            let poles = if kind == 7 {
                cursor.count(MAX_RECORDS)?
            } else {
                degree + 1
            };
            let knots = if kind == 7 {
                cursor.count(MAX_RECORDS)?
            } else {
                2
            };
            if poles < 2 || knots < 2 {
                return Err("invalid XBF spline sizes".into());
            }
            // Exact Bezier conversion: clamped B-spline with the same poles.
            out = format!("7 {rational} {periodic} {degree} {poles} {knots} ");
            real_text(
                cursor,
                &mut out,
                poles * (dimension + usize::from(rational)),
            )?;
            if kind == 6 {
                write!(out, "0 {} 1 {} ", degree + 1, degree + 1)?;
            } else {
                for _ in 0..knots {
                    write!(out, "{} {} ", cursor.real()?, cursor.count(degree + 1)?)?;
                }
            }
        }
        8 => {
            real_text(cursor, &mut out, 2)?;
            out.push_str(&curve(cursor, dimension, depth + 1)?);
        }
        9 => {
            real_text(cursor, &mut out, if dimension == 3 { 4 } else { 1 })?;
            out.push_str(&curve(cursor, dimension, depth + 1)?);
        }
        _ => return Err(format!("unsupported XBF curve representation {kind}").into()),
    }
    Ok(out)
}

/// Translate one native surface record to validated BREP text.
///
/// # Errors
///
/// The surface schema, numeric payload or recursion/spline limits are unsupported or invalid.
fn surface(cursor: &mut Cursor<'_>, depth: usize) -> Result<String> {
    if depth > MAX_DEPTH {
        return Err("XBF nested surfaces exceed 64 levels".into());
    }
    let kind = cursor.byte()?;
    let mut out = format!("{kind} ");
    match kind {
        1..=5 => {
            real_text(cursor, &mut out, 12)?;
            real_text(
                cursor,
                &mut out,
                match kind {
                    1 => 0,
                    2 | 4 => 1,
                    _ => 2,
                },
            )?;
        }
        6 | 7 => {
            real_text(cursor, &mut out, if kind == 6 { 3 } else { 6 })?;
            out.push_str(&curve(cursor, 3, depth + 1)?);
        }
        8 | 9 => {
            let ur = cursor.boolean()?;
            let vr = cursor.boolean()?;
            let up = if kind == 9 { cursor.boolean()? } else { 0 };
            let vp = if kind == 9 { cursor.boolean()? } else { 0 };
            let ud = degree(cursor)?;
            let vd = degree(cursor)?;
            let un = if kind == 9 {
                cursor.count(MAX_RECORDS)?
            } else {
                ud + 1
            };
            let vn = if kind == 9 {
                cursor.count(MAX_RECORDS)?
            } else {
                vd + 1
            };
            let uk = if kind == 9 {
                cursor.count(MAX_RECORDS)?
            } else {
                2
            };
            let vk = if kind == 9 {
                cursor.count(MAX_RECORDS)?
            } else {
                2
            };
            let cells = un.checked_mul(vn).ok_or("XBF spline grid overflow")?;
            if cells > MAX_RECORDS || un < 2 || vn < 2 || uk < 2 || vk < 2 {
                return Err("invalid or oversized XBF surface grid".into());
            }
            out = format!("9 {ur} {vr} {up} {vp} {ud} {vd} {un} {vn} {uk} {vk} ");
            real_text(cursor, &mut out, cells * (3 + usize::from(ur | vr)))?;
            if kind == 8 {
                write!(out, "0 {} 1 {} 0 {} 1 {} ", ud + 1, ud + 1, vd + 1, vd + 1)?;
            } else {
                for (count, degree) in [(uk, ud), (vk, vd)] {
                    for _ in 0..count {
                        write!(out, "{} {} ", cursor.real()?, cursor.count(degree + 1)?)?;
                    }
                }
            }
        }
        10 => {
            real_text(cursor, &mut out, 4)?;
            out.push_str(&surface(cursor, depth + 1)?);
        }
        11 => {
            real_text(cursor, &mut out, 1)?;
            out.push_str(&surface(cursor, depth + 1)?);
        }
        _ => return Err(format!("unsupported XBF surface representation {kind}").into()),
    }
    Ok(out)
}

/// Read a finite native affine placement matrix.
///
/// # Errors
///
/// The matrix payload is truncated or contains non-finite numbers.
fn read_transform(cursor: &mut Cursor<'_>) -> Result<Transform> {
    let mut transform = Transform::IDENTITY;
    for row in 0..3 {
        for column in &mut transform.0 {
            column[row] = cursor.real()?;
        }
    }
    Ok(transform)
}

/// Invert a finite nonsingular affine placement.
///
/// # Errors
///
/// The matrix is singular or its inverse exceeds numeric range.
fn inverse(transform: Transform) -> Result<Transform> {
    let c = transform.0;
    let a = Vec3::new(c[0][0], c[0][1], c[0][2]);
    let b = Vec3::new(c[1][0], c[1][1], c[1][2]);
    let d = Vec3::new(c[2][0], c[2][1], c[2][2]);
    let determinant = a.dot(b.cross(d));
    if !determinant.is_finite() || determinant.abs() < 1e-30 {
        return Err("singular XBF location".into());
    }
    let rows = [
        b.cross(d) / determinant,
        d.cross(a) / determinant,
        a.cross(b) / determinant,
    ];
    let mut result = Transform::IDENTITY;
    for (row, r) in rows.iter().enumerate() {
        result.0[0][row] = r.x;
        result.0[1][row] = r.y;
        result.0[2][row] = r.z;
    }
    let translation = Vec3::new(c[3][0], c[3][1], c[3][2]);
    let offset = -result.apply(translation);
    result.0[3] = [offset.x, offset.y, offset.z, 1.0];
    Ok(result)
}

/// Compose a placement raised to a bounded signed integer power.
///
/// # Errors
///
/// The exponent exceeds limits or a negative power requires an invalid inverse.
fn power(mut transform: Transform, exponent: i32) -> Result<Transform> {
    if exponent.unsigned_abs() > 1024 {
        return Err("XBF location power exceeds 1024".into());
    }
    if exponent < 0 {
        transform = inverse(transform)?;
    }
    let mut result = Transform::IDENTITY;
    for _ in 0..exponent.unsigned_abs() {
        result = result.then(transform);
    }
    if result.0.iter().flatten().any(|v| !v.is_finite()) {
        return Err("XBF location composition overflow".into());
    }
    Ok(result)
}

impl Tables {
    /// Read or reuse a native quick-part location record.
    ///
    /// # Errors
    ///
    /// The placement/back-reference is invalid or exceeds nesting/table limits.
    fn location(&mut self, cursor: &mut Cursor<'_>, depth: usize) -> Result<usize> {
        if depth > MAX_DEPTH || self.locations.len() >= MAX_RECORDS {
            return Err("XBF location hierarchy exceeds preview limits".into());
        }
        let pos = cursor.pos;
        let kind = cursor.byte()?;
        if matches!(kind, 7 | 8) {
            return Ok(0);
        }
        if (1..=4).contains(&kind) {
            let reference = cursor.reference(kind)?;
            return self
                .location_positions
                .get(&reference)
                .copied()
                .ok_or_else(|| "unknown/cyclic XBF location reference".into());
        }
        let transform = match kind {
            6 => read_transform(cursor)?,
            5 => {
                let mut result = Transform::IDENTITY;
                loop {
                    let id = self.location(cursor, depth + 1)?;
                    if id == 0 {
                        break;
                    }
                    let exponent = cursor.i32()?;
                    result = power(self.locations[id - 1], exponent)?.then(result);
                }
                result
            }
            _ => return Err("unsupported XBF location representation".into()),
        };
        let id = self.locations.len() + 1;
        self.locations.push(transform);
        self.location_positions.insert(pos, id);
        Ok(id)
    }
    /// Read or reuse a native typed geometry-table record.
    ///
    /// # Errors
    ///
    /// The schema/back-reference is invalid or exceeds geometry limits.
    fn geometry(&mut self, cursor: &mut Cursor<'_>, expected: u8) -> Result<usize> {
        let pos = cursor.pos;
        let kind = cursor.byte()?;
        if kind == expected + 1 {
            return Err("XBF topology references empty curve/surface geometry".into());
        }
        if (1..=4).contains(&kind) {
            let reference = cursor.reference(kind)?;
            return self
                .geometry_positions
                .get(&(expected, reference))
                .copied()
                .ok_or_else(|| "unknown XBF geometry reference".into());
        }
        if kind != expected {
            return Err("XBF geometry record has the wrong type".into());
        }
        let text = match expected {
            9 => curve(cursor, 3, 0)?,
            11 => curve(cursor, 2, 0)?,
            13 => surface(cursor, 0)?,
            _ => return Err("unsupported XBF geometry object".into()),
        };
        let table = match expected {
            9 => &mut self.curves,
            11 => &mut self.pcurves,
            _ => &mut self.surfaces,
        };
        if table.len() >= MAX_RECORDS {
            return Err("XBF geometry table exceeds 100000 records".into());
        }
        table.push(text);
        let id = table.len();
        self.geometry_positions.insert((expected, pos), id);
        Ok(id)
    }
    /// Read or reuse quick-part topology with its native location and orientation.
    ///
    /// # Errors
    ///
    /// The topology schema, reference or bounded child hierarchy is invalid.
    fn shape(&mut self, cursor: &mut Cursor<'_>, depth: usize) -> Result<Option<ShapeRef>> {
        if depth > MAX_DEPTH || self.shapes.len() >= MAX_RECORDS {
            return Err("XBF shape hierarchy exceeds preview limits".into());
        }
        let pos = cursor.pos;
        let kind = cursor.byte()?;
        if matches!(kind, 198 | 199) {
            return Ok(None);
        }
        if (1..=4).contains(&kind) {
            let reference = cursor.reference(kind)?;
            let node = *self
                .shape_positions
                .get(&reference)
                .ok_or("unknown/cyclic XBF shape reference")?;
            let location = self.location(cursor, 0)?;
            let orientation = cursor.byte()?;
            if orientation > 3 {
                return Err("invalid XBF shape orientation".into());
            }
            return Ok(Some(ShapeRef {
                node,
                location,
                orientation,
            }));
        }
        if !(200..=231).contains(&kind) {
            return Err("invalid XBF shape tag".into());
        }
        let orientation = (kind - 200) & 3;
        let kind = (kind - 200) >> 2;
        let location = self.location(cursor, 0)?;
        let geometry = self.quick_shape_geometry(cursor, kind)?;
        let flags = cursor.byte()?;
        if flags & 128 != 0 {
            return Err("invalid XBF shape flags".into());
        }
        let mut children = Vec::new();
        while let Some(child) = self.shape(cursor, depth + 1)? {
            if children.len() >= MAX_RECORDS {
                return Err("XBF shape has too many children".into());
            }
            children.push(child);
        }
        let node = self.shapes.len();
        self.shapes.push(Shape {
            kind,
            geometry,
            flags,
            children,
        });
        self.shape_positions.insert(pos, node);
        Ok(Some(ShapeRef {
            node,
            location,
            orientation,
        }))
    }
    /// Translate quick-part shape geometry into the corresponding BREP payload.
    ///
    /// # Errors
    ///
    /// The shape/representation schema, numbers or geometry references are invalid or unsupported.
    #[allow(
        clippy::too_many_lines,
        reason = "Keep the format record dispatch, validation and its resource checks together without changing geometry evaluation."
    )]
    fn quick_shape_geometry(&mut self, cursor: &mut Cursor<'_>, kind: u8) -> Result<String> {
        let mut out = String::new();
        match kind {
            7 => {
                real_text(cursor, &mut out, 4)?;
                loop {
                    let rep = cursor.byte()?;
                    if rep == 0 {
                        break;
                    }
                    cursor.real()?;
                    match rep {
                        1 => {
                            self.geometry(cursor, 9)?;
                        }
                        2 => {
                            self.geometry(cursor, 11)?;
                            self.geometry(cursor, 13)?;
                        }
                        3 => {
                            cursor.real()?;
                            self.geometry(cursor, 13)?;
                        }
                        _ => return Err("unsupported XBF vertex representation".into()),
                    }
                    self.location(cursor, 0)?;
                }
                out.push_str("0 0\n");
            }
            6 => {
                real_text(cursor, &mut out, 1)?;
                let flags = cursor.byte()?;
                if flags & !7 != 0 {
                    return Err("invalid XBF edge flags".into());
                }
                writeln!(
                    out,
                    "{} {} {}",
                    flags & 1,
                    (flags >> 1) & 1,
                    (flags >> 2) & 1
                )?;
                loop {
                    let rep = cursor.byte()?;
                    if rep == 0 {
                        break;
                    }
                    write!(out, "{rep} ")?;
                    match rep {
                        1 => {
                            let curve = self.geometry(cursor, 9)?;
                            let loc = self.location(cursor, 0)?;
                            self.check_representation_location(loc)?;
                            write!(out, "{curve} {loc} ")?;
                            real_text(cursor, &mut out, 2)?;
                        }
                        2 | 3 => {
                            let curve = self.geometry(cursor, 11)?;
                            write!(out, "{curve} ")?;
                            if rep == 3 {
                                let curve = self.geometry(cursor, 11)?;
                                let continuity = cursor.byte()?;
                                write!(out, "{curve} {} ", continuity_text(continuity)?)?;
                            }
                            let surface = self.geometry(cursor, 13)?;
                            let loc = self.location(cursor, 0)?;
                            self.check_representation_location(loc)?;
                            write!(out, "{surface} {loc} ")?;
                            real_text(cursor, &mut out, 2)?;
                        }
                        4 => {
                            write!(out, "{} ", continuity_text(cursor.byte()?)?)?;
                            for _ in 0..2 {
                                let s = self.geometry(cursor, 13)?;
                                let l = self.location(cursor, 0)?;
                                write!(out, "{s} {l} ")?;
                            }
                        }
                        _ => {
                            return Err(
                                "XBF polygon-only edge representations are unsupported".into()
                            );
                        }
                    }
                    out.push('\n');
                }
                out.push_str("0\n");
            }
            4 => {
                write!(out, "{} ", cursor.boolean()?)?;
                real_text(cursor, &mut out, 1)?;
                let surface = self.geometry(cursor, 13)?;
                let loc = self.location(cursor, 0)?;
                self.check_representation_location(loc)?;
                if surface == 0 {
                    return Err("XBF face has no analytic surface".into());
                }
                writeln!(out, "{surface} {loc}")?;
                match cursor.byte()? {
                    0 | 1 => {}
                    _ => return Err("XBF faces with stored triangulations are unsupported".into()),
                }
            }
            0..=3 | 5 => {}
            _ => return Err("unsupported XBF topology type".into()),
        }
        Ok(out)
    }
}

/// Map a native continuity enumeration to its BREP spelling.
///
/// # Errors
///
/// The continuity value is outside the supported enumeration.
fn continuity_text(kind: u8) -> Result<&'static str> {
    ["C0", "G1", "C1", "G2", "C2", "C3", "CN"]
        .get(usize::from(kind))
        .copied()
        .ok_or_else(|| "invalid XBF continuity".into())
}

/// Read and render a native binary XCAF/BREP document.
///
/// # Errors
///
/// File access, binary schema, geometry, document roots or tessellation fail validation.
pub(super) fn load(path: &Path) -> Result<Scene> {
    let bytes = super::read_file(path)?;
    parse(&bytes)
}

/// Document label attributes needed for shape ownership, placement and color.
#[derive(Default)]
struct Label {
    /// Native integer label path identifying this document label.
    path: Vec<i32>,
    /// Native shape occurrences directly stored in this label.
    shapes: Vec<ShapeRef>,
    /// Native placement index; zero selects identity.
    location: Option<usize>,
    /// Whether this label declares the document shape-tool attribute.
    shape_tool: bool,
    /// Native attribute trees indexed by their supported type identifiers.
    trees: HashMap<u32, Tree>,
    /// Optional inherited RGB surface or line color.
    color: Option<[u8; 3]>,
    /// Whether this label references externally stored geometry.
    external: bool,
}
/// Native attribute-tree links used by shape and color associations.
struct Tree {
    /// Native attribute identifier used by tree links.
    id: i32,
    /// Native parent attribute identifier in the association tree.
    father: i32,
    /// Native first-child attribute identifier in the association tree.
    first: i32,
}
/// Supported binary document metadata and indexed label attributes.
struct Document {
    /// Supported native binary document format version.
    version: u32,
    /// Attribute type names in native table order.
    types: Vec<String>,
    /// Decoded document labels and their supported attributes.
    labels: Vec<Label>,
    /// Native attribute identifiers mapped to owning label indices.
    attribute_labels: HashMap<i32, usize>,
}

/// Resolve binary document attributes and native geometry into a complete scene.
///
/// # Errors
///
/// Document headers, labels, tables, references or CAD geometry are invalid, unsupported or oversized.
#[allow(
    clippy::too_many_lines,
    reason = "Keep the format record dispatch, validation and its resource checks together without changing geometry evaluation."
)]
fn parse(bytes: &[u8]) -> Result<Scene> {
    if bytes.len() > MAX_BYTES {
        return Err("XBF input exceeds the 16 MiB preview limit".into());
    }
    let mut cursor = Cursor::new(bytes);
    if cursor.take(7)? != b"BINFILE" || cursor.i32()? != 0x0403_0201 {
        return Err("unsupported XBF binary signature or byte order".into());
    }
    let mut header = [0i32; 12];
    for word in &mut header {
        *word = cursor.i32()?;
    }
    cursor.count(MAX_RECORDS)?; // generic persistent object count
    let version = cursor.string(1)?.parse::<u32>()?;
    if !(6..=12).contains(&version) {
        return Err("XBF document versions outside 6..12 are unsupported".into());
    }
    cursor.string(1)?;
    cursor.string(1)?;
    cursor.string(1)?;
    cursor.string(2)?;
    cursor.string(1)?;
    cursor.string(2)?;
    let user_count = cursor.count(MAX_RECORDS)?;
    let mut types = Vec::new();
    let mut in_types = false;
    let mut xcaf = false;
    for _ in 0..user_count {
        let value = cursor.string(1)?;
        match value.as_str() {
            "START_TYPES" => in_types = true,
            "END_TYPES" => in_types = false,
            "FILE_FORMAT: BinXCAF" => xcaf = true,
            _ if in_types => types.push(value),
            _ => {}
        }
    }
    if !xcaf || in_types || types.is_empty() {
        return Err("XBF input is not a valid BinXCAF document".into());
    }
    let document_section =
        usize::try_from(header[11]).map_err(|_| "invalid XBF document offset")?;
    if document_section < cursor.pos || document_section > bytes.len() {
        return Err("invalid XBF header section bounds".into());
    }
    cursor.pos = document_section;
    let mut shape_section = None;
    {
        let name = cursor.string(1)?;
        let (offset, length, post) = if version <= 9 {
            (
                u64::try_from(cursor.i32()?)?,
                u64::try_from(cursor.i32()?)?,
                u64::try_from(cursor.i32()?)?,
            )
        } else {
            (cursor.u64()?, cursor.u64()?, cursor.u64()?)
        };
        if name == "SHAPE_SECTION_POS:" {
            if post != 0 {
                return Err("post-read XBF shape sections are unsupported".into());
            }
            let start = usize::try_from(offset)?;
            let length = usize::try_from(length)?;
            let end = start.checked_add(length).ok_or("XBF section overflow")?;
            if start < cursor.pos || end > bytes.len() {
                return Err("invalid XBF shape section bounds".into());
            }
            shape_section = Some((start, end));
        } else if name != ":" || version != 12 {
            return Err(format!("unsupported XBF document section {name}").into());
        }
    }
    if version < 12 && shape_section.is_none() {
        return Err("XBF document has no shape section".into());
    }
    let mut tables = Tables::default();
    if let Some((start, end)) = shape_section {
        let mut shape_cursor = Cursor {
            bytes: &bytes[..end],
            pos: start,
        };
        tables.read_old(&mut shape_cursor)?;
        if shape_cursor.pos != end {
            return Err("XBF shape section length disagrees with geometry".into());
        }
    }
    if cursor.i32()? != 0 {
        return Err("XBF document root label must have tag zero".into());
    }
    let mut document = Document {
        version,
        types,
        labels: Vec::new(),
        attribute_labels: HashMap::new(),
    };
    document.label(&mut cursor, &mut tables, vec![0], 0)?;
    let expected_end = shape_section.map_or(bytes.len(), |(start, _)| start);
    if cursor.pos != expected_end {
        return Err("XBF document hierarchy has trailing or missing records".into());
    }
    document.render(&mut tables)
}

impl Tables {
    /// Read native table-based geometry for supported legacy document versions.
    ///
    /// # Errors
    ///
    /// Table schemas, references, numeric data or limits are invalid or unsupported.
    #[allow(
        clippy::too_many_lines,
        reason = "Keep the format record dispatch, validation and its resource checks together without changing geometry evaluation."
    )]
    fn read_old(&mut self, cursor: &mut Cursor<'_>) -> Result<()> {
        let start = cursor.pos;
        let prefix = cursor
            .bytes
            .get(start..)
            .ok_or("truncated XBF shape section")?;
        if !prefix.starts_with(b"SHAPE_SECTION") {
            return Err("XBF document lacks a native shape section".into());
        }
        cursor.take(13)?;
        while cursor
            .bytes
            .get(cursor.pos)
            .is_some_and(u8::is_ascii_whitespace)
        {
            cursor.pos += 1;
        }
        let start = cursor.pos;
        while cursor.bytes.get(cursor.pos).is_some_and(|b| *b != b'\n') {
            cursor.pos += 1;
        }
        let version = std::str::from_utf8(
            cursor
                .bytes
                .get(start..cursor.pos)
                .ok_or("truncated XBF shape version")?,
        )?;
        let version = match version.trim() {
            "Open CASCADE Topology V1 (c)" => 1,
            "Open CASCADE Topology V2 (c)" => 2,
            "Open CASCADE Topology V3 (c)" => 3,
            "Open CASCADE Topology V4, (c) Open Cascade" => 4,
            _ => return Err("unsupported XBF BinTools topology version".into()),
        };
        cursor.take(1)?;
        let count = cursor.table_header("Locations")?;
        for _ in 0..count {
            let transform = match cursor.byte()? {
                1 => read_transform(cursor)?,
                2 => {
                    let mut result = Transform::IDENTITY;
                    loop {
                        let id = cursor.count(self.locations.len())?;
                        if id == 0 {
                            break;
                        }
                        result = result.then(power(self.locations[id - 1], cursor.i32()?)?);
                    }
                    result
                }
                _ => return Err("unsupported XBF table location".into()),
            };
            self.locations.push(transform);
        }
        let count = cursor.table_header("Curve2ds")?;
        for _ in 0..count {
            self.pcurves.push(curve(cursor, 2, 0)?);
        }
        let count = cursor.table_header("Curves")?;
        for _ in 0..count {
            self.curves.push(curve(cursor, 3, 0)?);
        }
        if cursor.table_header("Polygon3D")? != 0
            || cursor.table_header("PolygonOnTriangulations")? != 0
        {
            return Err("XBF table polygon representations are unsupported".into());
        }
        let count = cursor.table_header("Surfaces")?;
        for _ in 0..count {
            self.surfaces.push(surface(cursor, 0)?);
        }
        if cursor.table_header("Triangulations")? != 0 {
            return Err("XBF stored triangulations are unsupported".into());
        }
        let total = cursor.table_header("TShapes")?;
        for _ in 0..total {
            let kind = cursor.byte()?;
            let geometry = self.old_shape_geometry(cursor, kind, version)?;
            let mut flags = 0;
            for bit in 0..7 {
                flags |= cursor.boolean()? << bit;
            }
            let mut children = Vec::new();
            loop {
                let orientation = cursor.byte()?;
                if orientation == b'*' {
                    break;
                }
                if orientation > 3 {
                    return Err("invalid XBF table orientation".into());
                }
                let reverse_id = cursor.count(total)?;
                if reverse_id == 0 {
                    return Err("zero XBF topology reference".into());
                }
                let node = total - reverse_id;
                if node >= self.shapes.len() {
                    return Err("forward/cyclic XBF topology reference".into());
                }
                let location = cursor.count(self.locations.len())?;
                if children.len() >= MAX_RECORDS {
                    return Err("XBF shape has too many children".into());
                }
                children.push(ShapeRef {
                    node,
                    location,
                    orientation,
                });
            }
            self.shapes.push(Shape {
                kind,
                geometry,
                flags,
                children,
            });
        }
        Ok(())
    }
    /// Translate legacy table-based shape representations to BREP syntax.
    ///
    /// # Errors
    ///
    /// Native representation data or geometry/location references are invalid or unsupported.
    #[allow(
        clippy::too_many_lines,
        reason = "Keep the format record dispatch, validation and its resource checks together without changing geometry evaluation."
    )]
    fn old_shape_geometry(
        &self,
        cursor: &mut Cursor<'_>,
        kind: u8,
        version: u32,
    ) -> Result<String> {
        let mut out = String::new();
        match kind {
            7 => {
                real_text(cursor, &mut out, 4)?;
                loop {
                    let rep = cursor.byte()?;
                    if rep == 0 {
                        break;
                    }
                    cursor.real()?;
                    match rep {
                        1 => {
                            cursor.count(self.curves.len())?;
                        }
                        2 => {
                            cursor.count(self.pcurves.len())?;
                            cursor.count(self.surfaces.len())?;
                        }
                        3 => {
                            cursor.real()?;
                            cursor.count(self.surfaces.len())?;
                        }
                        _ => return Err("unsupported XBF table vertex representation".into()),
                    }
                    cursor.count(self.locations.len())?;
                }
                out.push_str("0 0\n");
            }
            6 => {
                real_text(cursor, &mut out, 1)?;
                writeln!(
                    out,
                    "{} {} {}",
                    cursor.boolean()?,
                    cursor.boolean()?,
                    cursor.boolean()?
                )?;
                loop {
                    let rep = cursor.byte()?;
                    if rep == 0 {
                        break;
                    }
                    write!(out, "{rep} ")?;
                    match rep {
                        1 => {
                            let curve = cursor.index(self.curves.len())?;
                            let location = cursor.count(self.locations.len())?;
                            self.check_representation_location(location)?;
                            write!(out, "{curve} {location} ")?;
                            real_text(cursor, &mut out, 2)?;
                        }
                        2 | 3 => {
                            write!(out, "{} ", cursor.index(self.pcurves.len())?)?;
                            if rep == 3 {
                                write!(
                                    out,
                                    "{} {} ",
                                    cursor.index(self.pcurves.len())?,
                                    continuity_text(cursor.byte()?)?
                                )?;
                            }
                            let surface = cursor.index(self.surfaces.len())?;
                            let location = cursor.count(self.locations.len())?;
                            self.check_representation_location(location)?;
                            write!(out, "{surface} {location} ")?;
                            real_text(cursor, &mut out, 2)?;
                            if matches!(version, 2 | 3) {
                                for _ in 0..4 {
                                    cursor.real()?;
                                }
                            }
                        }
                        4 => {
                            write!(out, "{} ", continuity_text(cursor.byte()?)?)?;
                            for _ in 0..2 {
                                write!(
                                    out,
                                    "{} {} ",
                                    cursor.count(self.surfaces.len())?,
                                    cursor.count(self.locations.len())?
                                )?;
                            }
                        }
                        _ => return Err("unsupported XBF table edge representation".into()),
                    }
                    out.push('\n');
                }
                out.push_str("0\n");
            }
            4 => {
                write!(out, "{} ", cursor.boolean()?)?;
                real_text(cursor, &mut out, 1)?;
                let surface = cursor.index(self.surfaces.len())?;
                let location = cursor.count(self.locations.len())?;
                self.check_representation_location(location)?;
                if surface == 0 {
                    return Err("XBF face has no analytic surface".into());
                }
                writeln!(out, "{surface} {location}")?;
                match cursor.byte()? {
                    0 | 1 => {}
                    _ => return Err("XBF face triangulation references are unsupported".into()),
                }
            }
            0..=3 | 5 => {}
            _ => return Err("unsupported XBF table topology type".into()),
        }
        Ok(out)
    }
    /// Decode a stored shape reference and its placement/orientation.
    ///
    /// # Errors
    ///
    /// The encoded shape, location or orientation is invalid or missing.
    fn stored_reference(&self, cursor: &mut Cursor<'_>) -> Result<ShapeRef> {
        cursor.align()?;
        let index = cursor.count(self.shapes.len())?;
        if index == 0 {
            return Err("XBF named shape has a null shape reference".into());
        }
        let location = cursor.count(self.locations.len())?;
        let orientation = match cursor.byte()? {
            b'F' => 0,
            b'R' => 1,
            b'I' => 2,
            b'E' => 3,
            _ => return Err("invalid XBF named shape orientation".into()),
        };
        Ok(ShapeRef {
            node: index - 1,
            location,
            orientation,
        })
    }
    /// Resolve a native location table index, including identity index zero.
    ///
    /// # Errors
    ///
    /// The location index is out of range.
    fn location_transform(&self, index: usize) -> Result<Transform> {
        if index == 0 {
            Ok(Transform::IDENTITY)
        } else {
            self.locations
                .get(index - 1)
                .copied()
                .ok_or_else(|| "invalid XBF location index".into())
        }
    }
    /// Check a representation's native location reference.
    ///
    /// # Errors
    ///
    /// The location does not resolve to a known placement.
    fn check_representation_location(&self, index: usize) -> Result<()> {
        self.location_transform(index)?;
        Ok(())
    }
}

impl Document {
    /// Read one document label and its supported typed attributes recursively.
    ///
    /// # Errors
    ///
    /// Attributes, labels, references or nesting limits are malformed or unsupported.
    #[allow(
        clippy::too_many_lines,
        reason = "Keep the format record dispatch, validation and its resource checks together without changing geometry evaluation."
    )]
    fn label(
        &mut self,
        cursor: &mut Cursor<'_>,
        tables: &mut Tables,
        path: Vec<i32>,
        depth: usize,
    ) -> Result<()> {
        if depth > MAX_DEPTH || self.labels.len() >= MAX_RECORDS {
            return Err("XBF document hierarchy exceeds preview limits".into());
        }
        let label_end = if self.version == 12 {
            let position = cursor.pos;
            let size = usize::try_from(cursor.u64()?)?;
            let end = position
                .checked_add(size)
                .ok_or("XBF label size overflow")?;
            if size < 16 || end > cursor.bytes.len() {
                return Err("invalid XBF label size".into());
            }
            Some(end)
        } else {
            None
        };
        let index = self.labels.len();
        self.labels.push(Label {
            path,
            ..Default::default()
        });
        loop {
            let kind = cursor.i32()?;
            if kind == -1 {
                break;
            }
            let kind = usize::try_from(kind).map_err(|_| "invalid XBF attribute type")?;
            let name = self
                .types
                .get(kind.checked_sub(1).ok_or("zero XBF attribute type")?)
                .ok_or("unknown XBF attribute type")?
                .clone();
            let id = cursor.i32()?;
            if id == 0 || id == i32::MIN || self.attribute_labels.insert(id.abs(), index).is_some()
            {
                return Err("invalid or duplicate XBF attribute ID".into());
            }
            let size = cursor.count(MAX_BYTES)?;
            let data = cursor.take(size)?;
            let mut value = Cursor::new(data);
            let mut direct_end = None;
            if id < 0 {
                if self.version != 12 {
                    return Err("inline XBF attributes require document version 12".into());
                }
                let start = cursor.pos;
                let size = usize::try_from(cursor.u64()?)?;
                let end = start
                    .checked_add(size)
                    .ok_or("XBF inline attribute overflow")?;
                if size < 8 || end > cursor.bytes.len() {
                    return Err("invalid XBF inline attribute length".into());
                }
                direct_end = Some(end);
            }
            match name.as_str() {
                "XCAFDoc_ShapeTool" => self.labels[index].shape_tool = true,
                "TNaming_NamedShape" => {
                    let count = value.count(MAX_RECORDS)?;
                    value.i32()?;
                    let evolution = value.byte()?;
                    if !b"PGMDSR".contains(&evolution) {
                        return Err("unsupported XBF shape evolution".into());
                    }
                    for _ in 0..count {
                        if evolution != b'P' {
                            if direct_end.is_some() {
                                tables.shape(cursor, 0)?;
                            } else {
                                tables.stored_reference(&mut value)?;
                            }
                        }
                        if evolution != b'D' {
                            let shape = if direct_end.is_some() {
                                tables.shape(cursor, 0)?.ok_or("null XBF named shape")?
                            } else {
                                tables.stored_reference(&mut value)?
                            };
                            self.labels[index].shapes.push(shape);
                        }
                    }
                    if value.pos != data.len() {
                        return Err("XBF named-shape payload has trailing data".into());
                    }
                }
                "XCAFDoc_Location" => {
                    let location = if direct_end.is_some() {
                        tables.location(cursor, 0)?
                    } else {
                        let first = value.count(tables.locations.len())?;
                        // The v6+ attribute repeats the remaining location
                        // chain for legacy compatibility. The first table
                        // entry already stores the exact complete transform.
                        while value.pos < data.len() {
                            value.count(tables.locations.len())?;
                        }
                        first
                    };
                    self.labels[index].location = Some(location);
                }
                "TDataStd_TreeNode" => {
                    let father = value.i32()?;
                    value.i32()?;
                    value.i32()?;
                    let first = value.i32()?;
                    let guid = value.take(16)?;
                    let prefix = u32::from_le_bytes(guid[..4].try_into()?);
                    if value.pos != data.len() {
                        return Err("invalid XBF tree attribute length".into());
                    }
                    self.labels[index].trees.insert(
                        prefix,
                        Tree {
                            id: id.abs(),
                            father,
                            first,
                        },
                    );
                }
                "XCAFDoc_Color" => {
                    let mut color = [0u8; 3];
                    for component in &mut color {
                        let value = value.real()?;
                        if !(0.0..=1.0).contains(&value) {
                            return Err("XBF color is outside 0..1".into());
                        }
                        *component = linear_color(value);
                    }
                    if value.pos < data.len() {
                        let alpha = f32::from_le_bytes(value.take(4)?.try_into()?);
                        if !alpha.is_finite() || !(0.0..=1.0).contains(&alpha) {
                            return Err("invalid XBF color alpha".into());
                        }
                    }
                    if value.pos != data.len() {
                        return Err("invalid XBF color payload length".into());
                    }
                    self.labels[index].color = Some(color);
                }
                "TDataStd_UAttribute"
                    if data.len() == 16
                        && u32::from_le_bytes(data[..4].try_into()?) == 0x6b89_6b01 =>
                {
                    self.labels[index].external = true;
                }
                _ if direct_end.is_some() => {
                    return Err(format!("unsupported direct XBF attribute {name}").into());
                }
                _ => {}
            }
            if let Some(end) = direct_end
                && cursor.pos != end
            {
                return Err("XBF inline geometry size mismatch".into());
            }
        }
        let mut tags = HashSet::new();
        loop {
            let tag = cursor.i32()?;
            if tag == -2 {
                break;
            }
            if tag <= 0 || !tags.insert(tag) {
                return Err("invalid or duplicate XBF child label tag".into());
            }
            let mut path = self.labels[index].path.clone();
            path.push(tag);
            self.label(cursor, tables, path, depth + 1)?;
        }
        if label_end.is_some_and(|end| cursor.pos != end) {
            return Err("XBF label size disagrees with its hierarchy".into());
        }
        Ok(())
    }

    /// Resolve a shape label or assembly reference to concrete native shapes.
    ///
    /// # Errors
    ///
    /// Label/tree references are missing, cyclic or exceed nesting limits.
    fn resolve(&self, index: usize, tables: &mut Tables, depth: usize) -> Result<Vec<ShapeRef>> {
        if depth > MAX_DEPTH {
            return Err("cyclic or overly deep XBF assembly reference".into());
        }
        let label = &self.labels[index];
        if label.external {
            return Err("XBF external shape references are unsupported".into());
        }
        if let Some(tree) = label.trees.get(&0x5b89_6afe).filter(|tree| tree.father > 0) {
            let parent = *self
                .attribute_labels
                .get(&tree.father)
                .ok_or("XBF assembly reference target does not exist")?;
            let target_tree = self.labels[parent]
                .trees
                .get(&0x5b89_6afe)
                .ok_or("XBF assembly reference does not target a shape tree")?;
            if target_tree.id != tree.father {
                return Err("XBF assembly link has the wrong attribute type".into());
            }
            let location = label
                .location
                .ok_or("XBF assembly reference has no placement")?;
            let transform = tables.location_transform(location)?;
            let mut shapes = self.resolve(parent, tables, depth + 1)?;
            for shape in &mut shapes {
                let transform = transform.then(tables.location_transform(shape.location)?);
                tables.locations.push(transform);
                shape.location = tables.locations.len();
            }
            Ok(shapes)
        } else {
            Ok(label.shapes.clone())
        }
    }

    /// Resolve a label's inherited diffuse color.
    ///
    /// # Errors
    ///
    /// The label/color-tree references are invalid or cyclic.
    fn diffuse(&self, index: usize) -> Result<Option<[u8; 3]>> {
        let label = &self.labels[index];
        for kind in [0xefd2_12e5, 0xefd2_12e4, 0xefd2_12e6] {
            if let Some(tree) = label.trees.get(&kind).filter(|tree| tree.father > 0) {
                let parent = *self
                    .attribute_labels
                    .get(&tree.father)
                    .ok_or("XBF color reference target does not exist")?;
                let target_tree = self.labels[parent]
                    .trees
                    .get(&kind)
                    .ok_or("XBF color reference has the wrong tree type")?;
                if target_tree.id != tree.father {
                    return Err("invalid XBF color reference attribute".into());
                }
                return self.labels[parent]
                    .color
                    .ok_or_else(|| "XBF color target has no RGB value".into())
                    .map(Some);
            }
        }
        Ok(None)
    }

    /// Render document roots with inherited color and native occurrence placements.
    ///
    /// # Errors
    ///
    /// Required shapes, roots, placements or CAD tessellation cannot produce a complete bounded scene.
    fn render(&self, tables: &mut Tables) -> Result<Scene> {
        let tools: Vec<_> = self
            .labels
            .iter()
            .filter(|label| label.shape_tool)
            .collect();
        if tools.len() != 1 {
            return Err("XBF document must have exactly one shape tool".into());
        }
        let base = &tools[0].path;
        let mut colors = HashMap::new();
        for (index, label) in self.labels.iter().enumerate() {
            if let Some(color) = self.diffuse(index)? {
                for shape in &label.shapes {
                    colors.insert(shape.node, color);
                }
            }
        }
        let mut faces = Vec::with_capacity(tables.shapes.len());
        for (index, shape) in tables.shapes.iter().enumerate() {
            let mut contains = shape.kind == 4;
            for child in &shape.children {
                if child.node >= index {
                    return Err("forward or cyclic XBF shape topology".into());
                }
                contains |= faces[child.node];
            }
            faces.push(contains);
        }
        let mut primitives = Vec::new();
        let mut occurrences = 0;
        for (index, label) in self.labels.iter().enumerate() {
            if label.path.len() != base.len() + 1 || !label.path.starts_with(base) {
                continue;
            }
            if label
                .trees
                .get(&0x5b89_6afe)
                .is_some_and(|tree| tree.first > 0)
            {
                continue;
            }
            let color = self.diffuse(index)?;
            for shape in self.resolve(index, tables, 0)? {
                collect_primitives(
                    tables,
                    shape,
                    Transform::IDENTITY,
                    color,
                    &colors,
                    &faces,
                    &mut primitives,
                    &mut occurrences,
                    0,
                )?;
            }
        }
        if primitives.is_empty() {
            return Err("XBF document has no free renderable shapes".into());
        }
        let text = tables.brep(&primitives)?;
        let (mut model, root) = ogeom_io::brep::read(&text, ogeom_core::Tolerances::millimetres())?;
        let children = model.children_of(&root)?;
        if children.len() != primitives.len() + tables.shapes.len() {
            return Err("XBF topology conversion omitted a primitive".into());
        }
        tables.restore_representation_locations(&mut model, &children[..tables.shapes.len()])?;
        let mut scene = Scene::default();
        for (shape, (_, _, color)) in children
            .into_iter()
            .skip(tables.shapes.len())
            .zip(primitives)
        {
            let first_triangle = scene.triangles.len();
            let first_point = scene.points.len();
            let first_line = scene.lines.len();
            super::cad::append_shape(&mut scene, &model, &shape)?;
            for triangle in &mut scene.triangles[first_triangle..] {
                triangle.color = color;
            }
            for point in &mut scene.points[first_point..] {
                point.color = color;
            }
            for line in &mut scene.lines[first_line..] {
                line.color = color;
            }
        }
        scene.validate()?;
        Ok(scene)
    }
}

/// Encode one clamped linear RGB component as an sRGB byte.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    reason = "Validated zero-to-one color factors are intentionally rounded to bounded RGB bytes."
)]
fn linear_color(value: f64) -> u8 {
    let value = if value <= 0.003_130_8 {
        value * 12.92
    } else {
        1.055 * value.powf(1.0 / 2.4) - 0.055
    };
    (value * 255.0).round().clamp(0.0, 255.0) as u8
}

/// A renderable native shape occurrence with world placement and inherited RGB color.
type Primitive = (ShapeRef, Transform, Option<[u8; 3]>);

/// Collect face, free-edge and vertex occurrences with their world placement and color.
///
/// # Errors
///
/// Shape/location references are invalid or occurrence, nesting or primitive limits are exceeded.
#[allow(
    clippy::too_many_arguments,
    reason = "The bounded shape walk carries distinct placement, color, ownership, and resource state through recursion."
)]
fn collect_primitives(
    tables: &Tables,
    reference: ShapeRef,
    parent: Transform,
    color: Option<[u8; 3]>,
    colors: &HashMap<usize, [u8; 3]>,
    faces: &[bool],
    output: &mut Vec<Primitive>,
    occurrences: &mut usize,
    depth: usize,
) -> Result<()> {
    *occurrences += 1;
    if *occurrences > MAX_RECORDS || depth > MAX_DEPTH {
        return Err("XBF instances exceed 100000 occurrences or 64 levels".into());
    }
    let shape = tables
        .shapes
        .get(reference.node)
        .ok_or("XBF shape index is out of range")?;
    let world = parent.then(tables.location_transform(reference.location)?);
    let color = colors.get(&reference.node).copied().or(color);
    if shape.kind == 4 || (shape.kind == 6 && !faces[reference.node]) || shape.kind == 7 {
        if output.len() >= 4096 {
            return Err("XBF exceeds 4096 preview primitives".into());
        }
        output.push((
            ShapeRef {
                location: 0,
                ..reference
            },
            world,
            color,
        ));
        return Ok(());
    }
    // Face boundaries and solid wire edges are already represented by their
    // faces. Wire-only documents retain their actual edge curves.
    let contains_faces = faces[reference.node];
    for child in &shape.children {
        if contains_faces && !faces[child.node] {
            continue;
        }
        collect_primitives(
            tables,
            *child,
            world,
            color,
            colors,
            faces,
            output,
            occurrences,
            depth + 1,
        )?;
    }
    Ok(())
}

impl Tables {
    /// The ASCII kernel reader preserves topology placements but resets
    /// edge/surface representation placements. Restore those exact native
    /// records through the public typed geometry API before tessellation.
    #[allow(
        clippy::too_many_lines,
        reason = "Keep the format record dispatch, validation and its resource checks together without changing geometry evaluation."
    )]
    fn restore_representation_locations(
        &self,
        model: &mut ogeom_topo::Model,
        nodes: &[ogeom_topo::Shape],
    ) -> Result<()> {
        use ogeom_geom::Transformable;
        let tolerance = ogeom_core::Tolerances::millimetres();
        let mut transforms = vec![ogeom_math::Transform::IDENTITY];
        for transform in &self.locations {
            let rows =
                std::array::from_fn(|row| std::array::from_fn(|column| transform.0[column][row]));
            let scale = ogeom_math::Matrix3::new(rows).determinant().cbrt();
            if !scale.is_finite() || scale == 0.0 {
                return Err("singular XBF geometry location".into());
            }
            let normalized =
                std::array::from_fn(|row| std::array::from_fn(|column| rows[row][column] / scale));
            transforms.push(ogeom_math::Transform::from_parts(
                ogeom_math::Matrix3::new(normalized),
                scale,
                ogeom_math::Vector::new(transform.0[3][0], transform.0[3][1], transform.0[3][2]),
                1e-9,
            )?);
        }
        // The tessellator evaluates carrier geometry in its stored coordinate
        // frame. Materialize each actual rigid carrier placement once and
        // share that transformed geometry between its face and pcurves.
        let mut surfaces = HashMap::new();
        let mut curves = HashMap::new();
        let placed_surface = |model: &mut ogeom_topo::Model,
                              surfaces: &mut HashMap<
            (ogeom_topo::SurfaceId, usize),
            ogeom_topo::SurfaceId,
        >,
                              id: ogeom_topo::SurfaceId,
                              index: usize|
         -> Result<ogeom_topo::SurfaceId> {
            let transform = transforms
                .get(index)
                .ok_or("invalid XBF surface location")?;
            if (transform.scale_factor().abs() - 1.0).abs() > 1e-9 {
                return Err("scaled XBF surface representation locations are unsupported".into());
            }
            if transform.kind() == ogeom_math::TransformKind::Identity {
                return Ok(id);
            }
            if let Some(placed) = surfaces.get(&(id, index)) {
                return Ok(*placed);
            }
            let surface = model
                .geometry()
                .surface(id)
                .ok_or("XBF carrier surface is missing")?
                .transformed(transform, tolerance)?;
            let placed = model.geometry_mut().add_surface(surface);
            surfaces.insert((id, index), placed);
            Ok(placed)
        };
        for (shape, node) in self.shapes.iter().zip(nodes) {
            let mut tokens = shape.geometry.split_whitespace();
            let mut data = model
                .node(node)
                .ok_or("converted XBF node is missing")?
                .data()
                .clone();
            match &mut data {
                ogeom_topo::NodeData::Face(face) => {
                    let index = tokens
                        .nth(3)
                        .ok_or("XBF face has no carrier placement")?
                        .parse::<usize>()?;
                    face.surface = placed_surface(model, &mut surfaces, face.surface, index)?;
                    face.location = ogeom_topo::Location::identity();
                }
                ogeom_topo::NodeData::Edge(edge) => {
                    for _ in 0..4 {
                        tokens.next().ok_or("truncated XBF edge geometry")?;
                    }
                    let mut index = 0;
                    loop {
                        let kind = tokens
                            .next()
                            .ok_or("truncated XBF edge representations")?
                            .parse::<u8>()?;
                        if kind == 0 {
                            break;
                        }
                        let (before, after) = match kind {
                            1 => (1, 2),
                            2 => (2, 2),
                            3 => (4, 2),
                            4 => {
                                for _ in 0..5 {
                                    tokens.next().ok_or("truncated XBF continuity")?;
                                }
                                continue;
                            }
                            _ => return Err("unsupported converted XBF edge representation".into()),
                        };
                        for _ in 0..before {
                            tokens.next().ok_or("truncated XBF edge placement")?;
                        }
                        let native_location = tokens
                            .next()
                            .ok_or("missing XBF edge placement")?
                            .parse::<usize>()?;
                        let transform = transforms
                            .get(native_location)
                            .ok_or("invalid XBF edge placement")?;
                        if (transform.scale_factor().abs() - 1.0).abs() > 1e-9 {
                            return Err(
                                "scaled XBF curve representation locations are unsupported".into(),
                            );
                        }
                        let representation = edge
                            .representations
                            .get_mut(index)
                            .ok_or("XBF conversion lost an edge representation")?;
                        match representation {
                            ogeom_topo::EdgeRepr::Curve3d {
                                curve, location, ..
                            } => {
                                if transform.kind() != ogeom_math::TransformKind::Identity {
                                    let key = (*curve, native_location);
                                    let placed = if let Some(id) = curves.get(&key) {
                                        *id
                                    } else {
                                        let geometry = model
                                            .geometry()
                                            .curve(*curve)
                                            .ok_or("XBF edge curve is missing")?
                                            .transformed(transform, tolerance)?;
                                        let id = model.geometry_mut().add_curve(geometry);
                                        curves.insert(key, id);
                                        id
                                    };
                                    *curve = placed;
                                }
                                *location = ogeom_topo::Location::identity();
                            }
                            ogeom_topo::EdgeRepr::PCurve {
                                surface, location, ..
                            }
                            | ogeom_topo::EdgeRepr::Seam {
                                surface, location, ..
                            } => {
                                *surface = placed_surface(
                                    model,
                                    &mut surfaces,
                                    *surface,
                                    native_location,
                                )?;
                                *location = ogeom_topo::Location::identity();
                            }
                            _ => return Err("XBF conversion changed an edge representation".into()),
                        }
                        index += 1;
                        for _ in 0..after {
                            tokens.next().ok_or("truncated XBF edge range")?;
                        }
                    }
                    if index != edge.representations.len() {
                        return Err("XBF conversion lost edge representations".into());
                    }
                    edge.assert_same_parameter(false);
                }
                _ => {}
            }
            *model
                .node_mut(node)
                .ok_or("converted XBF node is missing")?
                .data_mut() = data;
        }
        Ok(())
    }
    /// Serialize collected native topology and placements as ASCII BREP.
    ///
    /// # Errors
    ///
    /// Required topology references, geometry or formatting are invalid.
    fn brep(&mut self, primitives: &[Primitive]) -> Result<String> {
        let mut locations = self.locations.clone();
        let mut root_children = Vec::new();
        for (shape, world, _) in primitives {
            locations.push(*world);
            root_children.push(ShapeRef {
                location: locations.len(),
                ..*shape
            });
        }
        let mut out =
            String::from("DBRep_DrawableShape\n\nCASCADE Topology V1, (c) Matra-Datavision\n");
        writeln!(out, "Locations {}", locations.len())?;
        for location in locations {
            out.push_str("1\n");
            for row in 0..3 {
                for column in &location.0 {
                    write!(out, "{} ", column[row])?;
                }
                out.push('\n');
            }
        }
        writeln!(out, "Curve2ds {}", self.pcurves.len())?;
        for curve in &self.pcurves {
            writeln!(out, "{curve}")?;
        }
        writeln!(out, "Curves {}", self.curves.len())?;
        for curve in &self.curves {
            writeln!(out, "{curve}")?;
        }
        out.push_str("Polygon3D 0\nPolygonOnTriangulations 0\n");
        writeln!(out, "Surfaces {}", self.surfaces.len())?;
        for surface in &self.surfaces {
            writeln!(out, "{surface}")?;
        }
        out.push_str("Triangulations 0\n");
        let total = self.shapes.len() + 1;
        writeln!(out, "TShapes {total}")?;
        for shape in &self.shapes {
            writeln!(out, "{}\n{}", shape_name(shape.kind)?, shape.geometry)?;
            for bit in 0..7 {
                write!(out, "{}", (shape.flags >> bit) & 1)?;
            }
            out.push('\n');
            for child in &shape.children {
                write_reference(&mut out, *child, total)?;
            }
            out.push_str("*\n");
            if out.len() > MAX_BYTES {
                return Err("converted XBF topology exceeds 16 MiB".into());
            }
        }
        out.push_str("Co\n0001000\n");
        // Native-node references make the BREP conversion's identities
        // explicit, allowing representation placements to be restored
        // without relying on kernel arena allocation or iteration order.
        for node in 0..self.shapes.len() {
            write_reference(
                &mut out,
                ShapeRef {
                    node,
                    location: 0,
                    orientation: 0,
                },
                total,
            )?;
        }
        for child in root_children {
            write_reference(&mut out, child, total)?;
        }
        out.push_str("*\n+1 0\n");
        if out.len() > MAX_BYTES {
            return Err("converted XBF topology exceeds 16 MiB".into());
        }
        Ok(out)
    }
}
/// Resolve a native topology kind to its ASCII BREP name.
///
/// # Errors
///
/// The topology kind is outside the supported enumeration.
fn shape_name(kind: u8) -> Result<&'static str> {
    ["Co", "CS", "So", "Sh", "Fa", "Wi", "Ed", "Ve"]
        .get(usize::from(kind))
        .copied()
        .ok_or_else(|| "unsupported XBF shape type".into())
}
/// Write a native shape occurrence in ASCII BREP reference syntax.
///
/// # Errors
///
/// The referenced shape index is invalid or formatting fails.
fn write_reference(out: &mut String, shape: ShapeRef, total: usize) -> Result<()> {
    let orientation = ["+", "-", "i", "e"]
        .get(usize::from(shape.orientation))
        .ok_or("invalid XBF shape orientation")?;
    let number = total
        .checked_sub(shape.node)
        .ok_or("invalid XBF shape index")?;
    write!(out, "{orientation}{number} {} ", shape.location)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    fn integer(out: &mut Vec<u8>, value: i32) {
        out.extend(value.to_le_bytes());
    }
    fn real(out: &mut Vec<u8>, value: f64) {
        out.extend(value.to_le_bytes());
    }
    fn reals(out: &mut Vec<u8>, values: &[f64]) {
        for value in values {
            real(out, *value);
        }
    }
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "Small authored test payload lengths fit their native field widths; preserve the exact binary fixture encoding."
    )]
    fn string(out: &mut Vec<u8>, value: &str) {
        integer(out, value.len() as i32);
        out.extend(value.as_bytes());
    }
    fn transform(out: &mut Vec<u8>, value: Transform) {
        out.push(6);
        for row in 0..3 {
            for column in &value.0 {
                real(out, column[row]);
            }
        }
    }
    #[allow(
        clippy::cast_possible_truncation,
        reason = "Small authored test payload lengths fit their native field widths; preserve the exact binary fixture encoding."
    )]
    fn reference(out: &mut Vec<u8>, offset: usize) {
        let delta = out.len() - offset;
        out.push(3);
        out.extend((delta as u32).to_le_bytes());
    }
    fn vertex(out: &mut Vec<u8>, point: Vec3, orientation: u8) {
        out.extend([228 + orientation, 7]);
        reals(out, &[1e-7, point.x, point.y, point.z]);
        out.extend([0, 8, 199]);
    }
    fn triangle(carrier: Transform, root: Transform) -> Vec<u8> {
        let mut out = vec![200];
        transform(&mut out, root);
        out.push(8);
        out.extend([216, 7, 0]);
        real(&mut out, 1e-7);
        let surface = out.len();
        out.extend([13, 1]);
        reals(&mut out, &[0., 0., 0., 0., 0., 1., 1., 0., 0., 0., 1., 0.]);
        let placement = out.len();
        transform(&mut out, carrier);
        out.extend([0, 8, 220, 7, 8]);
        let points = [
            Vec3::new(0., 0., 0.),
            Vec3::new(2., 0., 0.),
            Vec3::new(0., 1., 0.),
        ];
        for edge in 0..3 {
            let start = points[edge];
            let end = points[(edge + 1) % 3];
            let delta = end - start;
            let length = delta.length();
            let direction = delta / length;
            out.extend([224, 7]);
            real(&mut out, 1e-7);
            out.extend([3, 1, 9, 1]);
            reals(
                &mut out,
                &[start.x, start.y, 0., direction.x, direction.y, 0.],
            );
            reference(&mut out, placement);
            reals(&mut out, &[0., length]);
            out.extend([2, 11, 1]);
            reals(&mut out, &[start.x, start.y, direction.x, direction.y]);
            reference(&mut out, surface);
            reference(&mut out, placement);
            reals(&mut out, &[0., length]);
            out.extend([0, 8]);
            vertex(&mut out, carrier.apply(start), 0);
            vertex(&mut out, carrier.apply(end), 1);
            out.push(199);
        }
        out.extend([199, 199, 199]);
        out
    }
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "Small authored test payload lengths fit their native field widths; preserve the exact binary fixture encoding."
    )]
    fn attribute(kind: i32, id: i32, data: Vec<u8>, direct: Option<Vec<u8>>) -> Vec<u8> {
        let mut out = Vec::new();
        integer(&mut out, kind);
        integer(&mut out, id);
        integer(&mut out, data.len() as i32);
        out.extend(data);
        if let Some(data) = direct {
            out.extend(((data.len() + 8) as u64).to_le_bytes());
            out.extend(data);
        }
        out
    }
    fn tree(id: i32, father: i32, first: i32) -> Vec<u8> {
        let mut data = Vec::new();
        for value in [father, -1, -1, first] {
            integer(&mut data, value);
        }
        data.extend(0xefd2_12e4u32.to_le_bytes());
        data.extend([
            0xfd, 0x6d, 0xd4, 0x11, 0xb9, 0xc8, 0, 0x60, 0xb0, 0xee, 0x28, 0x1b,
        ]);
        attribute(3, id, data, None)
    }
    fn label(attributes: Vec<Vec<u8>>, children: Vec<(i32, Vec<u8>)>, quick: bool) -> Vec<u8> {
        let mut out = if quick { vec![0; 8] } else { Vec::new() };
        for attr in attributes {
            out.extend(attr);
        }
        integer(&mut out, -1);
        for (tag, child) in children {
            integer(&mut out, tag);
            out.extend(child);
        }
        integer(&mut out, -2);
        if quick {
            let size = out.len() as u64;
            out[..8].copy_from_slice(&size.to_le_bytes());
        }
        out
    }
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "Small authored test payload lengths fit their native field widths; preserve the exact binary fixture encoding."
    )]
    #[allow(
        clippy::too_many_lines,
        reason = "Keep the format record dispatch, validation and its resource checks together without changing geometry evaluation."
    )]
    fn document(geometry: Vec<u8>, version: u32) -> Vec<u8> {
        let quick = version == 12;
        let mut named = Vec::new();
        integer(&mut named, 1);
        integer(&mut named, 1);
        named.push(b'P');
        let direct = if quick {
            Some(geometry.clone())
        } else {
            named.extend([0, 0, 0]);
            integer(&mut named, 3);
            integer(&mut named, 0);
            named.push(b'F');
            None
        };
        let shape = label(
            vec![
                attribute(1, if quick { -2 } else { 2 }, named, direct),
                tree(3, 4, -1),
            ],
            vec![],
            quick,
        );
        let mut color = Vec::new();
        reals(&mut color, &[0.25, 0.5, 1.0]);
        let color = label(
            vec![tree(4, -1, 3), attribute(4, 5, color, None)],
            vec![],
            quick,
        );
        let body = label(
            vec![],
            vec![(
                1,
                label(
                    vec![],
                    vec![
                        (
                            1,
                            label(vec![attribute(2, 1, vec![], None)], vec![(1, shape)], quick),
                        ),
                        (2, label(vec![], vec![(1, color)], quick)),
                    ],
                    quick,
                ),
            )],
            quick,
        );
        let mut out = b"BINFILE".to_vec();
        out.resize(59, 0);
        integer(&mut out, 1);
        string(&mut out, &version.to_string());
        for _ in 0..3 {
            string(&mut out, "");
        }
        integer(&mut out, 0);
        string(&mut out, "");
        integer(&mut out, 0);
        let info = [
            "FILE_FORMAT: BinXCAF",
            "START_TYPES",
            "TNaming_NamedShape",
            "XCAFDoc_ShapeTool",
            "TDataStd_TreeNode",
            "XCAFDoc_Color",
            "END_TYPES",
        ];
        integer(&mut out, info.len() as i32);
        for item in info {
            string(&mut out, item);
        }
        let end_info = out.len() as i32;
        integer(&mut out, 0);
        let start_doc = out.len() as i32;
        let header = [
            0x0403_0201,
            7,
            end_info,
            end_info,
            start_doc,
            -1,
            -1,
            -1,
            -1,
            -1,
            -1,
            start_doc,
            start_doc,
        ];
        for (index, value) in header.iter().enumerate() {
            out[7 + index * 4..11 + index * 4].copy_from_slice(&value.to_le_bytes());
        }
        if quick {
            integer(&mut out, 4);
            out.extend(b":\0\0\0");
            out.extend([0; 24]);
        } else {
            integer(&mut out, 20);
            out.extend(b"SHAPE_SECTION_POS:\0\0");
            let offset = out.len() + 24 + 4 + body.len();
            out.extend((offset as u64).to_le_bytes());
            out.extend((geometry.len() as u64).to_le_bytes());
            out.extend(0u64.to_le_bytes());
        }
        integer(&mut out, 0);
        out.extend(body);
        if !quick {
            out.extend(geometry);
        }
        out
    }
    fn bounds(scene: &Scene) -> (Vec3, Vec3) {
        let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
        let mut high = -low;
        for p in scene
            .triangles
            .iter()
            .flat_map(|t| t.vertices)
            .chain(scene.points.iter().map(|p| p.position))
            .chain(scene.lines.iter().flat_map(|l| l.vertices))
        {
            low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
            high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
        }
        (low, high)
    }
    fn close(actual: Vec3, expected: Vec3) {
        assert!(
            (actual - expected).length() < 1e-6,
            "{actual:?} differs from {expected:?}"
        );
    }
    #[test]
    fn modern_native_topology_has_actual_area_placement_color_and_thumbnail() {
        let root = Transform([
            [0., 1., 0., 0.],
            [-1., 0., 0., 0.],
            [0., 0., 1., 0.],
            [10., -2., 3., 1.],
        ]);
        let scene = parse(&document(triangle(Transform::IDENTITY, root), 12)).unwrap();
        let (low, high) = bounds(&scene);
        close(low, Vec3::new(9., -2., 3.));
        close(high, Vec3::new(10., 0., 3.));
        let area: f64 = scene
            .triangles
            .iter()
            .map(|t| {
                (t.vertices[1] - t.vertices[0])
                    .cross(t.vertices[2] - t.vertices[0])
                    .length()
                    * 0.5
            })
            .sum();
        assert!((area - 1.).abs() < 1e-6);
        assert!(
            scene
                .triangles
                .iter()
                .all(|t| t.color == Some([137, 188, 255]))
        );
        let options = crate::render::RenderOptions {
            width: 96,
            height: 64,
            transparent: true,
            ..Default::default()
        };
        let image = crate::render::render(&scene, &options).unwrap();
        assert!(image.pixels().filter(|p| p[3] > 0).count() > 100);
    }
    #[test]
    fn carrier_locations_are_applied_to_surfaces_and_edge_representations() {
        let carrier = Transform([
            [1., 0., 0., 0.],
            [0., 1., 0., 0.],
            [0., 0., 1., 0.],
            [7., 5., 2., 1.],
        ]);
        let scene = parse(&document(triangle(carrier, Transform::IDENTITY), 12)).unwrap();
        let (low, high) = bounds(&scene);
        close(low, Vec3::new(7., 5., 2.));
        close(high, Vec3::new(9., 6., 2.));
        assert!(!scene.triangles.is_empty());
    }
    #[test]
    fn mirrored_carriers_and_scaled_instances_keep_geometry() {
        let mirrored = Transform([
            [-1., 0., 0., 0.],
            [0., 1., 0., 0.],
            [0., 0., 1., 0.],
            [7., 5., 2., 1.],
        ]);
        let scene = parse(&document(triangle(mirrored, Transform::IDENTITY), 12)).unwrap();
        let (low, high) = bounds(&scene);
        close(low, Vec3::new(5., 5., 2.));
        close(high, Vec3::new(7., 6., 2.));
        let scale = Transform([
            [2., 0., 0., 0.],
            [0., 2., 0., 0.],
            [0., 0., 2., 0.],
            [0., 0., 0., 1.],
        ]);
        let scene = parse(&document(triangle(Transform::IDENTITY, scale), 12)).unwrap();
        let (low, high) = bounds(&scene);
        close(low, Vec3::default());
        close(high, Vec3::new(4., 2., 0.));
        let area: f64 = scene
            .triangles
            .iter()
            .map(|t| {
                (t.vertices[1] - t.vertices[0])
                    .cross(t.vertices[2] - t.vertices[0])
                    .length()
                    * 0.5
            })
            .sum();
        assert!((area - 4.).abs() < 1e-6);
        let error = parse(&document(triangle(scale, Transform::IDENTITY), 12))
            .unwrap_err()
            .to_string();
        assert!(error.contains("scaled XBF"));
    }
    #[test]
    fn legacy_table_archive_uses_document_roots_and_real_vertex_geometry() {
        let mut archive=b"SHAPE_SECTION\nOpen CASCADE Topology V3 (c)\nLocations 0\nCurve2ds 0\nCurves 0\nPolygon3D 0\nPolygonOnTriangulations 0\nSurfaces 0\nTriangulations 0\nTShapes 3\n".to_vec();
        for point in [[1., 2., 3.], [4., 5., 6.]] {
            archive.push(7);
            real(&mut archive, 1e-7);
            reals(&mut archive, &point);
            archive.extend([0, 0, 0, 0, 1, 0, 0, 0, b'*']);
        }
        archive.push(0);
        archive.extend([0, 0, 0, 1, 0, 0, 0]);
        for index in [3, 2] {
            archive.push(0);
            integer(&mut archive, index);
            integer(&mut archive, 0);
        }
        archive.push(b'*');
        let scene = parse(&document(archive, 10)).unwrap();
        assert_eq!(scene.points.len(), 2);
        let (low, high) = bounds(&scene);
        close(low, Vec3::new(1., 2., 3.));
        close(high, Vec3::new(4., 5., 6.));
        assert!(
            scene
                .points
                .iter()
                .all(|p| p.color == Some([137, 188, 255]))
        );
    }
    #[test]
    fn composed_locations_preserve_order_negative_powers_and_mirroring() {
        let translation = Transform([
            [1., 0., 0., 0.],
            [0., 1., 0., 0.],
            [0., 0., 1., 0.],
            [4., -2., 3., 1.],
        ]);
        let mirror = Transform([
            [-1., 0., 0., 0.],
            [0., 1., 0., 0.],
            [0., 0., 1., 0.],
            [0., 0., 0., 1.],
        ]);
        close(
            power(translation, -1)
                .unwrap()
                .apply(Vec3::new(4., -2., 3.)),
            Vec3::default(),
        );
        let mut bytes = vec![5];
        transform(&mut bytes, translation);
        integer(&mut bytes, 1);
        transform(&mut bytes, mirror);
        integer(&mut bytes, 1);
        bytes.push(8);
        let mut tables = Tables::default();
        let location = tables.location(&mut Cursor::new(&bytes), 0).unwrap();
        close(
            tables
                .location_transform(location)
                .unwrap()
                .apply(Vec3::new(1., 2., 3.)),
            Vec3::new(-5., 0., 6.),
        );
        assert!(power(translation, i32::MIN).is_err());
    }
    #[test]
    fn malformed_binary_documents_and_geometry_fail_without_panics() {
        let valid = document(triangle(Transform::IDENTITY, Transform::IDENTITY), 12);
        for size in [0, 7, 12, 58, 100, valid.len() / 2, valid.len() - 1] {
            assert!(parse(&valid[..size]).is_err());
        }
        let mut bad = valid.clone();
        bad[7] = 4;
        assert!(parse(&bad).is_err());
        let mut bad = valid;
        bad[55..59].copy_from_slice(&i32::MAX.to_le_bytes());
        assert!(parse(&bad).is_err());
        let mut tables = Tables::default();
        assert!(tables.shape(&mut Cursor::new(&[1, 1, 7, 0]), 0).is_err());
        assert!(tables.geometry(&mut Cursor::new(&[10]), 9).is_err());
        let mut values = vec![1];
        real(&mut values, f64::NAN);
        assert!(curve(&mut Cursor::new(&values), 3, 0).is_err());
        let mut values = vec![7, 0, 0];
        values.extend(65u16.to_le_bytes());
        assert!(curve(&mut Cursor::new(&values), 3, 0).is_err());
    }
}