polysmelt 0.16.0

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

use std::collections::HashMap;
use std::rc::Rc;

use crate::{Context, Result};

use super::model::{self, Model};
use super::reader::{Reader, byte_at, bytes_at, f64_at, marker_at, u16_at, u32_at};

/// `SketchUp` 3 predates several fields every later file carries.
const FIRST_V4: u32 = 4;
/// The texture image became an object of its own (with a slot) in `SketchUp` 6.
const FIRST_DIB_OBJECT: u32 = 6;
/// `SketchUp` 3 and 4 instances carry no name.
const FIRST_NAMED_INSTANCE: u32 = 5;
/// How deep objects may nest inside each other. Real files nest a few levels per component level; the cap keeps a
/// hostile file from exhausting the stack.
const MAX_DEPTH: usize = 160;
/// How deep attribute arrays may nest, for the same reason.
const MAX_ATTR_DEPTH: usize = 16;
/// Widest zero padding seen between `SketchUp` 2020's filler string and the count after it.
const MAX_V20_FILLER_PAD: usize = 29;
/// Where the throwaway slot-base probes number from, far above any real slot.
const PROBE_BASE: u64 = 1 << 20;
/// A tag's line style (`SketchUp` 2019 on) opens with its entity preamble twice in 2019, once from 2020.
const FIRST_SINGLE_PREAMBLE_LINE_STYLE: u32 = 20;

#[derive(Debug, Default, Clone, Copy)]
struct Draw {
    mat: u64,
    hidden: bool,
    /// An edge drawn without a line (Soften).
    soft: bool,
    /// An edge the faces either side shade smoothly across.
    smooth: bool,
    layer: u64,
}

#[derive(Debug, Default)]
struct TexBlock {
    dib: Option<u64>,
    inline: Option<(usize, usize)>,
    tile: [f64; 2],
    rgb: [u8; 3],
    /// The image's average color.
    average: [u8; 3],
    /// A colorized copy of a texture: shown tinted toward `rgb`.
    colorize: bool,
    opacity: f64,
}

#[derive(Debug)]
struct MatRec {
    name: String,
    rgba: [u8; 4],
    opacity: f64,
    tex: Option<TexBlock>,
}

#[derive(Debug)]
struct FaceRec {
    attrs: Option<u64>,
    draw: Draw,
    normal: [f64; 3],
    loops: Vec<Rc<Value>>,
    back_mat: u64,
}

#[derive(Debug)]
struct InstRec {
    draw: Draw,
    def: u64,
    xf: [f64; 13],
    name: String,
}

/// What a read object decodes to. Records that only matter for alignment are `Other`.
#[derive(Debug, Default)]
enum Value {
    #[default]
    Other,
    Vertex([f64; 3]),
    Edge {
        v1: u64,
        v2: u64,
        smooth: bool,
    },
    EdgeUse {
        edge: u64,
        sense: bool,
    },
    Loop(Vec<Rc<Value>>),
    Face(Box<FaceRec>),
    Attrs(Vec<Obj>),
    Layer {
        hidden: bool,
    },
    Material(Box<MatRec>),
    Dib {
        start: usize,
        len: usize,
    },
    /// The front's and the back's positioned-texture matrices.
    Ftc(Box<[[f64; 9]; 2]>),
    Definition {
        name: String,
        ents: Vec<Obj>,
    },
    Instance(Box<InstRec>),
}

/// One object reference as read: its slot, class name (empty for a null reference) and value.
#[derive(Debug, Clone)]
struct Obj {
    slot: u64,
    name: Rc<str>,
    v: Option<Rc<Value>>,
}

#[derive(Debug)]
struct Entry {
    cls: bool,
    name: Rc<str>,
    v: Option<Rc<Value>>,
}

/// True when the bytes at `p` are a class reference to `slot`, in either the short or the escaped form.
fn is_class_ref(d: &[u8], p: usize, slot: u64) -> bool {
    if slot <= 0x7fff {
        return u16_at(d, p).is_some_and(|t| u64::from(t) == (0x8000 | slot));
    }
    u16_at(d, p) == Some(0x7fff) && u32_at(d, p + 2).is_some_and(|b| u64::from(b) == (0x8000_0000 | slot))
}

/// Whether the text whose font ends at `pos` is anchored to an entity, which adds a connection block.
fn anchored_text_connection(d: &[u8], pos: usize) -> bool {
    u32_at(d, pos + 20) == Some(4) && u32_at(d, pos + 16).is_some_and(|t| (2..=15).contains(&t))
}

/// The first empty string record within 12 bytes of `count_pos`: `SketchUp` 2020's filler.
fn v20_filler_marker(d: &[u8], count_pos: usize) -> Option<usize> {
    let at = (count_pos..count_pos + 12)
        .take_while(|i| i + 4 <= d.len())
        .find(|&i| marker_at(d, i))?;
    (byte_at(d, at + 3) == Some(0)).then_some(at)
}

/// `SketchUp` 2020's layout of a model with no definitions and no root entities: the filler, 13 zero bytes, then a
/// zero root count. Returns where that count sits.
fn find_empty_root_after_v20_filler(d: &[u8], count_pos: usize) -> Option<usize> {
    let marker = v20_filler_marker(d, count_pos)?;
    let root_count_at = marker + 4 + 13;
    let tail = d.get(marker + 3..root_count_at + 4)?;
    tail.iter().all(|&b| b == 0).then_some(root_count_at)
}

struct Archive<'a> {
    r: Reader<'a>,
    ver: u32,
    pid: bool,
    next: u64,
    base: u64,
    current_loop: u64,
    slots: HashMap<u64, Entry>,
    class_slot: HashMap<String, u64>,
    /// Where each class was first declared in full, in the walker's numbering.
    first_class_slot: HashMap<String, u64>,
    /// Whether a tag's line style has been read.
    seen_line_style: bool,
    /// Store-map indices the writer burned without writing bytes (annotation connection points), as
    /// (file band start, width). References past a band run ahead of the walker's numbering.
    burns: Vec<(u64, u64)>,
    cum_delta: u64,
    annot_watermark: Option<u64>,
    burn_stack: Vec<u32>,
    inline_stack: Vec<Vec<u64>>,
    cline_tail: Option<usize>,
    depth: usize,
    empty: Rc<str>,
}

impl std::fmt::Debug for Archive<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Archive")
            .field("p", &self.r.p)
            .field("ver", &self.ver)
            .finish_non_exhaustive()
    }
}

impl<'a> Archive<'a> {
    fn new(d: &'a [u8], ver: u32) -> Self {
        Self {
            r: Reader::new(d),
            ver,
            pid: ver >= 17,
            next: 0,
            base: 0,
            current_loop: 0,
            slots: HashMap::new(),
            class_slot: HashMap::new(),
            first_class_slot: HashMap::new(),
            seen_line_style: false,
            burns: Vec::new(),
            cum_delta: 0,
            annot_watermark: None,
            burn_stack: Vec::new(),
            inline_stack: Vec::new(),
            cline_tail: None,
            depth: 0,
            empty: Rc::from(""),
        }
    }

