catwalk3d 2.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
//! Static IFC Part 21 geometry and product placements, independent of native BIM kernels.
/// Bounded Boolean geometry for supported IFC solids.
#[path = "ifc_csg.rs"]
mod csg;
use super::transform::Transform;
use crate::scene::{Line, Point, Scene, Triangle, Vec3};
use crate::{Error, Result};
use ruststep::ast::{EntityInstance, Name, Parameter};
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::f64::consts::{PI, TAU};
use std::path::Path;
use truck_stepio::r#in::ruststep;

/// Maximum parsed schema entity count.
const MAX_ENTITIES: usize = 500_000;
/// Maximum geometry items or charged geometry visits.
const MAX_GEOMETRY: usize = 5_000_000;
/// Maximum recursive reference, geometry or partition depth.
const MAX_DEPTH: usize = 64;
/// Fixed sampling resolution for supported analytic profile curves.
const CURVE_SEGMENTS: usize = 96;
/// Construct an importer error with the supplied IFC diagnostic.
fn error(message: impl Into<String>) -> Error {
    message.into().into()
}
/// Require an IFC parameter-list value.
///
/// # Errors
///
/// The parameter is not a list.
fn list(p: &Parameter) -> Result<&[Parameter]> {
    if let Parameter::List(v) = p {
        Ok(v)
    } else {
        Err(error("IFC parameter requires a list"))
    }
}
/// Require an IFC numeric entity reference.
///
/// # Errors
///
/// The parameter is not an entity reference.
fn reference(p: &Parameter) -> Result<u64> {
    if let Parameter::Ref(Name::Entity(id)) = p {
        Ok(*id)
    } else {
        Err(error("IFC parameter requires an entity reference"))
    }
}
/// Decode an optional entity reference, treating omitted values as absent.
///
/// # Errors
///
/// A present parameter is not an entity reference.
fn optional_reference(p: &Parameter) -> Result<Option<u64>> {
    if matches!(p, Parameter::NotProvided | Parameter::Omitted) {
        Ok(None)
    } else {
        reference(p).map(Some)
    }
}
/// Read a finite IFC integer, real or typed numeric parameter.
///
/// # Errors
///
/// The parameter is nonnumeric or non-finite.
#[allow(
    clippy::cast_precision_loss,
    reason = "IFC integer dimensions intentionally use the geometry kernel's f64 representation, matching real parameters."
)]
fn number(p: &Parameter) -> Result<f64> {
    let n = match p {
        Parameter::Real(n) => *n,
        Parameter::Integer(n) => *n as f64,
        Parameter::Typed { parameter, .. } => return number(parameter),
        _ => return Err(error("IFC parameter requires a finite number")),
    };
    if n.is_finite() {
        Ok(n)
    } else {
        Err(error("non-finite IFC number"))
    }
}
/// Require a finite positive IFC dimension.
///
/// # Errors
///
/// The parameter is nonnumeric, non-finite or nonpositive.
fn positive(p: &Parameter) -> Result<f64> {
    let n = number(p)?;
    if n > 0. {
        Ok(n)
    } else {
        Err(error("IFC dimension must be positive"))
    }
}
/// Read a nonnegative machine-sized IFC integer.
///
/// # Errors
///
/// The parameter is not an integer or cannot represent a nonnegative machine-sized value.
fn integer(p: &Parameter) -> Result<usize> {
    if let Parameter::Integer(n) = p {
        usize::try_from(*n).map_err(Into::into)
    } else {
        Err(error("IFC index requires an integer"))
    }
}
/// Borrow an IFC string or enumeration spelling when present.
fn text(p: &Parameter) -> Option<&str> {
    match p {
        Parameter::String(s) | Parameter::Enumeration(s) => Some(s),
        _ => None,
    }
}
/// Decode an IFC logical true/false enumeration.
///
/// # Errors
///
/// The parameter is not a supported boolean spelling.
fn boolean(p: &Parameter) -> Result<bool> {
    match text(p) {
        Some("T" | "TRUE") => Ok(true),
        Some("F" | "FALSE") => Ok(false),
        _ => Err(error("IFC parameter requires a boolean")),
    }
}
/// Read a positional IFC entity attribute.
///
/// # Errors
///
/// The entity's attribute list is truncated.
fn field(e: &Entity, i: usize) -> Result<&Parameter> {
    e.fields
        .get(i)
        .ok_or_else(|| error(format!("truncated IFC {} attribute list", e.kind)))
}
/// Decode a list of IFC entity references.
///
/// # Errors
///
/// The parameter is not a list or a member is not an entity reference.
fn refs(p: &Parameter) -> Result<Vec<u64>> {
    list(p)?.iter().map(reference).collect()
}
/// Read finite two- or three-dimensional IFC coordinates, defaulting absent Z to zero.
///
/// # Errors
///
/// Dimensionality or numeric components are invalid.
fn vector(p: &Parameter) -> Result<Vec3> {
    let values = list(p)?;
    if !(2..=3).contains(&values.len()) {
        return Err(error("IFC coordinate needs 2 or 3 components"));
    }
    Ok(Vec3::new(
        number(&values[0])?,
        number(&values[1])?,
        values.get(2).map(number).transpose()?.unwrap_or(0.),
    ))
}
/// Normalize a finite direction above the numerical length floor.
///
/// # Errors
///
/// The vector has non-finite or near-zero length.
fn normalized(v: Vec3) -> Result<Vec3> {
    let length = v.length();
    if !length.is_finite() || length <= 1e-15 {
        return Err(error("invalid IFC direction"));
    }
    Ok(v / length)
}
/// Build an orthogonal placement frame from its origin and Z/X directions.
///
/// # Errors
///
/// The axes cannot define a finite nondegenerate orthogonal frame.
fn basis(origin: Vec3, z: Vec3, x: Vec3) -> Result<Transform> {
    let z = normalized(z)?;
    let x = normalized(x - z * x.dot(z))?;
    let y = z.cross(x);
    Ok(Transform([
        [x.x, x.y, x.z, 0.],
        [y.x, y.y, y.z, 0.],
        [z.x, z.y, z.z, 0.],
        [origin.x, origin.y, origin.z, 1.],
    ]))
}
/// Extract the three spatial components of a placement column.
fn column(t: Transform, i: usize) -> Vec3 {
    Vec3::new(t.0[i][0], t.0[i][1], t.0[i][2])
}
/// Compute the placement's spatial determinant to detect orientation reversal.
fn determinant(t: Transform) -> f64 {
    column(t, 0).dot(column(t, 1).cross(column(t, 2)))
}
/// Remove a repeated closing vertex and validate a polygon ring.
///
/// # Errors
///
/// The remaining ring has too few vertices or non-finite coordinates.
fn checked_ring(mut ring: Vec<Vec3>) -> Result<Vec<Vec3>> {
    if ring.first() == ring.last() {
        ring.pop();
    }
    if ring.len() < 3 || ring.len() > MAX_GEOMETRY || ring.iter().any(|p| !p.is_finite()) {
        return Err(error("IFC polygon requires at least three finite vertices"));
    }
    Ok(ring)
}
/// Compute a planar profile ring's signed XY area.
fn signed_area(ring: &[Vec3]) -> f64 {
    (0..ring.len())
        .map(|i| {
            let a = ring[i];
            let b = ring[(i + 1) % ring.len()];
            a.x * b.y - b.x * a.y
        })
        .sum::<f64>()
        / 2.
}
/// Triangulate coplanar polygon boundaries with holes.
///
/// # Errors
///
/// Boundaries are malformed, nonplanar or cannot be triangulated consistently.
fn triangles(rings: &[Vec<Vec3>]) -> Result<Vec<[Vec3; 3]>> {
    super::citygml::triangulate_rings(rings)
        .map_err(|e| error(format!("IFC face triangulation: {e}")))
}
/// One IFC schema record and its positional Part 21 attributes.
struct Entity {
    /// Native schema or topology kind selecting the record interpretation.
    kind: String,
    /// Positional Part 21 parameter values for the schema record.
    fields: Vec<Parameter>,
}
/// Indexed IFC entities, presentation colors, units and shared geometry-work budget.
struct Model {
    /// IFC schema records indexed by numeric entity identifier.
    entities: HashMap<u64, Entity>,
    /// Diffuse RGB colors indexed by the associated geometry item.
    colors: HashMap<u64, [u8; 3]>,
    /// Indexed per-face diffuse RGB colors for tessellated geometry.
    face_colors: HashMap<u64, Vec<[u8; 3]>>,
    /// Project length-unit scale used to normalize scene coordinates.
    length_scale: f64,
    /// Project angle-unit scale used to convert authored angles to radians.
    angle_scale: f64,
    /// Interior-mutable reference/geometry visit count shared by model expansion.
    visits: Cell<usize>,
}
impl Model {
    /// Charge one geometry/reference visit against the shared preview work limit.
    ///
    /// # Errors
    ///
    /// The visit count exceeds the work budget.
    fn visit(&self) -> Result<()> {
        let visits = self.visits.get() + 1;
        if visits > MAX_GEOMETRY {
            return Err(error("IFC reference traversal exceeds its work limit"));
        }
        self.visits.set(visits);
        Ok(())
    }
    /// Resolve an IFC entity by its identifier.
    ///
    /// # Errors
    ///
    /// The referenced entity is missing.
    fn entity(&self, id: u64) -> Result<&Entity> {
        self.entities
            .get(&id)
            .ok_or_else(|| error(format!("missing IFC entity #{id}")))
    }
    /// Resolve an IFC entity of the required schema kind.
    ///
    /// # Errors
    ///
    /// The entity is missing or has another schema kind.
    fn expected(&self, id: u64, kind: &str) -> Result<&Entity> {
        let e = self.entity(id)?;
        if e.kind == kind {
            Ok(e)
        } else {
            Err(error(format!(
                "IFC #{id} requires {kind}, found {}",
                e.kind
            )))
        }
    }
    /// Resolve an IFC Cartesian point to finite coordinates.
    ///
    /// # Errors
    ///
    /// The entity kind or coordinate tuple is invalid.
    fn point(&self, id: u64) -> Result<Vec3> {
        vector(field(self.expected(id, "IFCCARTESIANPOINT")?, 0)?)
    }
    /// Resolve an IFC direction to finite components.
    ///
    /// # Errors
    ///
    /// The entity kind or direction tuple is invalid.
    fn direction(&self, id: u64) -> Result<Vec3> {
        normalized(vector(field(self.expected(id, "IFCDIRECTION")?, 0)?)?)
    }
    /// Resolve an optional IFC direction or use its supplied default.
    ///
    /// # Errors
    ///
    /// A present direction reference or its tuple is invalid.
    fn optional_direction(&self, p: &Parameter, default: Vec3) -> Result<Vec3> {
        optional_reference(p)?
            .map(|id| self.direction(id))
            .transpose()
            .map(|v| v.unwrap_or(default))
    }
    /// Resolve an optional two- or three-dimensional IFC axis placement.
    ///
    /// # Errors
    ///
    /// Placement entities or axis directions are missing, unsupported or invalid.
    fn axis(&self, id: Option<u64>) -> Result<Transform> {
        let Some(id) = id else {
            return Ok(Transform::IDENTITY);
        };
        let e = self.entity(id)?;
        let origin = self.point(reference(field(e, 0)?)?)?;
        match e.kind.as_str() {
            "IFCAXIS2PLACEMENT3D" => {
                let z = self.optional_direction(field(e, 1)?, Vec3::new(0., 0., 1.))?;
                let default = if z.x.abs() > 0.999_999 {
                    Vec3::new(0., 1., 0.)
                } else {
                    Vec3::new(1., 0., 0.)
                };
                basis(origin, z, self.optional_direction(field(e, 2)?, default)?)
            }
            "IFCAXIS2PLACEMENT2D" => {
                let x = self.optional_direction(field(e, 1)?, Vec3::new(1., 0., 0.))?;
                if x.z.abs() > 1e-12 {
                    return Err(error("IFC 2D placement direction is not 2D"));
                }
                basis(origin, Vec3::new(0., 0., 1.), x)
            }
            "IFCAXIS1PLACEMENT" => {
                let z = self.optional_direction(field(e, 1)?, Vec3::new(0., 0., 1.))?;
                basis(
                    origin,
                    z,
                    if z.x.abs() > 0.999_999 {
                        Vec3::new(0., 1., 0.)
                    } else {
                        Vec3::new(1., 0., 0.)
                    },
                )
            }
            _ => Err(error(format!("unsupported IFC axis placement {}", e.kind))),
        }
    }
    /// Compose nested local product placements into a world transform.
    ///
    /// # Errors
    ///
    /// Placement references are invalid or recursive nesting exceeds the limit.
    fn placement(&self, id: Option<u64>, depth: usize) -> Result<Transform> {
        self.visit()?;
        if depth > MAX_DEPTH {
            return Err(error("IFC placement chain is cyclic or too deep"));
        }
        let Some(id) = id else {
            return Ok(Transform::IDENTITY);
        };
        let e = self.expected(id, "IFCLOCALPLACEMENT")?;
        Ok(self
            .placement(optional_reference(field(e, 0)?)?, depth + 1)?
            .then(self.axis(Some(reference(field(e, 1)?)?))?))
    }
    /// Resolve a supported Cartesian transformation operator, including nonuniform scale.
    ///
    /// # Errors
    ///
    /// Axes, scale values, entity kinds or transform numbers are invalid or unsupported.
    fn operator(&self, id: u64) -> Result<Transform> {
        let e = self.entity(id)?;
        if !matches!(
            e.kind.as_str(),
            "IFCCARTESIANTRANSFORMATIONOPERATOR3D"
                | "IFCCARTESIANTRANSFORMATIONOPERATOR3DNONUNIFORM"
                | "IFCCARTESIANTRANSFORMATIONOPERATOR2D"
                | "IFCCARTESIANTRANSFORMATIONOPERATOR2DNONUNIFORM"
        ) {
            return Err(error(format!(
                "unsupported IFC mapping operator {}",
                e.kind
            )));
        }
        let is_3d = e.kind.contains("3D");
        let z = if is_3d {
            self.optional_direction(field(e, 4)?, Vec3::new(0., 0., 1.))?
        } else {
            Vec3::new(0., 0., 1.)
        };
        let default = if z.x.abs() > 0.999_999 {
            Vec3::new(0., 1., 0.)
        } else {
            Vec3::new(1., 0., 0.)
        };
        let x = self.optional_direction(field(e, 0)?, default)?;
        let mut matrix = basis(self.point(reference(field(e, 2)?)?)?, z, x)?;
        if let Some(y) = optional_reference(field(e, 1)?)?
            && self.direction(y)?.dot(column(matrix, 1)) < 0.
        {
            for n in &mut matrix.0[1][..3] {
                *n = -*n;
            }
        }
        let default_scale = if matches!(field(e, 3)?, Parameter::NotProvided) {
            1.
        } else {
            positive(field(e, 3)?)?
        };
        let mut scales = [default_scale; 3];
        if e.kind.ends_with("NONUNIFORM") {
            for (axis, i) in [(1, if is_3d { 5 } else { 4 }), (2, 6)] {
                if axis == 2 && !is_3d {
                    continue;
                }
                if !matches!(field(e, i)?, Parameter::NotProvided) {
                    scales[axis] = positive(field(e, i)?)?;
                }
            }
        }
        if !is_3d {
            scales[2] = 1.;
        }
        for (axis, scale) in scales.into_iter().enumerate() {
            for n in &mut matrix.0[axis][..3] {
                *n *= scale;
            }
        }
        Ok(matrix)
    }
    /// Resolve a finite 2D/3D IFC point-list entity.
    ///
    /// # Errors
    ///
    /// The point-list kind, dimensions, count or coordinate values are invalid.
    fn coordinates(&self, id: u64) -> Result<Vec<Vec3>> {
        let e = self.entity(id)?;
        if !matches!(
            e.kind.as_str(),
            "IFCCARTESIANPOINTLIST3D" | "IFCCARTESIANPOINTLIST2D"
        ) {
            return Err(error("IFC tessellation requires a Cartesian point list"));
        }
        let values = list(field(e, 0)?)?;
        if values.len() > MAX_GEOMETRY {
            return Err(error("IFC coordinate count exceeds limit"));
        }
        values.iter().map(vector).collect()
    }
    /// Sample supported profile curves in their authored placements.
    ///
    /// # Errors
    ///
    /// Curve types/references, numeric data or recursion/geometry budgets are invalid or unsupported.
    #[allow(
        clippy::cast_precision_loss,
        reason = "Validated dimensions and bounded subdivision indices intentionally retain existing f64 evaluation and rounding."
    )]
    fn curve(&self, id: u64, depth: usize) -> Result<Vec<Vec3>> {
        self.visit()?;
        if depth > MAX_DEPTH {
            return Err(error("IFC curve references are cyclic or too deep"));
        }
        let e = self.entity(id)?;
        match e.kind.as_str() {
            "IFCPOLYLINE" | "IFCPOLYLOOP" => refs(field(e, 0)?)?
                .into_iter()
                .map(|id| self.point(id))
                .collect(),
            "IFCINDEXEDPOLYCURVE" => {
                let points = self.coordinates(reference(field(e, 0)?)?)?;
                if matches!(field(e, 1)?, Parameter::NotProvided) {
                    return Ok(points);
                }
                let mut result = Vec::new();
                for segment in list(field(e, 1)?)? {
                    let Parameter::Typed { keyword, parameter } = segment else {
                        return Err(error("invalid IFC indexed curve segment"));
                    };
                    let indices = list(parameter)?;
                    let get = |p: &Parameter| -> Result<Vec3> {
                        let index = integer(p)?
                            .checked_sub(1)
                            .ok_or_else(|| error("IFC indices are one-based"))?;
                        points
                            .get(index)
                            .copied()
                            .ok_or_else(|| error("IFC curve index out of bounds"))
                    };
                    let path = match keyword.as_str() {
                        "IFCLINEINDEX" if indices.len() >= 2 => {
                            indices.iter().map(get).collect::<Result<Vec<_>>>()?
                        }
                        "IFCARCINDEX" if indices.len() == 3 => {
                            arc(get(&indices[0])?, get(&indices[1])?, get(&indices[2])?)?
                        }
                        _ => return Err(error("unsupported IFC indexed curve segment")),
                    };
                    append_path(&mut result, path)?;
                }
                Ok(result)
            }
            "IFCCOMPOSITECURVE" => {
                let mut result = Vec::new();
                for segment in refs(field(e, 0)?)? {
                    let segment = self.expected(segment, "IFCCOMPOSITECURVESEGMENT")?;
                    let mut path = self.curve(reference(field(segment, 2)?)?, depth + 1)?;
                    if !boolean(field(segment, 1)?)? {
                        path.reverse();
                    }
                    append_path(&mut result, path)?;
                }
                Ok(result)
            }
            "IFCCIRCLE" | "IFCELLIPSE" => {
                let t = self.axis(Some(reference(field(e, 0)?)?))?;
                let a = positive(field(e, 1)?)?;
                let b = if e.kind == "IFCELLIPSE" {
                    positive(field(e, 2)?)?
                } else {
                    a
                };
                Ok((0..=CURVE_SEGMENTS)
                    .map(|i| {
                        let angle = i as f64 / CURVE_SEGMENTS as f64 * TAU;
                        t.apply(Vec3::new(a * angle.cos(), b * angle.sin(), 0.))
                    })
                    .collect())
            }
            _ => Err(error(format!("unsupported IFC curve {}", e.kind))),
        }
    }
    /// Build supported swept-area profile rings, including voids and derived placements.
    ///
    /// # Errors
    ///
    /// Profile schemas, dimensions, curves, winding or recursion limits are invalid or unsupported.
    #[allow(
        clippy::cast_precision_loss,
        reason = "Validated dimensions and bounded subdivision indices intentionally retain existing f64 evaluation and rounding."
    )]
    #[allow(
        clippy::too_many_lines,
        reason = "Keep the format record dispatch, validation and its resource checks together without changing geometry evaluation."
    )]
    fn profile(&self, id: u64, depth: usize) -> Result<Vec<Vec<Vec3>>> {
        self.visit()?;
        if depth > MAX_DEPTH {
            return Err(error("IFC profile references are cyclic or too deep"));
        }
        let e = self.entity(id)?;
        if text(field(e, 0)?) != Some("AREA") {
            return Err(error("IFC solid profile must define an area"));
        }
        let mut rings = match e.kind.as_str() {
            "IFCARBITRARYCLOSEDPROFILEDEF" => {
                vec![checked_ring(self.curve(reference(field(e, 2)?)?, 0)?)?]
            }
            "IFCARBITRARYPROFILEDEFWITHVOIDS" => {
                let mut rings = vec![checked_ring(self.curve(reference(field(e, 2)?)?, 0)?)?];
                for id in refs(field(e, 3)?)? {
                    rings.push(checked_ring(self.curve(id, 0)?)?);
                }
                rings
            }
            "IFCDERIVEDPROFILEDEF" | "IFCMIRROREDPROFILEDEF" => {
                let rings = self.profile(reference(field(e, 2)?)?, depth + 1)?;
                let t = self.operator(reference(field(e, 3)?)?)?;
                rings
                    .into_iter()
                    .map(|ring| ring.into_iter().map(|p| t.apply(p)).collect())
                    .collect()
            }
            "IFCRECTANGLEPROFILEDEF"
            | "IFCROUNDEDRECTANGLEPROFILEDEF"
            | "IFCRECTANGLEHOLLOWPROFILEDEF" => {
                let x = positive(field(e, 3)?)? / 2.;
                let y = positive(field(e, 4)?)? / 2.;
                let mut rings = vec![rectangle(x, y)];
                if e.kind == "IFCROUNDEDRECTANGLEPROFILEDEF" {
                    let radius = positive(field(e, 5)?)?;
                    rings[0] = fillets(
                        &rectangle(x, y),
                        &[(0, radius), (1, radius), (2, radius), (3, radius)],
                    )?;
                }
                if e.kind == "IFCRECTANGLEHOLLOWPROFILEDEF" {
                    let thickness = positive(field(e, 5)?)?;
                    if thickness >= x.min(y) {
                        return Err(error("IFC hollow rectangle wall is too thick"));
                    }
                    let inner = e
                        .fields
                        .get(6)
                        .filter(|p| !matches!(p, Parameter::NotProvided))
                        .map(number)
                        .transpose()?
                        .unwrap_or(0.);
                    let outer = e
                        .fields
                        .get(7)
                        .filter(|p| !matches!(p, Parameter::NotProvided))
                        .map(number)
                        .transpose()?
                        .unwrap_or(0.);
                    rings[0] = fillets(
                        &rectangle(x, y),
                        &[(0, outer), (1, outer), (2, outer), (3, outer)],
                    )?;
                    rings.push(fillets(
                        &rectangle(x - thickness, y - thickness),
                        &[(0, inner), (1, inner), (2, inner), (3, inner)],
                    )?);
                }
                rings
            }
            "IFCCIRCLEPROFILEDEF" | "IFCCIRCLEHOLLOWPROFILEDEF" | "IFCELLIPSEPROFILEDEF" => {
                let a = positive(field(e, 3)?)?;
                let b = if e.kind == "IFCELLIPSEPROFILEDEF" {
                    positive(field(e, 4)?)?
                } else {
                    a
                };
                let ellipse = |a: f64, b: f64| {
                    (0..CURVE_SEGMENTS)
                        .map(|i| {
                            let angle = i as f64 / CURVE_SEGMENTS as f64 * TAU;
                            Vec3::new(a * angle.cos(), b * angle.sin(), 0.)
                        })
                        .collect()
                };
                let mut rings = vec![ellipse(a, b)];
                if e.kind == "IFCCIRCLEHOLLOWPROFILEDEF" {
                    let thickness = positive(field(e, 4)?)?;
                    if thickness >= a {
                        return Err(error("IFC hollow circle wall is too thick"));
                    }
                    rings.push(ellipse(a - thickness, b - thickness));
                }
                rings
            }
            "IFCISHAPEPROFILEDEF" => {
                let w = positive(field(e, 3)?)? / 2.;
                let h = positive(field(e, 4)?)? / 2.;
                let web = positive(field(e, 5)?)? / 2.;
                let flange = positive(field(e, 6)?)?;
                if web >= w || flange >= h {
                    return Err(error("invalid IFC I-section dimensions"));
                }
                for p in e.fields.iter().skip(8) {
                    if !matches!(p, Parameter::NotProvided) && number(p)? != 0. {
                        return Err(error("IFC I-section edge rounding/slopes are unsupported"));
                    }
                }
                let ring = vec![
                    (-w, -h),
                    (w, -h),
                    (w, -h + flange),
                    (web, -h + flange),
                    (web, h - flange),
                    (w, h - flange),
                    (w, h),
                    (-w, h),
                    (-w, h - flange),
                    (-web, h - flange),
                    (-web, -h + flange),
                    (-w, -h + flange),
                ]
                .into_iter()
                .map(|(x, y)| Vec3::new(x, y, 0.))
                .collect::<Vec<_>>();
                let radius = e
                    .fields
                    .get(7)
                    .filter(|p| !matches!(p, Parameter::NotProvided))
                    .map(number)
                    .transpose()?
                    .unwrap_or(0.);
                vec![fillets(
                    &ring,
                    &[(3, radius), (4, radius), (9, radius), (10, radius)],
                )?]
            }
            _ => {
                return Err(error(format!(
                    "unsupported IFC extrusion profile {}",
                    e.kind
                )));
            }
        };
        if matches!(
            e.kind.as_str(),
            "IFCRECTANGLEPROFILEDEF"
                | "IFCROUNDEDRECTANGLEPROFILEDEF"
                | "IFCRECTANGLEHOLLOWPROFILEDEF"
                | "IFCCIRCLEPROFILEDEF"
                | "IFCCIRCLEHOLLOWPROFILEDEF"
                | "IFCELLIPSEPROFILEDEF"
                | "IFCISHAPEPROFILEDEF"
        ) {
            let t = self.axis(optional_reference(field(e, 2)?)?)?;
            for ring in &mut rings {
                for p in ring {
                    *p = t.apply(*p);
                }
            }
        }
        for (i, ring) in rings.iter_mut().enumerate() {
            if ring.iter().any(|p| p.z.abs() > 1e-8) {
                return Err(error("IFC extrusion profile is not in its XY plane"));
            }
            let area = signed_area(ring);
            if !area.is_finite() || area == 0. {
                return Err(error("IFC profile is degenerate"));
            }
            if (area > 0.) != (i == 0) {
                ring.reverse();
            }
        }
        Ok(rings)
    }
    /// Read a bounded IFC RGB surface color.
    ///
    /// # Errors
    ///
    /// The color entity/components are missing, non-finite or outside zero/one.
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "Validated zero-to-one color factors are intentionally rounded to bounded RGB bytes."
    )]
    fn color(&self, id: u64) -> Result<[u8; 3]> {
        let e = self.expected(id, "IFCCOLOURRGB")?;
        let mut color = [0; 3];
        for (i, c) in color.iter_mut().enumerate() {
            let n = number(field(e, i + 1)?)?;
            if !(0. ..=1.).contains(&n) {
                return Err(error("IFC RGB channel out of range"));
            }
            *c = (n * 255.).round() as u8;
        }
        Ok(color)
    }
    /// Resolve supported presentation style references to a diffuse color.
    ///
    /// # Errors
    ///
    /// Style references, RGB data or nesting are invalid or unsupported.
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "Validated zero-to-one color factors are intentionally rounded to bounded RGB bytes."
    )]
    fn style(&self, id: u64, depth: usize) -> Result<Option<[u8; 3]>> {
        self.visit()?;
        if depth > MAX_DEPTH {
            return Err(error("IFC style references are cyclic or too deep"));
        }
        let e = self.entity(id)?;
        match e.kind.as_str() {
            "IFCPRESENTATIONSTYLEASSIGNMENT" | "IFCSURFACESTYLE" => {
                for child in refs(field(e, if e.kind == "IFCSURFACESTYLE" { 2 } else { 0 })?)? {
                    if let Some(color) = self.style(child, depth + 1)? {
                        return Ok(Some(color));
                    }
                }
                Ok(None)
            }
            "IFCSURFACESTYLESHADING" | "IFCSURFACESTYLERENDERING" => {
                let mut color = self.color(reference(field(e, 0)?)?)?;
                if e.kind == "IFCSURFACESTYLERENDERING" {
                    match field(e, 2)? {
                        Parameter::Ref(_) => color = self.color(reference(field(e, 2)?)?)?,
                        Parameter::NotProvided => {}
                        n => {
                            let ratio = number(n)?;
                            if !(0. ..=1.).contains(&ratio) {
                                return Err(error("IFC diffuse color factor out of range"));
                            }
                            color = color.map(|c| (f64::from(c) * ratio).round() as u8);
                        }
                    }
                }
                Ok(Some(color))
            }
            "IFCCURVESTYLE" => optional_reference(field(e, 3)?)?
                .map(|id| self.color(id))
                .transpose(),
            // Texture/specular/light/refraction styles do not change geometry.
            _ => Ok(None),
        }
    }
    /// Index item and face colors from supported IFC presentation associations.
    ///
    /// # Errors
    ///
    /// Style/color associations or indexed-color references are malformed or unsupported.
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "Validated zero-to-one color factors are intentionally rounded to bounded RGB bytes."
    )]
    fn collect_styles(&mut self) -> Result<()> {
        for (&id, e) in &self.entities {
            if e.kind == "IFCSTYLEDITEM" {
                let Some(item) = optional_reference(field(e, 0)?)? else {
                    continue;
                };
                for style in refs(field(e, 1)?)? {
                    if let Some(color) = self.style(style, 0)? {
                        if let Some(previous) = self.colors.insert(item, color)
                            && previous != color
                        {
                            return Err(error(format!("conflicting IFC styles on #{item}")));
                        }
                        break;
                    }
                }
            } else if e.kind == "IFCINDEXEDCOLOURMAP" {
                let mapped = reference(field(e, 0)?)?;
                let colors = self.expected(reference(field(e, 2)?)?, "IFCCOLOURRGBLIST")?;
                let colors = list(field(colors, 0)?)?
                    .iter()
                    .map(|value| {
                        let v = list(value)?;
                        if v.len() != 3 {
                            return Err(error("IFC color list requires RGB triples"));
                        }
                        let mut c = [0; 3];
                        for i in 0..3 {
                            let n = number(&v[i])?;
                            if !(0. ..=1.).contains(&n) {
                                return Err(error("IFC RGB channel out of range"));
                            }
                            c[i] = (n * 255.).round() as u8;
                        }
                        Ok(c)
                    })
                    .collect::<Result<Vec<_>>>()?;
                let indices = list(field(e, 3)?)?;
                let values = indices
                    .iter()
                    .map(|p| {
                        let index = integer(p)?
                            .checked_sub(1)
                            .ok_or_else(|| error("IFC color indices are one-based"))?;
                        colors
                            .get(index)
                            .copied()
                            .ok_or_else(|| error("IFC color index out of range"))
                    })
                    .collect::<Result<Vec<_>>>()?;
                if self.face_colors.insert(mapped, values).is_some() {
                    return Err(error(format!("duplicate IFC color map #{id}")));
                }
            }
        }
        Ok(())
    }
    /// Append transformed triangle geometry with inherited color and corrected mirror winding.
    ///
    /// # Errors
    ///
    /// Coordinates overflow or the output exceeds the geometry limit.
    fn emit(
        scene: &mut Scene,
        vertices: [Vec3; 3],
        t: Transform,
        color: Option<[u8; 3]>,
    ) -> Result<()> {
        if scene.triangles.len() >= MAX_GEOMETRY {
            return Err(error("IFC triangle count exceeds limit"));
        }
        let mut vertices = vertices.map(|p| t.apply(p));
        if vertices.iter().any(|p| !p.is_finite()) {
            return Err(error("IFC transform overflows its coordinates"));
        }
        if determinant(t) < 0. {
            vertices.swap(1, 2);
        }
        if (vertices[1] - vertices[0])
            .cross(vertices[2] - vertices[0])
            .length()
            > 1e-15
        {
            scene.triangles.push(Triangle { vertices, color });
        }
        Ok(())
    }
    /// Render one product's representation in its absolute placement and subtract linked openings.
    ///
    /// # Errors
    ///
    /// Product/representation/placement references or required geometry are invalid or unsupported.
    fn product(&self, id: u64) -> Result<Scene> {
        let p = self.entity(id)?;
        let Some(representation) = optional_reference(field(p, 6)?)? else {
            return Ok(Scene::default());
        };
        let placement = self.placement(optional_reference(field(p, 5)?)?, 0)?;
        let shape = self.entity(representation)?;
        let reps = refs(field(shape, 2)?)?;
        let has_body = reps.iter().any(|id| {
            self.entities
                .get(id)
                .and_then(|e| e.fields.get(1))
                .and_then(text)
                == Some("Body")
        });
        let mut scene = Scene::default();
        for id in reps {
            let r = self.entity(id)?;
            if r.kind != "IFCSHAPEREPRESENTATION" {
                return Err(error("unsupported IFC product representation"));
            }
            let identifier = text(field(r, 1)?);
            if has_body && identifier != Some("Body") {
                continue;
            }
            if matches!(
                identifier,
                Some("Axis" | "FootPrint" | "Box" | "Clearance" | "SurveyPoints")
            ) {
                continue;
            }
            self.geometry(id, placement, None, 0, &mut scene)?;
        }
        Ok(scene)
    }
    /// Create a bounded half-space clipping solid around an operand's bounds.
    ///
    /// # Errors
    ///
    /// The half-space schema, placement, dimensions or clipping geometry are invalid or unsupported.
    fn halfspace(&self, id: u64, operand: &Scene, color: Option<[u8; 3]>) -> Result<Scene> {
        let e = self.expected(id, "IFCHALFSPACESOLID")?;
        let plane = self.expected(reference(field(e, 0)?)?, "IFCPLANE")?;
        let placement = self.axis(Some(reference(field(plane, 0)?)?))?;
        let origin = column(placement, 3);
        let mut minimum = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
        let mut maximum = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
        for p in operand.triangles.iter().flat_map(|t| t.vertices) {
            let p = p - origin;
            let p = Vec3::new(
                p.dot(column(placement, 0)),
                p.dot(column(placement, 1)),
                p.dot(column(placement, 2)),
            );
            minimum = Vec3::new(minimum.x.min(p.x), minimum.y.min(p.y), minimum.z.min(p.z));
            maximum = Vec3::new(maximum.x.max(p.x), maximum.y.max(p.y), maximum.z.max(p.z));
        }
        let negative = boolean(field(e, 1)?)?;
        if operand.triangles.is_empty()
            || (negative && minimum.z >= 0.)
            || (!negative && maximum.z <= 0.)
        {
            return Ok(Scene::default());
        }
        let extent = (maximum - minimum).length().max(1e-8);
        if !extent.is_finite() {
            return Err(error("IFC half-space bounds overflow"));
        }
        minimum = minimum - Vec3::new(extent, extent, extent);
        maximum = maximum + Vec3::new(extent, extent, extent);
        if negative {
            maximum.z = 0.;
        } else {
            minimum.z = 0.;
        }
        let p = [
            Vec3::new(minimum.x, minimum.y, minimum.z),
            Vec3::new(maximum.x, minimum.y, minimum.z),
            Vec3::new(maximum.x, maximum.y, minimum.z),
            Vec3::new(minimum.x, maximum.y, minimum.z),
            Vec3::new(minimum.x, minimum.y, maximum.z),
            Vec3::new(maximum.x, minimum.y, maximum.z),
            Vec3::new(maximum.x, maximum.y, maximum.z),
            Vec3::new(minimum.x, maximum.y, maximum.z),
        ];
        let mut scene = Scene::default();
        for [a, b, c, d] in [
            [0, 3, 2, 1],
            [4, 5, 6, 7],
            [0, 1, 5, 4],
            [1, 2, 6, 5],
            [2, 3, 7, 6],
            [3, 0, 4, 7],
        ] {
            Self::emit(&mut scene, [p[a], p[b], p[c]], placement, color)?;
            Self::emit(&mut scene, [p[a], p[c], p[d]], placement, color)?;
        }
        Ok(scene)
    }
    /// Append an IFC polygonal face with its boundary holes.
    ///
    /// # Errors
    ///
    /// Face/boundary references, ring geometry or triangulation are invalid or unsupported.
    fn face(&self, id: u64, t: Transform, color: Option<[u8; 3]>, scene: &mut Scene) -> Result<()> {
        let e = self.entity(id)?;
        if !matches!(
            e.kind.as_str(),
            "IFCFACE" | "IFCFACESURFACE" | "IFCADVANCEDFACE"
        ) {
            return Err(error(format!("unsupported IFC shell face {}", e.kind)));
        }
        if e.kind != "IFCFACE" {
            self.expected(reference(field(e, 1)?)?, "IFCPLANE")?;
        }
        let mut rings = Vec::new();
        let mut outer = None;
        for bound in refs(field(e, 0)?)? {
            let b = self.entity(bound)?;
            if !matches!(b.kind.as_str(), "IFCFACEBOUND" | "IFCFACEOUTERBOUND") {
                return Err(error("unsupported IFC face bound"));
            }
            let loop_id = reference(field(b, 0)?)?;
            self.expected(loop_id, "IFCPOLYLOOP")?;
            let mut ring = checked_ring(self.curve(loop_id, 0)?)?;
            if !boolean(field(b, 1)?)? {
                ring.reverse();
            }
            if b.kind == "IFCFACEOUTERBOUND" && outer.replace(rings.len()).is_some() {
                return Err(error("IFC face has multiple outer bounds"));
            }
            rings.push(ring);
        }
        if let Some(index) = outer {
            rings.swap(0, index);
        }
        for triangle in triangles(&rings)? {
            Self::emit(scene, triangle, t, color)?;
        }
        Ok(())
    }
    /// Expand supported tessellated, swept, mapped and Boolean representation items.
    ///
    /// # Errors
    ///
    /// Required geometry, entity references or numeric data are invalid/unsupported, or preview budgets are exceeded.
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_precision_loss,
        clippy::cast_sign_loss,
        reason = "Validated dimensions and bounded subdivision indices intentionally retain existing f64 evaluation and rounding."
    )]
    #[allow(
        clippy::too_many_lines,
        reason = "Keep the format record dispatch, validation and its resource checks together without changing geometry evaluation."
    )]
    #[allow(
        clippy::many_single_char_names,
        reason = "Geometric formulas use conventional axis, endpoint and basis-vector symbols."
    )]
    fn geometry(
        &self,
        id: u64,
        t: Transform,
        inherited: Option<[u8; 3]>,
        depth: usize,
        scene: &mut Scene,
    ) -> Result<()> {
        self.visit()?;
        if depth > MAX_DEPTH {
            return Err(error("IFC geometry references are cyclic or too deep"));
        }
        let e = self.entity(id)?;
        let color = self.colors.get(&id).copied().or(inherited);
        match e.kind.as_str() {
            "IFCSHAPEREPRESENTATION" | "IFCTOPOLOGYREPRESENTATION" => {
                for child in refs(field(e, 3)?)? {
                    self.geometry(child, t, color, depth + 1, scene)?;
                }
            }
            "IFCMAPPEDITEM" => {
                let map = self.expected(reference(field(e, 0)?)?, "IFCREPRESENTATIONMAP")?;
                // MappingOrigin defines the source coordinate frame; target transforms it.
                let map_transform = self
                    .operator(reference(field(e, 1)?)?)?
                    .then(self.axis(Some(reference(field(map, 0)?)?))?);
                self.geometry(
                    reference(field(map, 1)?)?,
                    t.then(map_transform),
                    color,
                    depth + 1,
                    scene,
                )?;
            }
            "IFCEXTRUDEDAREASOLID" => {
                let rings = self.profile(reference(field(e, 0)?)?, 0)?;
                let placement = t.then(self.axis(optional_reference(field(e, 1)?)?)?);
                let direction = self.direction(reference(field(e, 2)?)?)?;
                let delta = direction * positive(field(e, 3)?)?;
                if direction.z.abs() < 1e-12 {
                    return Err(error("IFC extrusion direction lies in the profile plane"));
                }
                let reverse = direction.z < 0.;
                for mut triangle in triangles(&rings)? {
                    if reverse {
                        triangle.swap(1, 2);
                    }
                    Self::emit(scene, triangle.map(|p| p + delta), placement, color)?;
                    triangle.swap(1, 2);
                    Self::emit(scene, triangle, placement, color)?;
                }
                for ring in &rings {
                    for i in 0..ring.len() {
                        let a = ring[i];
                        let b = ring[(i + 1) % ring.len()];
                        for mut tri in [[a, b, b + delta], [a, b + delta, a + delta]] {
                            if reverse {
                                tri.swap(1, 2);
                            }
                            Self::emit(scene, tri, placement, color)?;
                        }
                    }
                }
            }
            "IFCREVOLVEDAREASOLID" => {
                let rings = self.profile(reference(field(e, 0)?)?, 0)?;
                let placement = t.then(self.axis(optional_reference(field(e, 1)?)?)?);
                let axis = self.axis(Some(reference(field(e, 2)?)?))?;
                let origin = column(axis, 3);
                let direction = column(axis, 2);
                if origin.z.abs() > 1e-8 || direction.z.abs() > 1e-8 {
                    return Err(error("IFC revolution axis must lie in the profile plane"));
                }
                let angle = positive(field(e, 3)?)? * self.angle_scale;
                if !angle.is_finite() || angle > TAU + 1e-6 {
                    return Err(error("IFC revolution angle exceeds a full turn"));
                }
                let angle = angle.min(TAU);
                let count = (angle / TAU * CURVE_SEGMENTS as f64).ceil().max(2.) as usize;
                let center = rings[0].iter().copied().fold(Vec3::default(), |a, b| a + b)
                    / rings[0].len() as f64;
                let forward = direction.cross(center - origin).z;
                if forward.abs() < 1e-12 {
                    return Err(error("IFC revolution axis crosses the profile center"));
                }
                let reverse = forward < 0.;
                let rotated = |p: Vec3, theta: f64| {
                    let v = p - origin;
                    origin
                        + v * theta.cos()
                        + direction.cross(v) * theta.sin()
                        + direction * (direction.dot(v) * (1. - theta.cos()))
                };
                if angle < TAU - 1e-6 {
                    for mut tri in triangles(&rings)? {
                        if reverse {
                            tri.swap(1, 2);
                        }
                        Self::emit(scene, tri.map(|p| rotated(p, angle)), placement, color)?;
                        tri.swap(1, 2);
                        Self::emit(scene, tri, placement, color)?;
                    }
                }
                for j in 0..count {
                    let start = angle * j as f64 / count as f64;
                    let end = angle * (j + 1) as f64 / count as f64;
                    for ring in &rings {
                        for i in 0..ring.len() {
                            let a = ring[i];
                            let b = ring[(i + 1) % ring.len()];
                            let a0 = rotated(a, start);
                            let b0 = rotated(b, start);
                            let a1 = rotated(a, end);
                            let b1 = rotated(b, end);
                            for mut tri in [[a0, b0, b1], [a0, b1, a1]] {
                                if reverse {
                                    tri.swap(1, 2);
                                }
                                Self::emit(scene, tri, placement, color)?;
                            }
                        }
                    }
                }
            }
            "IFCBOOLEANRESULT" | "IFCBOOLEANCLIPPINGRESULT" => {
                let mut a = Scene::default();
                let mut b = Scene::default();
                self.geometry(
                    reference(field(e, 1)?)?,
                    Transform::IDENTITY,
                    color,
                    depth + 1,
                    &mut a,
                )?;
                let second = reference(field(e, 2)?)?;
                let operator =
                    text(field(e, 0)?).ok_or_else(|| error("invalid IFC Boolean operator"))?;
                if self.entity(second)?.kind == "IFCHALFSPACESOLID" {
                    if operator == "UNION" {
                        return Err(error("IFC union with an infinite half-space is unbounded"));
                    }
                    b = self.halfspace(second, &a, color)?;
                } else {
                    self.geometry(second, Transform::IDENTITY, color, depth + 1, &mut b)?;
                }
                if !a.lines.is_empty()
                    || !a.points.is_empty()
                    || !b.lines.is_empty()
                    || !b.points.is_empty()
                {
                    return Err(error("IFC Boolean operands must be solids"));
                }
                let triangles = csg::boolean(a.triangles, b.triangles, operator)?;
                if scene.triangles.len() + triangles.len() > MAX_GEOMETRY {
                    return Err(error("IFC triangle count exceeds limit"));
                }
                for triangle in triangles {
                    Self::emit(scene, triangle.vertices, t, triangle.color)?;
                }
            }
            "IFCCSGSOLID" => self.geometry(reference(field(e, 0)?)?, t, color, depth + 1, scene)?,
            "IFCBLOCK" => {
                let placement = t.then(self.axis(Some(reference(field(e, 0)?)?))?);
                let x = positive(field(e, 1)?)?;
                let y = positive(field(e, 2)?)?;
                let z = positive(field(e, 3)?)?;
                let p = [
                    Vec3::new(0., 0., 0.),
                    Vec3::new(x, 0., 0.),
                    Vec3::new(x, y, 0.),
                    Vec3::new(0., y, 0.),
                    Vec3::new(0., 0., z),
                    Vec3::new(x, 0., z),
                    Vec3::new(x, y, z),
                    Vec3::new(0., y, z),
                ];
                for [a, b, c, d] in [
                    [0, 3, 2, 1],
                    [4, 5, 6, 7],
                    [0, 1, 5, 4],
                    [1, 2, 6, 5],
                    [2, 3, 7, 6],
                    [3, 0, 4, 7],
                ] {
                    Self::emit(scene, [p[a], p[b], p[c]], placement, color)?;
                    Self::emit(scene, [p[a], p[c], p[d]], placement, color)?;
                }
            }
            "IFCRIGHTCIRCULARCYLINDER" | "IFCRIGHTCIRCULARCONE" => {
                let placement = t.then(self.axis(Some(reference(field(e, 0)?)?))?);
                let height = positive(field(e, 1)?)?;
                let radius = positive(field(e, 2)?)?;
                let conical = e.kind == "IFCRIGHTCIRCULARCONE";
                for i in 0..CURVE_SEGMENTS {
                    let a = i as f64 / CURVE_SEGMENTS as f64 * TAU;
                    let b = (i + 1) as f64 / CURVE_SEGMENTS as f64 * TAU;
                    let a0 = Vec3::new(radius * a.cos(), radius * a.sin(), 0.);
                    let b0 = Vec3::new(radius * b.cos(), radius * b.sin(), 0.);
                    let a1 = if conical {
                        Vec3::new(0., 0., height)
                    } else {
                        a0 + Vec3::new(0., 0., height)
                    };
                    let b1 = if conical {
                        a1
                    } else {
                        b0 + Vec3::new(0., 0., height)
                    };
                    Self::emit(scene, [a0, b0, b1], placement, color)?;
                    Self::emit(scene, [a0, b1, a1], placement, color)?;
                    Self::emit(scene, [Vec3::default(), b0, a0], placement, color)?;
                    if !conical {
                        Self::emit(scene, [Vec3::new(0., 0., height), a1, b1], placement, color)?;
                    }
                }
            }
            "IFCSPHERE" => {
                let placement = t.then(self.axis(Some(reference(field(e, 0)?)?))?);
                let radius = positive(field(e, 1)?)?;
                let point = |i: usize, j: usize| {
                    let lon = i as f64 / CURVE_SEGMENTS as f64 * TAU;
                    let lat = j as f64 / (CURVE_SEGMENTS / 2) as f64 * PI - PI / 2.;
                    Vec3::new(
                        radius * lat.cos() * lon.cos(),
                        radius * lat.cos() * lon.sin(),
                        radius * lat.sin(),
                    )
                };
                for j in 0..CURVE_SEGMENTS / 2 {
                    for i in 0..CURVE_SEGMENTS {
                        let a = point(i, j);
                        let b = point(i + 1, j);
                        let c = point(i + 1, j + 1);
                        let d = point(i, j + 1);
                        Self::emit(scene, [a, b, c], placement, color)?;
                        Self::emit(scene, [a, c, d], placement, color)?;
                    }
                }
            }
            "IFCTRIANGULATEDFACESET" | "IFCPOLYGONALFACESET" => {
                let points = self.coordinates(reference(field(e, 0)?)?)?;
                let triangular = e.kind == "IFCTRIANGULATEDFACESET";
                let index_field = if triangular { 3 } else { 2 };
                let pn = e
                    .fields
                    .get(if triangular { 4 } else { 3 })
                    .map(|p| {
                        if matches!(p, Parameter::NotProvided) {
                            Ok(None)
                        } else {
                            list(p)?
                                .iter()
                                .map(integer)
                                .collect::<Result<Vec<_>>>()
                                .map(Some)
                        }
                    })
                    .transpose()?
                    .flatten();
                let get = |p: &Parameter| -> Result<Vec3> {
                    let index = integer(p)?
                        .checked_sub(1)
                        .ok_or_else(|| error("IFC coordinate indices are one-based"))?;
                    let index = if let Some(pn) = &pn {
                        pn.get(index)
                            .copied()
                            .ok_or_else(|| error("IFC PnIndex is out of range"))?
                            .checked_sub(1)
                            .ok_or_else(|| error("IFC PnIndex entries are one-based"))?
                    } else {
                        index
                    };
                    points
                        .get(index)
                        .copied()
                        .ok_or_else(|| error("IFC face coordinate index is out of range"))
                };
                let faces = list(field(e, index_field)?)?;
                if let Some(colors) = self.face_colors.get(&id)
                    && colors.len() != faces.len()
                {
                    return Err(error("IFC indexed colors differ from face count"));
                }
                for (i, face) in faces.iter().enumerate() {
                    let face_color = self.face_colors.get(&id).map(|v| v[i]).or(color);
                    if triangular {
                        let face = list(face)?;
                        if face.len() != 3 {
                            return Err(error("IFC triangulated face requires three indices"));
                        }
                        Self::emit(
                            scene,
                            [get(&face[0])?, get(&face[1])?, get(&face[2])?],
                            t,
                            face_color,
                        )?;
                    } else {
                        let f = self.entity(reference(face)?)?;
                        if !matches!(
                            f.kind.as_str(),
                            "IFCINDEXEDPOLYGONALFACE" | "IFCINDEXEDPOLYGONALFACEWITHVOIDS"
                        ) {
                            return Err(error("unsupported IFC polygonal face"));
                        }
                        let mut rings = vec![checked_ring(
                            list(field(f, 0)?)?.iter().map(get).collect::<Result<_>>()?,
                        )?];
                        if f.kind == "IFCINDEXEDPOLYGONALFACEWITHVOIDS" {
                            for inner in list(field(f, 1)?)? {
                                rings.push(checked_ring(
                                    list(inner)?.iter().map(get).collect::<Result<_>>()?,
                                )?);
                            }
                        }
                        for triangle in triangles(&rings)? {
                            Self::emit(scene, triangle, t, face_color)?;
                        }
                    }
                }
            }
            "IFCFACETEDBREP"
            | "IFCSHELLBASEDSURFACEMODEL"
            | "IFCFACEBASEDSURFACEMODEL"
            | "IFCCLOSEDSHELL"
            | "IFCOPENSHELL"
            | "IFCCONNECTEDFACESET"
            | "IFCGEOMETRICSET"
            | "IFCGEOMETRICCURVESET" => {
                let children = if e.kind == "IFCFACETEDBREP" {
                    vec![reference(field(e, 0)?)?]
                } else {
                    refs(field(e, 0)?)?
                };
                for child in children {
                    self.geometry(child, t, color, depth + 1, scene)?;
                }
            }
            "IFCFACE" | "IFCFACESURFACE" | "IFCADVANCEDFACE" => self.face(id, t, color, scene)?,
            "IFCPOLYLINE"
            | "IFCINDEXEDPOLYCURVE"
            | "IFCCOMPOSITECURVE"
            | "IFCCIRCLE"
            | "IFCELLIPSE" => {
                let path = self.curve(id, 0)?;
                if scene.lines.len() + path.len() > MAX_GEOMETRY {
                    return Err(error("IFC line count exceeds limit"));
                }
                for pair in path.windows(2) {
                    scene.lines.push(Line {
                        vertices: [t.apply(pair[0]), t.apply(pair[1])],
                        color,
                    });
                }
            }
            "IFCCARTESIANPOINT" => {
                if scene.points.len() >= MAX_GEOMETRY {
                    return Err(error("IFC point count exceeds limit"));
                }
                scene.points.push(Point {
                    position: t.apply(self.point(id)?),
                    color,
                });
            }
            _ => {
                return Err(error(format!(
                    "unsupported IFC required geometry {} (#{id})",
                    e.kind
                )));
            }
        }
        Ok(())
    }
}
/// Create a centered rectangular XY profile with the supplied dimensions.
fn rectangle(x: f64, y: f64) -> Vec<Vec3> {
    [(-x, -y), (x, -y), (x, y), (-x, y)]
        .map(|(x, y)| Vec3::new(x, y, 0.))
        .to_vec()
}
/// Replace selected polygon corners with bounded circular fillet samples.
///
/// # Errors
///
/// Corner indices, radii or neighboring edges cannot define supported finite fillets.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss,
    reason = "Validated dimensions and bounded subdivision indices intentionally retain existing f64 evaluation and rounding."
)]
#[allow(
    clippy::many_single_char_names,
    reason = "Geometric formulas use conventional axis, endpoint and basis-vector symbols."
)]
fn fillets(ring: &[Vec3], corners: &[(usize, f64)]) -> Result<Vec<Vec3>> {
    let mut result = Vec::new();
    for i in 0..ring.len() {
        let radius = corners
            .iter()
            .find(|(index, _)| *index == i)
            .map_or(0., |(_, r)| *r);
        if radius == 0. {
            result.push(ring[i]);
            continue;
        }
        if radius < 0. || !radius.is_finite() {
            return Err(error("invalid IFC profile fillet radius"));
        }
        let a = ring[(i + ring.len() - 1) % ring.len()];
        let b = ring[i];
        let c = ring[(i + 1) % ring.len()];
        let u = normalized(a - b)?;
        let v = normalized(c - b)?;
        let angle = u.dot(v).clamp(-1., 1.).acos();
        let distance = radius / (angle / 2.).tan();
        if !distance.is_finite()
            || distance > (a - b).length() / 2.
            || distance > (c - b).length() / 2.
        {
            return Err(error("IFC profile fillet radius exceeds adjacent edges"));
        }
        let center = b + normalized(u + v)? * (radius / (angle / 2.).sin());
        let start = b + u * distance;
        let end = b + v * distance;
        let theta = (start.y - center.y).atan2(start.x - center.x);
        let mut sweep =
            ((end.y - center.y).atan2(end.x - center.x) - theta + PI).rem_euclid(TAU) - PI;
        let turn = (b - a).cross(c - b).z;
        if sweep * turn < 0. {
            sweep += if turn > 0. { TAU } else { -TAU };
        }
        let steps = (sweep.abs() / TAU * CURVE_SEGMENTS as f64).ceil().max(2.) as usize;
        for j in 0..=steps {
            let angle = theta + sweep * j as f64 / steps as f64;
            result.push(center + Vec3::new(radius * angle.cos(), radius * angle.sin(), 0.));
        }
    }
    Ok(result)
}
/// Join consecutive sampled curve segments without duplicating shared endpoints.
///
/// # Errors
///
/// The segments are empty, discontinuous, non-finite or exceed geometry limits.
fn append_path(result: &mut Vec<Vec3>, mut next: Vec<Vec3>) -> Result<()> {
    if next.is_empty() {
        return Err(error("empty IFC curve segment"));
    }
    if let Some(last) = result.last() {
        if (*last - next[0]).length() > 1e-7 * last.length().max(next[0].length()).max(1.) {
            return Err(error("IFC composite curve segments are disconnected"));
        }
        let _ = next.remove(0);
    }
    if result
        .len()
        .checked_add(next.len())
        .is_none_or(|n| n > MAX_GEOMETRY)
    {
        return Err(error("IFC curve length exceeds limit"));
    }
    result.extend(next);
    Ok(())
}
/// Sample the circular arc passing through three authored points.
///
/// # Errors
///
/// The points cannot define a finite nondegenerate circle.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss,
    reason = "Validated dimensions and bounded subdivision indices intentionally retain existing f64 evaluation and rounding."
)]
#[allow(
    clippy::many_single_char_names,
    reason = "Geometric formulas use conventional axis, endpoint and basis-vector symbols."
)]
fn arc(a: Vec3, b: Vec3, c: Vec3) -> Result<Vec<Vec3>> {
    let ab = b - a;
    let ac = c - a;
    let cross = ab.cross(ac);
    let d = 2. * cross.dot(cross);
    if !d.is_finite() || d <= 1e-24 {
        return Err(error("IFC circular arc points are collinear"));
    }
    let center = a + (ac.cross(cross) * ab.dot(ab) + cross.cross(ab) * ac.dot(ac)) / d;
    let x = normalized(a - center)?;
    let z = normalized(cross)?;
    let y = z.cross(x);
    let angle = |p: Vec3| {
        let p = p - center;
        p.dot(y).atan2(p.dot(x)).rem_euclid(TAU)
    };
    let end = angle(c);
    let mid = angle(b);
    let sweep = if mid <= end { end } else { end - TAU };
    let steps = (sweep.abs() / TAU * CURVE_SEGMENTS as f64).ceil().max(2.) as usize;
    let radius = (a - center).length();
    let mut points: Vec<_> = (0..=steps)
        .map(|i| {
            let theta = sweep * i as f64 / steps as f64;
            center + (x * theta.cos() + y * theta.sin()) * radius
        })
        .collect();
    points[0] = a;
    points[steps] = c;
    Ok(points)
}