    fn d(&self) -> &'a [u8] {
        self.r.d
    }

    fn null(&self) -> Obj {
        Obj {
            slot: 0,
            name: Rc::clone(&self.empty),
            v: None,
        }
    }

    fn alloc(&mut self, e: Entry) -> u64 {
        let s = self.next;
        self.next += 1;
        self.slots.insert(s, e);
        s
    }

    fn object(&mut self, expect: Option<&str>) -> Result<Obj> {
        let tag = self.r.u16()?;
        match tag {
            0 => Ok(self.null()),
            0x7fff => {
                let big = self.r.u32()?;
                if big & 0x8000_0000 != 0 {
                    self.new_class_ref(u64::from(big & 0x7fff_ffff), expect)
                } else {
                    self.back(u64::from(big))
                }
            }
            0xffff => {
                let _schema = self.r.u16()?;
                let n = self.r.u16()?;
                ensure!(n <= 40, "implausible legacy class name");
                let name: Rc<str> = Rc::from(String::from_utf8_lossy(self.r.raw(usize::from(n))?).as_ref());
                let cs = self.alloc(Entry {
                    cls: true,
                    name: Rc::clone(&name),
                    v: None,
                });
                self.class_slot.insert(name.to_string(), cs);
                self.first_class_slot.entry(name.to_string()).or_insert(cs);
                self.new_obj(name)
            }
            t if t & 0x8000 != 0 => self.new_class_ref(u64::from(t & 0x7fff), expect),
            t => self.back(u64::from(t)),
        }
    }

    fn new_class_ref(&mut self, s: u64, expect: Option<&str>) -> Result<Obj> {
        if let std::collections::hash_map::Entry::Vacant(slot) = self.slots.entry(s) {
            let name = expect.context("unknown legacy class slot")?;
            slot.insert(Entry {
                cls: true,
                name: Rc::from(name),
                v: None,
            });
            self.class_slot.insert(name.to_owned(), s);
        }
        let entry = self.slots.get(&s).context("unknown legacy class slot")?;
        ensure!(entry.cls, "class ref points to an object");
        let name = Rc::clone(&entry.name);
        self.new_obj(name)
    }

    /// Maps a file store-map index to the walker's numbering through the burn bands; `None` inside a band.
    fn translate_ref(&self, slot: u64) -> Option<u64> {
        let mut offset = 0;
        for &(start, width) in &self.burns {
            if slot < start {
                break;
            }
            if slot < start + width {
                return None;
            }
            offset += width;
        }
        Some(slot - offset)
    }

    fn back(&self, mut s: u64) -> Result<Obj> {
        if self.burns.first().is_some_and(|b| s >= b.0) {
            match self.translate_ref(s) {
                Some(w) => s = w,
                None => {
                    return Ok(Obj {
                        slot: s,
                        name: Rc::from("reserved"),
                        v: None,
                    });
                }
            }
        }
        match self.slots.get(&s) {
            None if s < self.base => Ok(Obj {
                slot: s,
                name: Rc::from("premodel"),
                v: None,
            }),
            None => bail!("legacy backref to unknown slot"),
            Some(e) if e.cls => bail!("legacy backref to class"),
            Some(e) => Ok(Obj {
                slot: s,
                name: Rc::clone(&e.name),
                v: e.v.clone(),
            }),
        }
    }

    fn register_burn(&mut self, delta: u64) -> Result<()> {
        let watermark = self.annot_watermark.take().context("burn without an annotation")?;
        self.burns.push((watermark + self.cum_delta, delta));
        self.cum_delta += delta;
        if let Some(credit) = self.burn_stack.last_mut() {
            *credit += 1;
        }
        Ok(())
    }

    /// A reference to an entity that may point forward, past the walk (annotations are written before what they
    /// label). `allow_inline` lets it be a whole new object.
    fn entity_ref(&mut self, allow_inline: bool) -> Result<Option<u64>> {
        let start = self.r.p;
        let tag = self.r.u16()?;
        if tag == 0 {
            return Ok(None);
        }
        if tag == 0x7fff {
            let big = self.r.u32()?;
            if big & 0x8000_0000 == 0 {
                return Ok(Some(u64::from(big)));
            }
        } else if tag != 0xffff && tag & 0x8000 == 0 {
            return Ok(Some(u64::from(tag)));
        }
        ensure!(allow_inline, "entity ref is a new object");
        self.r.p = start;
        Ok(Some(self.object(None)?.slot))
    }

    /// Null, a plain back-reference or the escaped form; a new object is an error here.
    fn plain_entity_ref(&mut self) -> Result<Option<u64>> {
        let tag = self.r.u16()?;
        if tag == 0 {
            return Ok(None);
        }
        if tag == 0x7fff {
            let big = self.r.u32()?;
            ensure!(big & 0x8000_0000 == 0, "entity ref is a new object");
            return Ok(Some(u64::from(big)));
        }
        ensure!(tag != 0xffff && tag & 0x8000 == 0, "entity ref is a new object");
        Ok(Some(u64::from(tag)))
    }

    /// The instance paths after an annotation's connection ref: a ref, then two counted ref lists. MFC writes an
    /// object in full the first time anything points at it, so an entry can be a whole new object.
    fn connection_paths(&mut self) -> Result<()> {
        self.plain_entity_ref()?;
        let mut firsts = Vec::new();
        for _ in 0..2 {
            let count = self.r.u32()?;
            ensure!(count <= 1000, "implausible dimension path length");
            for i in 0..count {
                let tag = self.r.peek_u16()?;
                let is_new = if tag == 0x7fff {
                    u32_at(self.d(), self.r.p + 2).context("archive ends early")? & 0x8000_0000 != 0
                } else {
                    tag == 0xffff || tag & 0x8000 != 0
                };
                if is_new {
                    let slot = self.object(None)?.slot;
                    if i == 0 {
                        firsts.push(slot);
                    }
                } else {
                    self.plain_entity_ref()?;
                }
            }
        }
        if let Some(stack) = self.inline_stack.last_mut() {
            stack.extend(firsts);
        }
        Ok(())
    }

    /// The walker slot of the back-reference at the cursor, without moving it.
    fn peek_backref(&self) -> Option<u64> {
        let d = self.d();
        let mut slot = u64::from(u16_at(d, self.r.p)?);
        if slot == 0x7fff {
            slot = u64::from(u32_at(d, self.r.p + 2)?);
            if slot & 0x8000_0000 != 0 {
                return None;
            }
        } else if slot == 0 || slot & 0x8000 != 0 {
            return None;
        }
        if self.burns.first().is_some_and(|b| slot >= b.0) {
            return self.translate_ref(slot);
        }
        Some(slot)
    }

    /// Whether the u16 at `at` starts an object read in an unambiguous form.
    fn strict_next_tag(&self, at: usize, allow_null: bool) -> bool {
        match u16_at(self.d(), at) {
            Some(0) => allow_null,
            Some(0x7fff | 0xffff) => true,
            Some(t) if t & 0x8000 != 0 => self.slots.get(&u64::from(t & 0x7fff)).is_some_and(|e| e.cls),
            None | Some(_) => false,
        }
    }

    /// The tag at `at` can legally start an object read, back-references within the allocated range included.
    fn plausible_list_tag(&self, at: usize) -> bool {
        match u16_at(self.d(), at) {
            None => false,
            Some(0 | 0x7fff | 0xffff) => true,
            Some(t) if t & 0x8000 != 0 => self.slots.get(&u64::from(t & 0x7fff)).is_some_and(|e| e.cls),
            Some(t) => u64::from(t) < self.next,
        }
    }

    /// `SketchUp` 2020 writes an undocumented filler (an empty string then zero padding) ahead of some counts, which
    /// leaves the reader early. Finds the real count behind it and moves the cursor past it.
    fn retry_v20(&mut self, count_pos: usize, limit: u32) -> Option<u32> {
        let d = self.d();
        let marker = v20_filler_marker(d, count_pos)?;
        for pad in (1..=MAX_V20_FILLER_PAD).step_by(4) {
            let at = marker + 4 + pad;
            let count = u32_at(d, at)?;
            if count > 0 && count <= limit && self.plausible_list_tag(at + 4) {
                self.r.p = at + 4;
                return Some(count);
            }
        }
        None
    }

    /// The entity preamble: an attribute-container reference, then from `SketchUp` 2017 a persistent id. Returns
    /// the container's slot and the class the reference named.
    fn preamble(&mut self) -> Result<(Option<u64>, Rc<str>)> {
        let attrs = self.object(Some("CAttributeContainer"))?;
        if self.pid {
            let mask = self.r.u8()?;
            self.r.skip(mask.count_ones() as usize)?;
        }
        let slot = (!attrs.name.is_empty()).then_some(attrs.slot);
        Ok((slot, attrs.name))
    }

    /// The preamble for records that carry none in `SketchUp` 3: vertex, loop, edge use, material, layer.
    fn early_preamble(&mut self) -> Result<Option<u64>> {
        if self.ver < FIRST_V4 {
            return Ok(None);
        }
        Ok(self.preamble()?.0)
    }

    fn draw(&mut self) -> Result<Draw> {
        let v3 = self.ver < FIRST_V4;
        let b = self.r.raw(if v3 {
            5
        } else if self.ver < 5 {
            7
        } else {
            8
        })?;
        let mut out = Draw::default();
        // Material, hidden, casts and receives shadows, soft, smooth, then (from SketchUp 5) locked.
        if !v3 {
            out.mat = u64::from(u16::from_le_bytes([b[0], b[1]]));
            out.hidden = b[2] != 0;
            out.soft = b[5] != 0;
            out.smooth = b[6] != 0;
        }
        // The layer is normally a u16 id, but can be the layer object itself: inline on first use, an escaped
        // back-reference after.
        let tag = self.r.peek_u16()?;
        let lay_cs = self.class_slot.get("CLayer").copied();
        if lay_cs.is_some_and(|cs| u64::from(tag) == (0x8000 | cs)) {
            self.object(Some("CLayer"))?;
        } else if tag == 0x7fff {
            self.r.u16()?;
            ensure!(self.r.u32()? & 0x8000_0000 == 0, "drawbase layer: unexpected class");
        } else {
            out.layer = u64::from(self.r.u16()?);
        }
        Ok(out)
    }

    /// The textured-material payload shared by a textured `CMaterial` and a color-by-layer `CLayer`.
    fn texture_block(&mut self) -> Result<TexBlock> {
        let mut t = TexBlock::default();
        if self.ver < FIRST_DIB_OBJECT {
            self.r.u32()?;
            let z = self.r.u32()? as usize;
            ensure!(z <= self.d().len(), "implausible dib length");
            t.inline = Some((self.r.p, z));
            self.r.skip(z)?;
        } else {
            // The caller read the flag as a u16; its high byte opens the texture's own preamble.
            self.r.p = self.r.p.checked_sub(1).context("archive offset underflows")?;
            self.preamble()?;
            let dib = self.object(Some("CDib"))?;
            t.dib = (!dib.name.is_empty()).then_some(dib.slot);
        }
        let begin = self.r.p;
        let limit = self.d().len().min(begin + 28);
        let gap = (begin..limit.saturating_sub(2))
            .find(|&m| marker_at(self.d(), m))
            .map_or(limit - begin, |m| m - begin);
        match gap {
            20 => {
                self.r.u32()?;
            }
            16 => {}
            _ => bail!("texture size block misaligned"),
        }
        t.tile = self.r.f64s::<2>()?;
        self.r.utf16()?;
        // the image's average RGBA, a zero, then the material's own RGBA
        let c = self.r.raw(9)?;
        t.average = [c[0], c[1], c[2]];
        t.rgb = [c[5], c[6], c[7]];
        self.r.utf16()?;
        // the material type (2 for a colorized texture) and the colorize mode
        let kind = self.r.raw(8)?;
        t.colorize = kind[0] == 2;
        t.opacity = self.r.f64()?;
        if self.r.u8()? == 0 {
            t.opacity = 0.0;
        }
        Ok(t)
    }

    /// A `CLayer` record at `at`: its class declaration, a reference to its known class, or (for the throwaway
    /// probe) any short class reference.
    fn clayer_record_at(&self, at: usize, unmatched_class_ref: bool) -> bool {
        let d = self.d();
        let Some(tag) = u16_at(d, at) else { return false };
        if tag == 0xffff && u16_at(d, at + 4) == Some(6) && bytes_at(d, at + 6, b"CLayer") {
            return true;
        }
        if self.class_slot.get("CLayer").is_some_and(|&cs| is_class_ref(d, at, cs)) {
            return true;
        }
        unmatched_class_ref && tag & 0x8000 != 0 && tag != 0xffff
    }

    /// The line style a color layer may point at after its tail: nothing (0) for a plain tag, the style in full
    /// where a tag first uses it (a `CCustomLineStyle` class declaration, or a reference to that class once
    /// known), or a back-reference to a style an earlier tag wrote. Anything else is left for the callers.
    ///
    /// The slot-base probe numbers from [`PROBE_BASE`], so the file's own references can't be looked up there: a
    /// class reference is matched by its distance from the `CLayer` class (the same in both numberings), and once
    /// a style has been read, any other plain object reference here is a back-reference to it.
    fn read_clayer_line_style(&mut self) -> Result<()> {
        const CLASS: &str = "CCustomLineStyle";
        let d = self.d();
        let p = self.r.p;
        let Some(tag) = u16_at(d, p) else { return Ok(()) };
        if tag == 0xffff {
            if u16_at(d, p + 4) != Some(16) || !bytes_at(d, p + 6, CLASS.as_bytes()) {
                return Ok(());
            }
        } else if tag & 0x8000 != 0 {
            let Some(&cs) = self.class_slot.get(CLASS) else {
                return Ok(());
            };
            let shift = match (self.class_slot.get("CLayer"), self.first_class_slot.get("CLayer")) {
                (Some(&now), Some(&first)) => i128::from(now) - i128::from(first),
                _ => 0,
            };
            if i128::from(cs) + shift != i128::from(tag & 0x7fff) {
                return Ok(());
            }
        } else if tag == 0 || tag == 0x7fff {
            return Ok(());
        } else if self.base >= PROBE_BASE {
            if !self.seen_line_style {
                return Ok(());
            }
        } else if !self
            .slots
            .get(&u64::from(tag))
            .is_some_and(|e| !e.cls && &*e.name == CLASS)
        {
            return Ok(());
        }
        self.object(Some(CLASS))?;
        Ok(())
    }

    /// Some v18 files follow a color layer with 12 zero bytes and a u32 before the next `CLayer`.
    fn skip_clayer_color_ext(&mut self) {
        let p = self.r.p;
        let Some(pad) = self.d().get(p..p + 18) else { return };
        if pad[..12].iter().all(|&b| b == 0) && self.clayer_record_at(p + 16, true) {
            self.r.p += 16;
        }
    }

    /// v18's Layer0 after a custom tag carries a parent reference; consume it only when it and the word after it
    /// both point at layers.
    fn skip_clayer_parent_ref(&mut self, me: u64) {
        let d = self.d();
        let (Some(a), Some(b)) = (u16_at(d, self.r.p), u16_at(d, self.r.p + 2)) else {
            return;
        };
        let plain = |t: u16| t != 0 && t & 0x8000 == 0 && t != 0x7fff;
        if !plain(a) || !plain(b) || u64::from(a) == me {
            return;
        }
        let is_layer = |t: u16| {
            self.slots
                .get(&u64::from(t))
                .is_some_and(|e| !e.cls && &*e.name == "CLayer")
        };
        if is_layer(a) && is_layer(b) {
            self.r.p += 2;
        }
    }

    /// Layer records past the declared count (and null separators), up to the definition-list anchor.
    fn collect_trailing_layers(&mut self, out: &mut Vec<Obj>, unmatched_class_ref: bool) -> Result<()> {
        while let Some(tag) = u16_at(self.d(), self.r.p) {
            if tag == 0 {
                self.r.p += 2;
                continue;
            }
            if !self.clayer_record_at(self.r.p, unmatched_class_ref) {
                break;
            }
            let q = self.object(Some("CLayer"))?;
            if q.v.is_some() {
                out.push(q);
            }
        }
        Ok(())
    }

    fn new_obj(&mut self, name: Rc<str>) -> Result<Obj> {
        let slot = self.alloc(Entry {
            cls: false,
            name: Rc::clone(&name),
            v: None,
        });
        ensure!(self.depth < MAX_DEPTH, "objects nest too deeply");
        self.depth += 1;
        let read = self.read(&name, slot);
        self.depth -= 1;
        let v = Rc::new(read?);
        if let Some(e) = self.slots.get_mut(&slot) {
            e.v = Some(Rc::clone(&v));
        }
        if matches!(&*name, "CDimensionLinear" | "CText") {
            self.annot_watermark = Some(self.next);
        }
        Ok(Obj { slot, name, v: Some(v) })
    }

    fn read(&mut self, name: &str, me: u64) -> Result<Value> {
        match name {
            "CVertex" => {
                self.early_preamble()?;
                Ok(Value::Vertex(self.r.f64s::<3>()?))
            }
            "CEdge" => {
                self.preamble()?;
                let draw = self.draw()?;
                let v1 = self.object(Some("CVertex"))?.slot;
                let v2 = self.object(Some("CVertex"))?.slot;
                self.object(None)?; // the curve the edge belongs to
                Ok(Value::Edge {
                    v1,
                    v2,
                    smooth: draw.smooth,
                })
            }
            "CCurve" => {
                self.preamble()?;
                self.r.skip(5)?;
                Ok(Value::Other)
            }
            "CArcCurve" => {
                self.preamble()?;
                self.r.skip(5 + 14 * 8)?;
                Ok(Value::Other)
            }
            "CEdgeUse" => self.read_edge_use(),
            "CLoop" => self.read_loop(me),
            "CFace" => self.read_face(),
            "CAttributeContainer" => {
                self.preamble()?;
                let mut ents = Vec::new();
                while u16_at(self.d(), self.r.p).is_some_and(|t| t != 0) {
                    ents.push(self.object(Some("CAttributeNamed"))?);
                }
                self.r.u16()?;
                Ok(Value::Attrs(ents))
            }
            "CAttributeNamed" => self.read_attribute_named(),
            "CLayer" => self.read_layer(me),
            "CMaterial" => self.read_material(),
            "CDib" => {
                self.r.u32()?;
                let len = self.r.u32()? as usize;
                let start = self.r.p;
                self.r.skip(len)?;
                Ok(Value::Dib { start, len })
            }
            "CFaceTextureCoords" => self.read_texture_coords(),
            "CCamera" => {
                self.r.skip(137)?;
                self.r.u16()?;
                self.r.utf16()?;
                self.r.skip(if self.ver >= 6 { 33 } else { 10 })?;
                Ok(Value::Other)
            }
            "CThumbnail" => {
                self.preamble()?;
                if self.ver < FIRST_V4 {
                    self.r.skip(129)?;
                } else {
                    self.object(Some("CCamera"))?;
                    if self.ver >= 6 {
                        self.object(Some("CDib"))?;
                    }
                }
                Ok(Value::Other)
            }
            "CImage" => self.read_image(),
            "CRelationship" => {
                self.preamble()?;
                self.entity_ref(false)?;
                self.entity_ref(false)?;
                Ok(Value::Other)
            }
            "CConstructionLine" => self.read_construction_line(),
            "CConstructionPoint" => {
                self.preamble()?;
                self.draw()?;
                self.r.skip(6 * 8 + 1)?;
                Ok(Value::Other)
            }
            "CSectionPlane" => self.read_section_plane(),
            "CSkFont" => {
                self.object(Some("CAttributeContainer"))?;
                if self.pid {
                    let mask = self.r.u8()?;
                    self.r.skip(mask.count_ones() as usize)?;
                }
                self.r.utf16()?;
                self.r.skip(15)?;
                Ok(Value::Other)
            }
            "CDimensionLinear" => self.read_dimension(),
            "CText" => self.read_text(),
            "CComponentDefinition" => self.read_definition(),
            "CComponentInstance" | "CGroup" => self.read_instance(),
            "CCustomLineStyle" => {
                // A tag's line style ("Dash", "Solid Basic", ...): its name, its dash pattern and three doubles.
                self.early_preamble()?;
                if self.ver < FIRST_SINGLE_PREAMBLE_LINE_STYLE {
                    self.early_preamble()?;
                }
                self.r.utf16()?;
                self.r.utf16()?;
                self.r.skip(3 * 8)?;
                self.seen_line_style = true;
                Ok(Value::Other)
            }
            other => bail!("no legacy reader for {other}"),
        }
    }

    fn read_edge_use(&mut self) -> Result<Value> {
        self.early_preamble()?;
        let edge = self.object(Some("CEdge"))?.slot;
        let sense = self.r.u8()? != 0;
        // The parent-loop back-reference keeps the walk honest. After annotations it can sit ahead of the walker's
        // numbering by the indices the writer burned, which is a correction, not a misparse.
        let p0 = self.r.p;
        let tag = self.r.u16()?;
        let parent = if tag == 0x7fff {
            let big = self.r.u32()?;
            ensure!(big & 0x8000_0000 == 0, "edge-use parent is a new object");
            Some(u64::from(big))
        } else {
            ensure!(tag != 0xffff && tag & 0x8000 == 0, "edge-use parent is a new object");
            (tag != 0).then_some(u64::from(tag))
        };
        let expected = self.current_loop + self.cum_delta;
        if parent != Some(expected) {
            let delta = parent.and_then(|p| p.checked_sub(expected)).unwrap_or(0);
            if delta > 0 && delta <= 4096 && self.annot_watermark.is_some() {
                self.register_burn(delta)?;
            } else {
                self.r.p = p0;
                bail!("edge-use parent mismatch");
            }
        }
        Ok(Value::EdgeUse { edge, sense })
    }

    fn read_loop(&mut self, me: u64) -> Result<Value> {
        let old = self.current_loop;
        self.current_loop = me;
        let uses = self.read_loop_body();
        self.current_loop = old;
        Ok(Value::Loop(uses?))
    }

    fn read_loop_body(&mut self) -> Result<Vec<Rc<Value>>> {
        self.early_preamble()?;
        self.r.skip(2)?;
        let mut uses = Vec::new();
        while u16_at(self.d(), self.r.p).is_some_and(|t| t != 0) {
            if let Some(v) = self.object(Some("CEdgeUse"))?.v {
                uses.push(v);
            }
        }
        self.r.u16()?;
        Ok(uses)
    }

    fn read_face(&mut self) -> Result<Value> {
        let (mut attrs, lead_cls) = self.preamble()?;
        let mut draw = self.draw()?;
        if self.ver < FIRST_V4 && &*lead_cls == "CMaterial" {
            // SketchUp 3 opens a face with its front material, not an attribute container.
            if let Some(m) = attrs.take() {
                draw.mat = m;
            }
        }
        let plane = self.r.f64s::<4>()?;
        let count = self.r.u32()?;
        ensure!(count <= 10_000, "implausible loop count");
        let mut loops = Vec::new();
        for _ in 0..count {
            if let Some(v) = self.object(Some("CLoop"))?.v {
                loops.push(v);
            }
        }
        let back_mat = u64::from(self.r.u16()?);
        Ok(Value::Face(Box::new(FaceRec {
            attrs,
            draw,
            normal: [plane[0], plane[1], plane[2]],
            loops,
            back_mat,
        })))
    }

    fn read_attribute_named(&mut self) -> Result<Value> {
        self.preamble()?;
        self.r.skip(4)?;
        self.r.utf16()?;
        loop {
            if self.r.utf16()?.is_empty() {
                break;
            }
            let t = self.r.u8()?;
            self.skip_typed(t, 0)?;
        }
        // SketchUp 6 ends the record at the empty key; 7 added a u32.
        if self.ver >= 7 {
            self.r.u32()?;
        }
        Ok(Value::Other)
    }

    fn skip_typed(&mut self, t: u8, depth: usize) -> Result<()> {
        match t {
            0 => {}
            7 => self.r.skip(1)?,
            4 | 9 => self.r.skip(4)?,
            6 | 12 => self.r.skip(8)?,
            10 => {
                self.r.utf16()?;
            }
            17 | 18 => self.r.skip(24)?,
            11 => {
                ensure!(depth < MAX_ATTR_DEPTH, "attribute arrays nest too deeply");
                let n = self.r.u32()?;
                ensure!(n <= 100_000, "attr array too large");
                for _ in 0..n {
                    let t = self.r.u8()?;
                    self.skip_typed(t, depth + 1)?;
                }
            }
            _ => bail!("unknown legacy attribute type {t}"),
        }
        Ok(())
    }

    fn read_layer(&mut self, me: u64) -> Result<Value> {
        self.early_preamble()?;
        self.r.utf16()?;
        let mut hidden = None;
        let mut mid = 0;
        while mid < 8 && !self.r.marker() {
            let b = self.r.u8()?;
            hidden.get_or_insert(b);
            mid += 1;
        }
        self.r.utf16()?;
        let flags = self.r.u16()?;
        if flags & 0x00ff != 0 {
            // color-by-layer with a textured material
            self.texture_block()?;
            self.r.skip(4)?;
        } else {
            self.r.skip(4)?;
            self.r.utf16()?;
            self.r.skip(if self.ver < FIRST_V4 { 17 } else { 21 })?;
            self.read_clayer_line_style()?;
            self.skip_clayer_color_ext();
            self.skip_clayer_parent_ref(me);
        }
        Ok(Value::Layer {
            hidden: hidden.is_some_and(|h| h != 0),
        })
    }

    fn read_material(&mut self) -> Result<Value> {
        self.early_preamble()?;
        let name = self.r.utf16()?;
        let flag = self.r.u16()?;
        let rec = if flag == 0 {
            let c = self.r.raw(4)?;
            let rgba = [c[0], c[1], c[2], c[3]];
            self.r.utf16()?;
            self.r.skip(8)?;
            let mut opacity = self.r.f64()?;
            if self.r.u8()? == 0 {
                opacity = 0.0;
            }
            MatRec {
                name,
                rgba,
                opacity,
                tex: None,
            }
        } else {
            let t = self.texture_block()?;
            MatRec {
                name,
                rgba: [t.rgb[0], t.rgb[1], t.rgb[2], 255],
                opacity: t.opacity,
                tex: Some(t),
            }
        };
        Ok(Value::Material(Box::new(rec)))
    }

    fn read_texture_coords(&mut self) -> Result<Value> {
        self.preamble()?;
        self.r.u32()?;
        // the front's matrix sits at 0 and the back's at 12
        let a = self.r.f64s::<24>()?;
        let mut sides = [[0.0; 9]; 2];
        sides[0].copy_from_slice(&a[..9]);
        sides[1].copy_from_slice(&a[12..21]);
        for _ in 0..2 {
            let z = self.r.u32()? as usize;
            self.r
                .skip(z.checked_mul(32).context("texture point count overflows")?)?;
        }
        self.r.skip(8)?; // front and back flags
        Ok(Value::Ftc(Box::new(sides)))
    }

    fn read_image(&mut self) -> Result<Value> {
        self.preamble()?;
        let draw = self.draw()?;
        let def = self.object(None)?.slot;
        let placement = self.r.f64s::<12>()?;
        self.r.f64()?;
        self.r.utf16()?;
        self.r.skip(16)?;
        let mut xf = [0.0; 13];
        xf[..12].copy_from_slice(&placement);
        xf[12] = 1.0;
        Ok(Value::Instance(Box::new(InstRec {
            draw,
            def,
            xf,
            name: String::new(),
        })))
    }

    fn read_construction_line(&mut self) -> Result<Value> {
        self.preamble()?;
        self.draw()?;
        self.r.skip(8 * 8)?;
        // The tail length varies by the build that wrote the file; calibrate on the first guide line by finding
        // the length that lands on a legitimate next tag, then keep it.
        let tail = if let Some(t) = self.cline_tail {
            t
        } else {
            let preferred = if self.ver == 17 { 7 } else { 4 };
            let order = std::iter::once(preferred).chain([0, 4, 7].into_iter().filter(|&c| c != preferred));
            let p = self.r.p;
            let strict = order.clone().find(|&c| self.strict_next_tag(p + c, false));
            let t = strict
                .or_else(|| [4, 0, 7].into_iter().find(|&c| self.strict_next_tag(p + c, true)))
                .unwrap_or(4);
            self.cline_tail = Some(t);
            t
        };
        self.r.skip(tail)?;
        Ok(Value::Other)
    }

    fn read_section_plane(&mut self) -> Result<Value> {
        self.preamble()?;
        self.draw()?;
        let first = f64_at(self.d(), self.r.p).context("archive ends early")?;
        if first.abs() > 1.0001 {
            self.object(None)?;
        }
        self.r.skip(4 * 8)?;
        if self.r.marker() {
            self.r.utf16()?;
            self.r.utf16()?;
        }
        Ok(Value::Other)
    }

    fn read_dimension(&mut self) -> Result<Value> {
        self.preamble()?;
        self.draw()?;
        self.r.utf16()?;
        if self.ver >= 6 {
            self.object(Some("CSkFont"))?;
            self.r.skip(5)?;
        }
        for _ in 0..2 {
            self.r.skip(32)?;
            self.entity_ref(true)?;
            self.connection_paths()?;
        }
        self.r.skip(if self.ver >= 6 { 72 } else { 68 })?;
        Ok(Value::Other)
    }

    fn read_text(&mut self) -> Result<Value> {
        self.preamble()?;
        self.draw()?;
        self.object(Some("CSkFont"))?;
        if anchored_text_connection(self.d(), self.r.p) {
            self.r.skip(16 + 32)?;
            self.entity_ref(false)?;
            self.connection_paths()?;
        }
        let d = self.d();
        let start = self.r.p;
        let limit = d.len().min(start + 512);
        let found = (start..limit.saturating_sub(13))
            .find(|&q| {
                d.get(q..q + 14).is_some_and(|w| {
                    w[..4] == [1, 0, 0, 0]
                        && w[6] <= 8
                        && w[7..10] == [0, 0, 0]
                        && w[10] <= 1
                        && w[11..14] == [0xff, 0xfe, 0xff]
                })
            })
            .context("text delimiter not found")?;
        self.r.p = found + 11;
        self.r.utf16()?;
        self.r.skip(5)?;
        // escaped leader-attachment refs
        while bytes_at(d, self.r.p, &[0xff, 0x7f]) {
            match u32_at(d, self.r.p + 2) {
                Some(v) if v & 0x8000_0000 == 0 => self.r.p += 6,
                _ => break,
            }
        }
        Ok(Value::Other)
    }

    fn read_definition(&mut self) -> Result<Value> {
        self.preamble()?;
        let base_len = match self.ver {
            17.. => 22,
            5.. => 20,
            FIRST_V4.. => 19,
            _ => 13,
        };
        self.r.skip(base_len)?;
        let nl = self.r.u32()?;
        ensure!(nl <= 10_000, "implausible definition layer count");
        // The count is real layers; SketchUp 2020 puts null separators between them.
        let mut got = 0;
        while got < nl {
            if u16_at(self.d(), self.r.p) == Some(0) {
                self.r.p += 2;
                continue;
            }
            self.object(Some("CLayer"))?;
            got += 1;
        }
        if self.ver == 19 && nl > 0 && u16_at(self.d(), self.r.p) == Some(0) {
            self.r.p += 2;
        }
        if self.r.u16()? == 0x7fff {
            self.r.u32()?;
        }
        let count = self.definition_entity_count()?;
        let ents = self.entity_list(count, false)?;
        let mut nr = self.r.u32()?;
        if nr > 100_000
            && let Some(c) = self.retry_v20(self.r.p - 4, 100_000)
        {
            nr = c;
        }
        ensure!(nr <= 100_000, "definition list misaligned");
        for _ in 0..nr {
            self.object(Some("CRelationship"))?;
        }
        self.r.u16()?;
        let name = self.definition_tail()?;
        Ok(Value::Definition { name, ents })
    }

    fn definition_entity_count(&mut self) -> Result<u32> {
        let mut count = None;
        if self.ver >= 20 {
            count = self.retry_v20(self.r.p, 5_000_000);
        }
        let mut count = if let Some(c) = count {
            c
        } else {
            self.r.u32()?;
            self.r.u32()?
        };
        // A zero count is as much a sign of the filler as a huge one.
        if (count > 5_000_000 || count == 0)
            && let Some(c) = self.retry_v20(self.r.p - 4, 5_000_000)
        {
            count = c;
        }
        ensure!(count <= 5_000_000, "implausible definition entity count");
        Ok(count)
    }

    /// GUID, name, description, path and load time, then a variable gap up to the thumbnail. Returns the name.
    fn definition_tail(&mut self) -> Result<String> {
        // Some 2020 files carry two extra bytes ahead of the GUID; anchor on the name's string marker after it.
        if !marker_at(self.d(), self.r.p + 16)
            && let Some(skip) = (1..=4).find(|s| marker_at(self.d(), self.r.p + s + 16))
        {
            self.r.p += skip;
        }
        self.r.skip(16)?;
        let name = self.r.utf16()?;
        self.r.utf16()?;
        self.r.utf16()?;
        self.r.u32()?;
        let d = self.d();
        let thumb_cs = self.class_slot.get("CThumbnail").copied();
        let tpos = (0..96)
            .map(|off| self.r.p + off)
            .take_while(|p| p + 26 <= d.len())
            .find(|&p| {
                (bytes_at(d, p, &[0xff, 0xff]) && bytes_at(d, p + 4, &[10, 0]) && bytes_at(d, p + 6, b"CThumbnail"))
                    || thumb_cs.is_some_and(|cs| is_class_ref(d, p, cs))
            })
            .context("definition thumbnail not found")?;
        self.r.p = tpos;
        self.object(Some("CThumbnail"))?;
        Ok(name)
    }

    fn read_instance(&mut self) -> Result<Value> {
        self.preamble()?;
        let draw = self.draw()?;
        let def = self.object(Some("CComponentDefinition"))?.slot;
        let xf = self.r.f64s::<13>()?;
        let name = if self.ver >= FIRST_NAMED_INSTANCE || self.r.marker() {
            self.r.utf16()?
        } else {
            String::new()
        };
        if self.ver >= 14 {
            self.r.skip(16)?;
        }
        Ok(Value::Instance(Box::new(InstRec { draw, def, xf, name })))
    }

    fn entity_list(&mut self, n: u32, root: bool) -> Result<Vec<Obj>> {
        self.burn_stack.push(0);
        self.inline_stack.push(Vec::new());
        let depth = self.inline_stack.len() - 1;
        let out = self.entity_list_inner(n as usize, root, depth);
        self.burn_stack.pop();
        self.inline_stack.pop();
        out
    }

    fn entity_list_inner(&mut self, n: usize, root: bool, depth: usize) -> Result<Vec<Obj>> {
        let mut v: Vec<Obj> = Vec::new();
        while v.len() < n {
            let save = self.r.p;
            let pending = self.inline_stack.get(depth).context("entity list stack")?;
            if !pending.is_empty() && v.len() + pending.len() >= n {
                // everything left is an instance an annotation already wrote in full
                if !self.peek_backref().is_some_and(|s| pending.contains(&s)) {
                    break;
                }
            }
            let has_burn_credit = !root && self.burn_stack.last().is_some_and(|&c| c > 0);
            if has_burn_credit && u32_at(self.d(), save) == Some(0) && marker_at(self.d(), save + 22) {
                // the definition tail: the list's real end when the declared count includes phantoms
                break;
            }
            match self.object(None) {
                Ok(item) => {
                    if let Some(listed) = self.inline_stack.get_mut(depth) {
                        listed.retain(|&s| s != item.slot);
                    }
                    v.push(item);
                }
                Err(_) if root || has_burn_credit => {
                    // an over-declared count runs into the document tail
                    self.r.p = save;
                    break;
                }
                Err(e) => return Err(e),
            }
        }
        // instances an annotation wrote in full that the list never listed again are still its entities
        let leftover = self.inline_stack.get(depth).cloned().unwrap_or_default();
        for slot in leftover {
            if v.len() >= n {
                break;
            }
            let e = self.slots.get(&slot).context("inline instance slot")?;
            v.push(Obj {
                slot,
                name: Rc::clone(&e.name),
                v: e.v.clone(),
            });
        }
        Ok(v)
    }
}

struct Walk<'a> {
    ar: Archive<'a>,
    root: Vec<Obj>,
    materials: Vec<Obj>,
}

/// With two or more materials, the second material's class reference names `CMaterial`'s true slot, which fixes
/// the slot numbering for the whole file.
fn bootstrap_two_materials(data: &[u8], ver: u32, start: usize) -> Result<u64> {
    let mut boot = Archive::new(data, ver);
    boot.next = PROBE_BASE;
    boot.base = PROBE_BASE;
    boot.r.p = start;
    boot.object(Some("CMaterial"))?;
    let tag = boot.r.peek_u16()?;
    ensure!(tag != 0xffff && tag & 0x8000 != 0, "cannot bootstrap the slot base");
    Ok(u64::from(tag & 0x7fff))
}

/// Slot-base candidates for files with fewer than two materials: the reference after the layer list points back
/// at a layer, absolutely, so each layer read under a throwaway base gives one candidate.
fn probe_layer_anchor_bases(data: &[u8], ver: u32, start: usize, mat_count: u32) -> Result<Vec<u64>> {
    let mut boot = Archive::new(data, ver);
    boot.next = PROBE_BASE;
    boot.base = PROBE_BASE;
    boot.r.p = start;
    for _ in 0..mat_count {
        boot.object(Some("CMaterial"))?;
    }
    boot.r.u32()?;
    if ver >= 17 {
        boot.r.u8()?;
    }
    let mut layers = Vec::new();
    if ver >= FIRST_V4 {
        let count = boot.r.u32()?;
        ensure!((1..=100_000).contains(&count), "implausible layer count in base probe");
        for _ in 0..count {
            layers.push(boot.object(Some("CLayer"))?);
        }
    }
    boot.collect_trailing_layers(&mut layers, true)?;
    let anchor = boot.object(None)?;
    ensure!(
        &*anchor.name == "premodel",
        "base probe: anchor resolved to {}",
        anchor.name
    );
    Ok(layers
        .iter()
        .filter_map(|l| anchor.slot.checked_add(PROBE_BASE)?.checked_sub(l.slot))
        .filter(|&c| c > 0 && c < PROBE_BASE)
        .collect())
}