/// Validate IFC Part 21 string/comment boundaries and bound parameter nesting.
///
/// # Errors
///
/// Strings/comments are unterminated, parentheses are unbalanced or nesting is excessive.
fn nesting(text: &str) -> Result<()> {
    let bytes = text.as_bytes();
    let (mut i, mut depth) = (0usize, 0usize);
    while i < bytes.len() {
        match bytes[i] {
            b'\'' => {
                i += 1;
                loop {
                    let b = *bytes
                        .get(i)
                        .ok_or_else(|| error("unterminated IFC string"))?;
                    i += 1;
                    if b == b'\'' {
                        if bytes.get(i) == Some(&b'\'') {
                            i += 1;
                        } else {
                            break;
                        }
                    }
                }
            }
            b'/' if bytes.get(i + 1) == Some(&b'*') => {
                i += 2;
                while bytes.get(i..i + 2) != Some(b"*/") {
                    if i >= bytes.len() {
                        return Err(error("unterminated IFC comment"));
                    }
                    i += 1;
                }
                i += 2;
            }
            b'(' => {
                depth += 1;
                if depth > MAX_DEPTH {
                    return Err(error("IFC parameter nesting exceeds limit"));
                }
                i += 1;
            }
            b')' => {
                depth = depth
                    .checked_sub(1)
                    .ok_or_else(|| error("unbalanced IFC parentheses"))?;
                i += 1;
            }
            _ => i += 1,
        }
    }
    if depth != 0 {
        return Err(error("unbalanced IFC parentheses"));
    }
    Ok(())
}
/// Resolve supported IFC SI/conversion units with bounded recursion.
///
/// # Errors
///
/// Units, dimensions, conversion factors or recursion limits are invalid or unsupported.
fn unit(model: &Model, id: u64, depth: usize) -> Result<f64> {
    if depth > MAX_DEPTH {
        return Err(error("IFC unit references are cyclic or too deep"));
    }
    let e = model.entity(id)?;
    match e.kind.as_str() {
        "IFCSIUNIT" => {
            if !matches!(text(field(e, 3)?), Some("METRE" | "RADIAN")) {
                return Err(error("unsupported IFC SI geometry unit"));
            }
            match text(field(e, 2)?) {
                None => Ok(1.),
                Some("MILLI") => Ok(1e-3),
                Some("CENTI") => Ok(1e-2),
                Some("DECI") => Ok(1e-1),
                Some("KILO") => Ok(1e3),
                Some("MICRO") => Ok(1e-6),
                Some("NANO") => Ok(1e-9),
                Some("MEGA") => Ok(1e6),
                Some(_) => Err(error("unsupported IFC SI geometry unit prefix")),
            }
        }
        "IFCCONVERSIONBASEDUNIT" => {
            let factor = model.expected(reference(field(e, 3)?)?, "IFCMEASUREWITHUNIT")?;
            let result = positive(field(factor, 0)?)?
                * unit(model, reference(field(factor, 1)?)?, depth + 1)?;
            if !result.is_finite() {
                return Err(error("IFC unit conversion overflow"));
            }
            Ok(result)
        }
        _ => Err(error("unsupported IFC geometry unit")),
    }
}
/// Read IFC Part 21 product geometry and placement data.
///
/// # Errors
///
/// File/UTF-8 parsing, required IFC geometry or preview limits fail validation.
pub(super) fn load(path: &Path) -> Result<Scene> {
    let bytes = super::read_file(path)?;
    let source = std::str::from_utf8(&bytes)?.trim_start_matches('\u{feff}');
    parse(source)
}
/// Parse IFC entities, units, presentation styles and renderable products.
///
/// # Errors
///
/// Entity syntax/references, required geometry, units or preview budgets 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 parse(source: &str) -> Result<Scene> {
    nesting(source)?;
    let exchange = ruststep::parser::parse(source)
        .map_err(|_| error("invalid IFC STEP Part 21 exchange file"))?;
    let schema = exchange
        .header
        .iter()
        .find(|r| r.name.as_str() == "FILE_SCHEMA")
        .and_then(|r| list(&r.parameter).ok())
        .and_then(|p| p.first())
        .and_then(|p| list(p).ok())
        .and_then(|p| p.first())
        .and_then(text)
        .ok_or_else(|| error("IFC exchange requires FILE_SCHEMA"))?;
    if schema != "IFC2X3" && !schema.starts_with("IFC4") {
        return Err(error(format!("unsupported IFC schema {schema}")));
    }
    if !exchange.anchor.is_empty() || !exchange.reference.is_empty() {
        return Err(error("IFC external STEP references are unsupported"));
    }
    let mut model = Model {
        entities: HashMap::new(),
        colors: HashMap::new(),
        face_colors: HashMap::new(),
        length_scale: 1.,
        angle_scale: 1.,
        visits: Cell::new(0),
    };
    for entity in exchange
        .data
        .into_iter()
        .flat_map(|section| section.entities)
    {
        if model.entities.len() >= MAX_ENTITIES {
            return Err(error("IFC entity count exceeds limit"));
        }
        let EntityInstance::Simple { id, record } = entity else {
            return Err(error("IFC complex STEP entities are unsupported"));
        };
        let Parameter::List(fields) = record.parameter else {
            return Err(error("invalid IFC entity attribute list"));
        };
        if model
            .entities
            .insert(
                id,
                Entity {
                    kind: record.name,
                    fields,
                },
            )
            .is_some()
        {
            return Err(error("duplicate IFC entity ID"));
        }
    }
    for e in model.entities.values().filter(|e| e.kind == "IFCPROJECT") {
        if let Some(units) = optional_reference(field(e, 8)?)? {
            for id in refs(field(model.expected(units, "IFCUNITASSIGNMENT")?, 0)?)? {
                let u = model.entity(id)?;
                let kind = text(field(u, 1)?).map(str::to_owned);
                if kind.as_deref() == Some("LENGTHUNIT") {
                    model.length_scale = unit(&model, id, 0)?;
                }
                if kind.as_deref() == Some("PLANEANGLEUNIT") {
                    model.angle_scale = unit(&model, id, 0)?;
                }
            }
        }
    }
    model.collect_styles()?;
    let mut products: Vec<_> = model
        .entities
        .iter()
        .filter_map(|(&id, e)| {
            let p = e
                .fields
                .get(6)
                .and_then(|p| optional_reference(p).ok())
                .flatten()?;
            model.entities.get(&p).filter(|e| {
                matches!(
                    e.kind.as_str(),
                    "IFCPRODUCTDEFINITIONSHAPE" | "IFCPRODUCTREPRESENTATION"
                )
            })?;
            Some((id, p))
        })
        .collect();
    products.sort_unstable();
    let mut openings = HashMap::<u64, Vec<u64>>::new();
    let mut voids = HashSet::new();
    for e in model
        .entities
        .values()
        .filter(|e| e.kind == "IFCRELVOIDSELEMENT")
    {
        let host = reference(field(e, 4)?)?;
        let opening = reference(field(e, 5)?)?;
        model.entity(host)?;
        model.entity(opening)?;
        if host == opening {
            return Err(error("IFC product cannot void itself"));
        }
        if !voids.insert(opening) {
            return Err(error("IFC opening is assigned to multiple products"));
        }
        openings.entry(host).or_default().push(opening);
    }
    let mut scene = Scene::default();
    for (product, _) in products {
        let p = model.entity(product)?;
        if voids.contains(&product)
            || matches!(
                p.kind.as_str(),
                "IFCOPENINGELEMENT" | "IFCOPENINGSTANDARDCASE" | "IFCSPACE"
            )
        {
            continue;
        }
        let mut item = model.product(product)?;
        if let Some(openings) = openings.get(&product) {
            if !item.lines.is_empty() || !item.points.is_empty() {
                return Err(error(
                    "IFC products with openings require solid body geometry",
                ));
            }
            let color = item.triangles.first().and_then(|t| t.color);
            for &opening in openings {
                let mut cut = model.product(opening)?;
                if !cut.lines.is_empty() || !cut.points.is_empty() {
                    return Err(error("IFC openings require solid body geometry"));
                }
                for t in &mut cut.triangles {
                    t.color = color;
                }
                item.triangles = csg::boolean(item.triangles, cut.triangles, "DIFFERENCE")?;
            }
        }
        if scene
            .triangles
            .len()
            .checked_add(item.triangles.len())
            .is_none_or(|n| n > MAX_GEOMETRY)
            || scene
                .lines
                .len()
                .checked_add(item.lines.len())
                .is_none_or(|n| n > MAX_GEOMETRY)
            || scene
                .points
                .len()
                .checked_add(item.points.len())
                .is_none_or(|n| n > MAX_GEOMETRY)
        {
            return Err(error("IFC scene geometry count exceeds limit"));
        }
        scene.triangles.extend(item.triangles);
        scene.lines.extend(item.lines);
        scene.points.extend(item.points);
    }
    for tri in &mut scene.triangles {
        for p in &mut tri.vertices {
            *p = *p * model.length_scale;
        }
    }
    for line in &mut scene.lines {
        for p in &mut line.vertices {
            *p = *p * model.length_scale;
        }
    }
    for p in &mut scene.points {
        p.position = p.position * model.length_scale;
    }
    scene.validate()?;
    Ok(scene)
}