/// True when a `CComponentDefinition` record starts at `at`.
fn definition_starts_at(ar: &Archive<'_>, at: usize) -> bool {
    let d = ar.d();
    if bytes_at(d, at, &[0xff, 0xff]) && bytes_at(d, at + 6, b"CComponentDefinition") {
        return true;
    }
    ar.class_slot
        .get("CComponentDefinition")
        .is_some_and(|&cs| is_class_ref(d, at, cs))
}

fn walk_model(
    data: &[u8],
    ver: u32,
    start: usize,
    mat_count: u32,
    base: u64,
) -> Result<Walk<'_>, (crate::Error, usize)> {
    let mut ar = Archive::new(data, ver);
    ar.next = base;
    ar.base = base;
    ar.r.p = start;
    match walk_model_on(&mut ar, mat_count) {
        Ok((root, materials)) => Ok(Walk { ar, root, materials }),
        Err(e) => Err((e, ar.r.p)),
    }
}

fn walk_model_on(ar: &mut Archive<'_>, mat_count: u32) -> Result<(Vec<Obj>, Vec<Obj>)> {
    let ver = ar.ver;
    let mut materials = Vec::new();
    for _ in 0..mat_count {
        materials.push(ar.object(Some("CMaterial"))?);
    }
    ar.r.u32()?;
    if ver >= 17 {
        ar.r.u8()?;
    }
    // SketchUp 3 writes no layer count; its layers run until the definition-list anchor.
    let lc = if ver < FIRST_V4 {
        usize::MAX
    } else {
        ar.r.u32()? as usize
    };
    ensure!(lc <= 100_000 || ver < FIRST_V4, "invalid layer count");
    let mut layers = Vec::new();
    while layers.len() < lc {
        let Some(tag) = u16_at(ar.d(), ar.r.p) else { break };
        if tag == 0 {
            ar.r.p += 2;
            continue;
        }
        if tag != 0xffff && tag & 0x8000 == 0 {
            break;
        }
        let q = ar.object(Some("CLayer"))?;
        if q.v.is_some() {
            layers.push(q);
        }
    }
    ar.collect_trailing_layers(&mut layers, false)?;
    let anchor = ar.object(None)?;
    ensure!(&*anchor.name == "CLayer", "definition anchor is not a layer");
    read_definitions(ar)?;
    let mut root_count = ar.r.u32()?;
    if root_count > 5_000_000
        && let Some(c) = ar.retry_v20(ar.r.p - 4, 5_000_000)
    {
        root_count = c;
    }
    ensure!(root_count <= 5_000_000, "implausible root entity count");
    let root = ar.entity_list(root_count, true)?;
    Ok((root, materials))
}

fn read_definitions(ar: &mut Archive<'_>) -> Result<()> {
    let mut dc = ar.r.u32()?;
    if dc > 1_000_000 {
        if let Some(c) = ar.retry_v20(ar.r.p - 4, 1_000_000) {
            dc = c;
            if !definition_starts_at(ar, ar.r.p) {
                // no definitions: the count behind the filler was the root count, so put it back
                dc = 0;
                ar.r.p -= 4;
            }
        } else if let Some(at) = find_empty_root_after_v20_filler(ar.d(), ar.r.p - 4) {
            dc = 0;
            ar.r.p = at;
        }
    }
    ensure!(dc <= 1_000_000, "invalid definition count");
    for _ in 0..dc {
        ar.object(Some("CComponentDefinition"))?;
    }
    while definition_starts_at(ar, ar.r.p) {
        ar.object(None)?;
    }
    Ok(())
}

/// Tries each slot base; every wrong one fails almost at once, so when none works the error that got furthest
/// into the file is the useful one.
fn walk_with_bases<'a>(data: &'a [u8], ver: u32, start: usize, mat_count: u32, bases: &[u64]) -> Result<Walk<'a>> {
    let mut best: Option<(crate::Error, usize)> = None;
    for &base in bases {
        match walk_model(data, ver, start, mat_count, base) {
            Ok(w) => return Ok(w),
            Err((e, at)) => {
                if best.as_ref().is_none_or(|b| at > b.1) {
                    best = Some((e, at));
                }
            }
        }
    }
    Err(best.map_or_else(
        || invalid!("no viable slot base"),
        |(e, at)| invalid!("stopped at offset {at}: {e}"),
    ))
}