#[cfg(test)]
mod tests {
    use super::*;
    fn fixture(geometry: &str) -> String {
        format!(
            "ISO-10303-21;HEADER;FILE_SCHEMA(('IFC4'));ENDSEC;DATA;
            #1=IFCCARTESIANPOINT((0.,0.,0.));#2=IFCAXIS2PLACEMENT3D(#1,$,$);
            #3=IFCLOCALPLACEMENT($,#2);
            #4=IFCBUILDINGELEMENTPROXY('id',$,'shape',$,$,#3,#5,$,$);
            #5=IFCPRODUCTDEFINITIONSHAPE($,$,(#6));
            #6=IFCSHAPEREPRESENTATION($,'Body','SolidModel',(#20));
            {geometry}ENDSEC;END-ISO-10303-21;"
        )
    }
    fn volume(scene: &Scene) -> f64 {
        scene
            .triangles
            .iter()
            .map(|t| t.vertices[0].dot(t.vertices[1].cross(t.vertices[2])) / 6.)
            .sum()
    }
    fn near(actual: f64, expected: f64) {
        assert!((actual - expected).abs() < 1e-7, "{actual} != {expected}");
    }
    #[test]
    #[allow(
        clippy::float_cmp,
        reason = "The authored fixture verifies exact coordinates or discrete output properties."
    )]
    fn hollow_extrusion_has_real_caps_cavity_and_volume() {
        let scene = parse(&fixture(
            "#20=IFCEXTRUDEDAREASOLID(#21,$,#22,2.);
            #21=IFCRECTANGLEHOLLOWPROFILEDEF(.AREA.,$,$,4.,4.,1.,$,$);
            #22=IFCDIRECTION((0.,0.,1.));",
        ))
        .unwrap();
        near(volume(&scene), 24.);
        let cap_area: f64 = scene
            .triangles
            .iter()
            .filter(|t| t.vertices.iter().all(|p| p.z == 2.))
            .map(|t| {
                (t.vertices[1] - t.vertices[0])
                    .cross(t.vertices[2] - t.vertices[0])
                    .length()
                    / 2.
            })
            .sum();
        near(cap_area, 12.);
        assert!(crate::render::render(&scene, &crate::render::RenderOptions::default()).is_ok());
    }
    #[test]
    fn mirrored_derived_profile_retains_outward_winding() {
        let scene = parse(&fixture(
            "#20=IFCEXTRUDEDAREASOLID(#21,$,#26,2.);
            #21=IFCDERIVEDPROFILEDEF(.AREA.,$,#22,#23,$);
            #22=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,2.,2.);
            #23=IFCCARTESIANTRANSFORMATIONOPERATOR2D($,#24,#25,1.);
            #24=IFCDIRECTION((0.,-1.));#25=IFCCARTESIANPOINT((0.,0.));
            #26=IFCDIRECTION((0.,0.,1.));",
        ))
        .unwrap();
        near(volume(&scene), 8.);
    }
    #[test]
    fn mapped_geometry_uses_source_frame_and_nonuniform_mirroring() {
        let scene = parse(&fixture(
            "#20=IFCMAPPEDITEM(#21,#25);
            #21=IFCREPRESENTATIONMAP(#22,#23);#22=IFCAXIS2PLACEMENT3D(#24,$,$);
            #24=IFCCARTESIANPOINT((10.,0.,0.));
            #23=IFCSHAPEREPRESENTATION($,'Body','CSG',(#30));
            #25=IFCCARTESIANTRANSFORMATIONOPERATOR3DNONUNIFORM($,#26,#27,2.,$,3.,4.);
            #26=IFCDIRECTION((0.,-1.,0.));#27=IFCCARTESIANPOINT((5.,0.,0.));
            #30=IFCBLOCK(#2,1.,1.,1.);",
        ))
        .unwrap();
        near(volume(&scene), 24.);
        let points: Vec<_> = scene.triangles.iter().flat_map(|t| t.vertices).collect();
        near(
            points.iter().map(|p| p.x).fold(f64::INFINITY, f64::min),
            25.,
        );
        near(
            points.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max),
            27.,
        );
        near(
            points.iter().map(|p| p.y).fold(f64::INFINITY, f64::min),
            -3.,
        );
        near(
            points.iter().map(|p| p.z).fold(f64::NEG_INFINITY, f64::max),
            4.,
        );
    }
    #[test]
    fn tessellation_pn_index_and_indexed_colors_are_validated() {
        let source = fixture(
            "#20=IFCTRIANGULATEDFACESET(#21,$,.F.,((1,2,3)),(3,1,2));
            #21=IFCCARTESIANPOINTLIST3D(((0.,0.,0.),(1.,0.,0.),(0.,1.,0.)),$);
            #22=IFCINDEXEDCOLOURMAP(#20,$,#23,(1));#23=IFCCOLOURRGBLIST(((1.,0.,0.)));",
        );
        let scene = parse(&source).unwrap();
        assert_eq!(scene.triangles.len(), 1);
        assert_eq!(scene.triangles[0].vertices[0], Vec3::new(0., 1., 0.));
        assert_eq!(scene.triangles[0].color, Some([255, 0, 0]));
        assert!(parse(&source.replace("(3,1,2)", "(3,1,9)")).is_err());
        assert!(parse(&source.replace("((1,2,3))", "((0,2,3))")).is_err());
    }
    #[test]
    fn solid_boolean_operations_preserve_analytic_box_volumes() {
        for (operator, expected) in [("UNION", 1.5), ("INTERSECTION", 0.5), ("DIFFERENCE", 0.5)] {
            let scene = parse(&fixture(&format!(
                "#20=IFCBOOLEANRESULT(.{operator}.,#21,#22);
                #21=IFCBLOCK(#2,1.,1.,1.);#22=IFCBLOCK(#23,1.,1.,1.);
                #23=IFCAXIS2PLACEMENT3D(#24,$,$);#24=IFCCARTESIANPOINT((0.5,0.,0.));"
            )))
            .unwrap();
            near(volume(&scene), expected);
        }
    }
    #[test]
    fn halfspace_clipping_obeys_ifc_agreement_flag_and_caps_the_cut() {
        for (agreement, minimum, maximum) in [("T", 0.5, 1.), ("F", 0., 0.5)] {
            let scene = parse(&fixture(&format!(
                "#20=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#21,#22);
                #21=IFCBLOCK(#2,1.,1.,1.);#22=IFCHALFSPACESOLID(#23,.{agreement}.);
                #23=IFCPLANE(#24);#24=IFCAXIS2PLACEMENT3D(#25,$,$);
                #25=IFCCARTESIANPOINT((0.,0.,0.5));"
            )))
            .unwrap();
            near(volume(&scene), 0.5);
            let positions: Vec<_> = scene.triangles.iter().flat_map(|t| t.vertices).collect();
            near(
                positions.iter().map(|p| p.z).fold(f64::INFINITY, f64::min),
                minimum,
            );
            near(
                positions
                    .iter()
                    .map(|p| p.z)
                    .fold(f64::NEG_INFINITY, f64::max),
                maximum,
            );
        }
    }
    #[test]
    fn revolution_converts_project_length_and_angle_units() {
        let scene = parse(&fixture(
            "#20=IFCREVOLVEDAREASOLID(#21,$,#24,360.);
            #21=IFCRECTANGLEPROFILEDEF(.AREA.,$,#22,1000.,1000.);
            #22=IFCAXIS2PLACEMENT2D(#23,$);#23=IFCCARTESIANPOINT((2000.,0.));
            #24=IFCAXIS1PLACEMENT(#1,#25);#25=IFCDIRECTION((0.,1.,0.));
            #90=IFCPROJECT('project',$,$,$,$,$,$,$,#91);
            #91=IFCUNITASSIGNMENT((#92,#93));#92=IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.);
            #93=IFCCONVERSIONBASEDUNIT(#99,.PLANEANGLEUNIT.,'degree',#94);
            #94=IFCMEASUREWITHUNIT(IFCPLANEANGLEMEASURE(0.017453292519943295),#95);
            #95=IFCSIUNIT(*,.PLANEANGLEUNIT.,$,.RADIAN.);
            #99=IFCDIMENSIONALEXPONENTS(0,0,0,0,0,0,0);",
        ))
        .unwrap();
        assert!((volume(&scene) - 4. * PI).abs() < 0.01);
        let radius = scene
            .triangles
            .iter()
            .flat_map(|t| t.vertices)
            .map(|p| (p.x * p.x + p.z * p.z).sqrt())
            .fold(0_f64, f64::max);
        near(radius, 2.5);
    }
    #[test]
    #[allow(
        clippy::float_cmp,
        reason = "The authored fixture verifies exact coordinates or discrete output properties."
    )]
    fn relational_opening_is_subtracted_in_absolute_product_placement() {
        let scene = parse(&fixture(
            "#20=IFCBLOCK(#2,4.,4.,1.);
            #30=IFCOPENINGELEMENT('cut',$,$,$,$,#31,#32,$,$);
            #31=IFCLOCALPLACEMENT(#3,#33);#33=IFCAXIS2PLACEMENT3D(#34,$,$);
            #34=IFCCARTESIANPOINT((1.,1.,-1.));
            #32=IFCPRODUCTDEFINITIONSHAPE($,$,(#35));
            #35=IFCSHAPEREPRESENTATION($,'Body','CSG',(#36));#36=IFCBLOCK(#2,2.,2.,3.);
            #40=IFCRELVOIDSELEMENT('relation',$,$,$,#4,#30);",
        ))
        .unwrap();
        near(volume(&scene), 12.);
        assert!(
            scene
                .triangles
                .iter()
                .any(|t| t.vertices.iter().all(|p| p.x == 1.)
                    && t.vertices.iter().all(|p| (1. ..=3.).contains(&p.y)))
        );
    }
    #[test]
    fn invalid_and_unsupported_geometry_returns_errors() {
        assert!(parse("not IFC").is_err());
        assert!(parse(&fixture("#20=IFCSPHERE(#2,-1.);")).is_err());
        assert!(parse(&fixture("#20=IFCSECTIONEDSOLIDHORIZONTAL($,$,$,$);")).is_err());
        let cyclic = fixture("#20=IFCBLOCK(#2,1.,1.,1.);")
            .replace("IFCLOCALPLACEMENT($,#2)", "IFCLOCALPLACEMENT(#3,#2)");
        assert!(parse(&cyclic).is_err());
        assert!(
            parse(&fixture(
                "#20=IFCTRIANGULATEDFACESET(#999,$,.F.,((1,2,3)),$);"
            ))
            .is_err()
        );
    }
}