/// Finds where the model starts: the material count right before the first `CMaterial` class record, or for a
/// file with no materials the layer list before the first `CLayer` class record.
fn find_start(data: &[u8], ver: u32) -> Result<(usize, u32)> {
    let class_record = |name: &[u8]| {
        (0..data.len()).find(|&i| {
            bytes_at(data, i, &[0xff, 0xff])
                && u16_at(data, i + 4) == u16::try_from(name.len()).ok()
                && bytes_at(data, i + 6, name)
        })
    };
    if let Some(mh) = class_record(b"CMaterial").filter(|&mh| mh >= 4) {
        let mc = u32_at(data, mh - 4).context("archive ends early")?;
        ensure!(mc <= 100_000, "implausible material count");
        return Ok((mh, mc));
    }
    let lh = class_record(b"CLayer").context("no CMaterial or CLayer class record found")?;
    let start = lh
        .checked_sub(if ver >= 17 { 9 } else { 8 })
        .context("layer record too early")?;
    Ok((start, 0))
}

pub(crate) fn parse(data: &[u8], ver: u32) -> Result<Model> {
    let (start, mc) = find_start(data, ver)?;
    let bases = if mc >= 2 {
        vec![bootstrap_two_materials(data, ver, start)?]
    } else {
        probe_layer_anchor_bases(data, ver, start, mc)?
    };
    let walk = walk_with_bases(data, ver, start, mc, &bases)?;
    Ok(to_model(data, &walk))
}

fn to_model(data: &[u8], walk: &Walk<'_>) -> Model {
    let slots = &walk.ar.slots;
    let mut model = Model::default();
    for m in &walk.materials {
        if let Some(Value::Material(rec)) = m.v.as_deref() {
            model.materials.insert(m.slot, material(data, slots, rec));
        }
    }
    for (&slot, e) in slots {
        match e.v.as_deref() {
            Some(Value::Layer { hidden: true }) => model.hidden_layers.push(slot),
            Some(Value::Definition { name, ents }) => {
                let mut def = fill(ents, slots);
                def.name.clone_from(name);
                model.definitions.insert(slot, def);
            }
            _ => {}
        }
    }
    model.root = fill(&walk.root, slots);
    model
}

fn material(data: &[u8], slots: &HashMap<u64, Entry>, rec: &MatRec) -> model::Material {
    let texture = rec.tex.as_ref().and_then(|t| {
        let (start, len) = match t.inline {
            Some(range) => range,
            None => match slots.get(&t.dib?)?.v.as_deref()? {
                Value::Dib { start, len } => (*start, *len),
                _ => return None,
            },
        };
        let bytes = data.get(start..start.checked_add(len)?)?;
        Some(model::Texture {
            bytes: super::image::embeddable(bytes)?,
            tile: t.tile,
            average: Some(t.average),
        })
    });
    model::Material {
        name: rec.name.clone(),
        rgb: [rec.rgba[0], rec.rgba[1], rec.rgba[2]],
        alpha: legacy_alpha(rec),
        colorize: rec.tex.as_ref().is_some_and(|t| t.colorize),
        texture,
    }
}

/// The color's own alpha times the material's opacity. The opacity field only counts when the flag after it
/// says transparency is in use; otherwise the reader has already zeroed it.
fn legacy_alpha(rec: &MatRec) -> f64 {
    let transparency = (1.0 - rec.opacity).clamp(0.0, 1.0);
    f64::from(rec.rgba[3]) / 255.0 * transparency
}

/// Turns one entity list into faces and instances.
fn fill(ents: &[Obj], slots: &HashMap<u64, Entry>) -> model::Definition {
    let mut def = model::Definition::default();
    let nonzero = |id: u64| (id != 0).then_some(id);
    for obj in ents {
        match obj.v.as_deref() {
            Some(Value::Face(f)) => {
                let mut smooth = Vec::new();
                let loops: Vec<Vec<[f64; 3]>> = f
                    .loops
                    .iter()
                    .filter_map(|l| loop_points(l, slots, &mut smooth))
                    .collect();
                if loops.is_empty() {
                    continue;
                }
                if !smooth.contains(&true) {
                    smooth = Vec::new();
                }
                let uv = f.attrs.and_then(|a| texture_matrices(a, slots));
                def.faces.push(model::Face {
                    loops,
                    smooth,
                    normal: f.normal,
                    material: nonzero(f.draw.mat),
                    back_material: nonzero(f.back_mat),
                    uv_matrix: uv.map(|m| m[0]),
                    back_uv_matrix: uv.map(|m| m[1]),
                    hidden: f.draw.hidden,
                    layer: nonzero(f.draw.layer),
                });
            }
            Some(Value::Instance(i)) => def.instances.push(model::Instance {
                definition: i.def,
                name: i.name.clone(),
                matrix: i.xf,
                material: nonzero(i.draw.mat),
                hidden: i.draw.hidden,
                layer: nonzero(i.draw.layer),
            }),
            _ => {}
        }
    }
    def
}

/// The front's and back's positioned-texture matrices kept among a face's attributes, if any.
fn texture_matrices(attrs: u64, slots: &HashMap<u64, Entry>) -> Option<[[f64; 9]; 2]> {
    let Some(Value::Attrs(ents)) = slots.get(&attrs)?.v.as_deref() else {
        return None;
    };
    ents.iter().find_map(|e| match e.v.as_deref() {
        Some(Value::Ftc(m)) => Some(**m),
        _ => None,
    })
}

/// A loop's corner points: each edge use starts at its edge's first vertex, or its second when reversed. Pushes
/// onto `smooth`, for each corner kept, whether the edge leaving it is smooth.
fn loop_points(l: &Value, slots: &HashMap<u64, Entry>, smooth: &mut Vec<bool>) -> Option<Vec<[f64; 3]>> {
    let Value::Loop(uses) = l else { return None };
    let mut ids: Vec<(u64, bool)> = Vec::new();
    for u in uses {
        let Value::EdgeUse { edge, sense } = **u else { continue };
        let Some(&Value::Edge { v1, v2, smooth }) = slots.get(&edge).and_then(|e| e.v.as_deref()) else {
            continue;
        };
        let id = if sense { v2 } else { v1 };
        // after a zero-length edge, the edge that really leaves the corner is the one that counts
        match ids.last_mut() {
            Some(last) if last.0 == id => last.1 = smooth,
            _ => ids.push((id, smooth)),
        }
    }
    if ids.len() > 1 && ids.first().map(|c| c.0) == ids.last().map(|c| c.0) {
        ids.pop();
    }
    let points: Option<Vec<[f64; 3]>> = ids
        .iter()
        .map(|&(id, _)| match slots.get(&id)?.v.as_deref()? {
            Value::Vertex(p) => Some(*p),
            _ => None,
        })
        .collect();
    let points = points.filter(|p| p.len() >= 3)?;
    smooth.extend(ids.iter().map(|c| c.1));
    Some(points)
}

#[cfg(test)]
#[allow(clippy::cast_possible_truncation, reason = "test archives are small")]
mod tests {
    use super::*;

    fn class_decl(name: &str) -> Vec<u8> {
        let mut out = vec![0xff, 0xff, 1, 0];
        out.extend((name.len() as u16).to_le_bytes());
        out.extend(name.as_bytes());
        out
    }

    #[test]
    fn reads_class_declarations_and_back_references() {
        // a SketchUp 3 vertex has no preamble: the declaration, three doubles, then a back-reference to it
        let mut d = class_decl("CVertex");
        for v in [1.0f64, 2.0, 3.0] {
            d.extend(v.to_le_bytes());
        }
        d.extend(11u16.to_le_bytes());
        let mut ar = Archive::new(&d, 3);
        ar.next = 10;
        ar.base = 10;
        let v = ar.object(None).unwrap();
        assert_eq!(v.slot, 11);
        assert!(
            matches!(v.v.as_deref(), Some(Value::Vertex(p)) if p.map(f64::to_bits) == [1.0, 2.0, 3.0].map(f64::to_bits))
        );
        let again = ar.object(None).unwrap();
        assert_eq!(again.slot, 11);
        assert_eq!(&*again.name, "CVertex");
    }

    #[test]
    fn reads_tag_line_styles_and_counts_their_slots() {
        let string = |s: &str| {
            let mut out = vec![0xff, 0xfe, 0xff, s.len() as u8];
            out.extend(s.encode_utf16().flat_map(u16::to_le_bytes));
            out
        };
        for ver in [19, 20] {
            // The style in full where the first tag uses it: its class, a null attribute container and an empty
            // mask (twice in 2019), its name, its dash pattern and three doubles.
            let mut d = class_decl("CCustomLineStyle");
            for _ in 0..if ver < 20 { 2 } else { 1 } {
                d.extend([0, 0, 0]);
            }
            d.extend(string("Dash"));
            d.extend(string("4 2"));
            d.extend([0; 24]);
            let end = d.len();
            // A later tag's back-reference to it, a tag with none, and a reference to something else.
            d.extend(11u16.to_le_bytes());
            d.extend(0u16.to_le_bytes());
            d.extend(5u16.to_le_bytes());
            let mut ar = Archive::new(&d, ver);
            ar.next = 10;
            ar.base = 10;
            ar.read_clayer_line_style().unwrap();
            assert_eq!((ar.r.p, ar.next), (end, 12), "version {ver}");
            ar.read_clayer_line_style().unwrap();
            assert_eq!(ar.r.p, end + 2);
            ar.read_clayer_line_style().unwrap();
            assert_eq!(ar.r.p, end + 2);
            ar.r.p += 2;
            ar.read_clayer_line_style().unwrap();
            assert_eq!(ar.r.p, end + 4);
            // Cut short: an error, never a panic.
            for len in 0..end {
                let mut ar = Archive::new(&d[..len], ver);
                let _ = ar.read_clayer_line_style();
            }
        }
    }

    #[test]
    fn rejects_unknown_classes_and_slots() {
        let d = class_decl("CMystery");
        assert!(Archive::new(&d, 15).object(None).is_err());
        let d = 0x8005u16.to_le_bytes();
        assert!(Archive::new(&d, 15).object(None).is_err());
        let d = 5u16.to_le_bytes();
        assert!(Archive::new(&d, 15).object(None).is_err());
        let d = [0xff, 0xff, 1, 0, 200, 0];
        assert!(Archive::new(&d, 15).object(None).is_err());
    }

    #[test]
    fn deep_nesting_is_an_error_not_a_stack_overflow() {
        // a loop whose first edge use opens another loop, and so on: each level nests a new object
        let mut d = class_decl("CLoop");
        for _ in 0..400 {
            d.extend([0, 0]);
            d.extend(0x8000u16.to_le_bytes());
        }
        let mut ar = Archive::new(&d, 3);
        assert!(ar.object(None).is_err());
    }

    #[test]
    fn finds_counts_behind_the_v20_filler() {
        let mut d = vec![0; 4];
        d.extend([0xff, 0xfe, 0xff, 0]);
        d.extend([0; 9]);
        d.extend(7u32.to_le_bytes());
        d.extend([0, 0]);
        let mut ar = Archive::new(&d, 20);
        assert_eq!(ar.retry_v20(0, 100), Some(7));
        assert_eq!(ar.r.p, 21);
        // a non-empty string is real data, not filler
        d[7] = 1;
        assert_eq!(Archive::new(&d, 20).retry_v20(0, 100), None);
    }

    #[test]
    fn finds_an_empty_root_behind_the_filler() {
        let mut d = vec![0xff, 0xfe, 0xff, 0];
        d.extend([0; 17]);
        assert_eq!(find_empty_root_after_v20_filler(&d, 0), Some(17));
        d[10] = 1;
        assert_eq!(find_empty_root_after_v20_filler(&d, 0), None);
    }

    #[test]
    fn burn_bands_translate_references() {
        let mut ar = Archive::new(&[], 17);
        ar.burns = vec![(10, 2), (20, 3)];
        assert_eq!(ar.translate_ref(5), Some(5));
        assert_eq!(ar.translate_ref(11), None);
        assert_eq!(ar.translate_ref(12), Some(10));
        assert_eq!(ar.translate_ref(30), Some(25));
    }

    #[test]
    fn loops_carry_each_corners_smooth_flag() {
        let entry = |v: Value| Entry {
            cls: false,
            name: Rc::from(""),
            v: Some(Rc::new(v)),
        };
        let mut slots = HashMap::new();
        for (id, p) in [(1, [0.0, 0.0, 0.0]), (2, [1.0, 0.0, 0.0]), (3, [0.0, 1.0, 0.0])] {
            slots.insert(id, entry(Value::Vertex(p)));
        }
        // the edge from 2 to 3 is smooth; 13 is a zero-length edge at 2 and must not take over its corner
        for (id, v1, v2, smooth) in [
            (10, 1, 2, false),
            (11, 3, 2, true),
            (12, 3, 1, false),
            (13, 2, 2, false),
        ] {
            slots.insert(id, entry(Value::Edge { v1, v2, smooth }));
        }
        let uses = [(10, false), (13, false), (11, true), (12, false)]
            .map(|(edge, sense)| Rc::new(Value::EdgeUse { edge, sense }));
        let mut smooth = Vec::new();
        let points = loop_points(&Value::Loop(uses.to_vec()), &slots, &mut smooth).unwrap();
        assert_eq!(points.len(), 3);
        assert_eq!(smooth, [false, true, false]);
    }
}