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
//! Unit-normalized 3MF builds with multipart placement, colors, and packaged textures.
#[cfg(test)]
use super::zip_directory::{zip_u16, zip_u32, zip_u64};
use super::{MAX_INPUT_BYTES, transform::Transform};
use crate::{
    Result,
    scene::{
        Scene, Texture, TextureFilter, TextureInterpolationSpace, TextureWrap, Triangle,
        TriangleAppearance, Vec3,
    },
};
use image::{ImageFormat, RgbaImage};
use std::{
    collections::{BTreeMap, HashMap, HashSet},
    io::{Cursor, Read, Seek},
    path::Path,
    sync::Arc,
};

/// XML namespace of the supported 3MF core model schema.
const CORE: &str = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02";
/// XML namespace of the supported 3MF material resource extension.
const MATERIAL: &str = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02";
/// XML namespace of the supported multipart 3MF production extension.
const PRODUCTION: &str = "http://schemas.microsoft.com/3dmanufacturing/production/2015/06";
/// Open Packaging Conventions relationship XML namespace.
const RELATIONSHIPS: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
/// Relationship type identifying a 3MF model XML part.
const MODEL_RELATIONSHIP: &str = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel";
/// Relationship type required between an owning model part and its texture images.
const TEXTURE_RELATIONSHIP: &str = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture";
/// Maximum width or height of a decoded texture image.
const MAX_TEXTURE_AXIS: u32 = 8192;
/// Maximum pixel count of an individual decoded texture image.
const MAX_TEXTURE_PIXELS: u64 = 16 * 1024 * 1024;
/// Maximum aggregate pixel count across distinct package texture images.
const MAX_TOTAL_TEXTURE_PIXELS: u64 = 64 * 1024 * 1024;
/// Maximum source or expanded preview triangle count.
const MAX_TRIANGLES: usize = 5_000_000;
/// Maximum model parts referenced by a multipart package.
const MAX_PARTS: usize = 256;
/// Maximum aggregate resources or physical ZIP directory entries.
const MAX_RESOURCES: usize = 100_000;
/// Maximum aggregate source object references.
const MAX_REFERENCES: usize = 1_000_000;
/// Maximum recursive reference, geometry or partition depth.
const MAX_DEPTH: usize = 256;

/// A local or production-part object reference with its unit-normalized placement.
struct Reference {
    /// Optional canonical production-part path; absence refers to the current part.
    part: Option<String>,
    /// Object resource identifier scoped to the referenced model part.
    object: u32,
    /// Local-to-parent affine placement in normalized scene units.
    transform: Transform,
}

/// One mesh or component object with its part-local resource identity.
struct Object {
    /// Authored unit-normalized mesh triangles belonging to the object.
    triangles: Vec<Triangle>,
    /// Triangle-local texture identifiers and coordinates resolved in the owning part.
    textures: BTreeMap<usize, TextureMapping>,
    /// Placed references to component objects contained by this object.
    components: Vec<Reference>,
}

/// Part-local objects and build references decoded from one model XML part.
struct ModelPart {
    /// Decoded objects indexed by identifiers local to this XML part.
    objects: HashMap<u32, Object>,
    /// Authored build-item references; only the root part drives instantiation.
    build: Vec<Reference>,
    /// Part-local texture resources with shared images loaded from the package.
    textures: HashMap<u32, TextureResource>,
}

/// A direct single-layer texture resource and its sampler settings.
struct TextureResource {
    /// Canonical absolute image part name, stored without its leading slash.
    path: String,
    /// PNG or JPEG encoding required by the resource's content type.
    format: ImageFormat,
    /// Texture addressing along the horizontal coordinate.
    wrap_s: TextureWrap,
    /// Texture addressing along the vertical coordinate.
    wrap_t: TextureWrap,
    /// Authored nearest, bilinear, or default high-quality reconstruction.
    filter: TextureFilter,
    /// Shared decoded texels, present after package relationship validation.
    image: Option<Arc<RgbaImage>>,
}

/// A material property group selecting one texture and indexed UV coordinates.
struct TextureGroup {
    /// Part-local resource identifier of the associated texture image.
    texture: u32,
    /// Finite UV pairs converted to the renderer's upper-left image origin.
    coordinates: Vec<[f64; 2]>,
}

/// Per-corner texture properties attached to one source mesh triangle.
struct TextureMapping {
    /// Part-local texture resource selected by the triangle's property group.
    texture: u32,
    /// Three UV pairs following geometric triangle corner order.
    coordinates: [[f64; 2]; 3],
}

/// One decoded package image with its actual encoding retained for MIME validation.
struct CachedImage {
    /// Signature-verified PNG or JPEG encoding of the source package member.
    format: ImageFormat,
    /// Shared straight-alpha sRGB pixels used by every referencing model part.
    image: Arc<RgbaImage>,
}

/// Aggregate source/decompression/resource limits shared across referenced model parts.
#[derive(Default)]
struct Budget {
    /// Aggregate decompressed XML and encoded image bytes consumed from package parts.
    bytes: u64,
    /// Aggregate decoded pixels across distinct cached texture images.
    pixels: u64,
    /// Aggregate source mesh vertex count across decoded model parts.
    vertices: usize,
    /// Aggregate source mesh triangle count across decoded model parts.
    triangles: usize,
    /// Aggregate number of decoded resource records.
    resources: usize,
    /// Aggregate number of decoded object references.
    references: usize,
    /// Aggregate finite texture-coordinate entries across decoded material groups.
    texcoords: usize,
}

/// Increment one aggregate model count without crossing its limit.
///
/// # Errors
///
/// The count overflows or exceeds the supplied budget.
fn consume(count: &mut usize, limit: usize, label: &str) -> Result<()> {
    *count = count.checked_add(1).ok_or("3MF count overflow")?;
    if *count > limit {
        return Err(format!("3MF exceeds {label} limit").into());
    }
    Ok(())
}

/// Validate every physical 3MF ZIP member before library indexing.
///
/// # Errors
/// Returns an error for malformed ZIP directories, duplicate physical names,
/// unreadable package data or more than 100,000 directory entries.
fn validate_zip_directory(reader: &mut (impl Read + Seek), length: u64) -> Result<usize> {
    super::zip_directory::validate(reader, length, MAX_RESOURCES)
}

/// Model part names are OPC package URIs, never filesystem paths. Cache the
/// indexed ZIP entries so aliases cannot select an ambiguous duplicate part.
struct Package {
    /// Opened ZIP reader retaining the package file handle.
    archive: zip::ZipArchive<std::fs::File>,
    /// Canonical package part names mapped to unambiguous ZIP entry indices.
    entries: HashMap<String, usize>,
    /// Decoded texture images indexed by canonical package paths across model parts.
    images: HashMap<String, CachedImage>,
}

impl Package {
    /// Open a bounded ZIP package and index unambiguous canonical part names.
    ///
    /// # Errors
    ///
    /// File/ZIP validation, duplicate names or package limits fail.
    fn open(path: &Path) -> Result<Self> {
        let mut file = std::fs::File::open(path)?;
        let length = file.metadata()?.len();
        if length > MAX_INPUT_BYTES {
            return Err("3MF package exceeds the 512 MiB limit".into());
        }
        let physical_entries = validate_zip_directory(&mut file, length)?;
        let mut archive = zip::ZipArchive::new(file)?;
        if archive.len() != physical_entries {
            // Require every physically validated record to remain visible.
            // Decoded-name aliases are checked by the canonical index below.
            return Err("duplicate decoded 3MF package part name".into());
        }
        if archive.len() > MAX_RESOURCES {
            return Err("3MF package has too many archive entries".into());
        }
        let mut entries = HashMap::new();
        for index in 0..archive.len() {
            let entry = archive.by_index(index)?;
            if entry.is_dir() {
                continue;
            }
            // ZIP item names are decoded names, whereas relationship and
            // production targets are URIs. A literal '%' in an item name must
            // not be interpreted as a second URI escape.
            let path = part_name(&entry.name()?)?;
            if entries.insert(path, index).is_some() {
                return Err("duplicate 3MF package part name".into());
            }
        }
        Ok(Self {
            archive,
            entries,
            images: HashMap::new(),
        })
    }

    /// Test whether the canonical package part name exists in the archive index.
    fn contains(&self, path: &str) -> bool {
        self.entries.contains_key(path)
    }

    /// Read a referenced UTF-8 XML part within the aggregate decompression budget.
    ///
    /// # Errors
    ///
    /// The part is missing, unreadable, invalidly encoded or exceeds decompression limits.
    fn read(&mut self, path: &str, budget: &mut Budget) -> Result<String> {
        Ok(String::from_utf8(self.read_bytes(path, budget)?)?)
    }

    /// Read one package member within the shared XML and encoded-image byte budget.
    ///
    /// # Errors
    /// Returns an error if the member is missing, unreadable, corrupt, or exceeds
    /// the remaining aggregate decompression budget.
    fn read_bytes(&mut self, path: &str, budget: &mut Budget) -> Result<Vec<u8>> {
        let index = *self
            .entries
            .get(path)
            .ok_or_else(|| format!("3MF references a missing package part {path}"))?;
        let mut entry = self.archive.by_index(index)?;
        if entry.size() > MAX_INPUT_BYTES.saturating_sub(budget.bytes) {
            return Err("3MF consumed package data exceeds the aggregate 512 MiB limit".into());
        }
        let mut bytes = Vec::new();
        entry
            .by_ref()
            .take(MAX_INPUT_BYTES.saturating_sub(budget.bytes) + 1)
            .read_to_end(&mut bytes)?;
        budget.bytes = budget
            .bytes
            .checked_add(bytes.len() as u64)
            .filter(|&n| n <= MAX_INPUT_BYTES)
            .ok_or("3MF consumed package data exceeds the aggregate 512 MiB limit")?;
        Ok(bytes)
    }

    /// Decode a PNG/JPEG once after checking its signature, dimensions, and pixel budgets.
    ///
    /// # Errors
    /// Returns an error for a MIME/signature mismatch, invalid image data,
    /// missing package member, or exceeded encoded-byte, dimension, or pixel limits.
    fn texture(
        &mut self,
        path: &str,
        format: ImageFormat,
        budget: &mut Budget,
    ) -> Result<Arc<RgbaImage>> {
        if let Some(cached) = self.images.get(path) {
            if cached.format != format {
                return Err("3MF image signature differs from its texture content type".into());
            }
            return Ok(Arc::clone(&cached.image));
        }
        let bytes = self.read_bytes(path, budget)?;
        if image::guess_format(&bytes)? != format {
            return Err("3MF image signature differs from its texture content type".into());
        }
        let (width, height) =
            texture_reader(&bytes, format)
                .into_dimensions()
                .map_err(|error| {
                    format!("3MF texture metadata or dimensions exceed limits: {error}")
                })?;
        let pixels = u64::from(width) * u64::from(height);
        budget.pixels = budget
            .pixels
            .checked_add(pixels)
            .ok_or("3MF texture pixel count overflow")?;
        if width == 0
            || height == 0
            || width > MAX_TEXTURE_AXIS
            || height > MAX_TEXTURE_AXIS
            || pixels > MAX_TEXTURE_PIXELS
            || budget.pixels > MAX_TOTAL_TEXTURE_PIXELS
        {
            return Err("3MF textures exceed the dimension or aggregate pixel budget".into());
        }
        let image = Arc::new(texture_reader(&bytes, format).decode()?.to_rgba8());
        self.images.insert(
            path.to_owned(),
            CachedImage {
                format,
                image: Arc::clone(&image),
            },
        );
        Ok(image)
    }
}

/// Apply image allocation and axis limits during both metadata and pixel decoding.
fn texture_reader(bytes: &[u8], format: ImageFormat) -> image::ImageReader<Cursor<&[u8]>> {
    let mut reader = image::ImageReader::with_format(Cursor::new(bytes), format);
    let mut limits = image::Limits::default();
    limits.max_image_width = Some(MAX_TEXTURE_AXIS);
    limits.max_image_height = Some(MAX_TEXTURE_AXIS);
    limits.max_alloc = Some(128 * 1024 * 1024);
    reader.limits(limits);
    reader
}

/// Load the root 3MF build and referenced production-extension model parts.
///
/// # Errors
///
/// ZIP/XML structure, local references, resources, geometry or preview budgets are invalid or unsupported.
pub(super) fn load(path: &Path) -> Result<Scene> {
    let mut package = Package::open(path)?;
    let mut budget = Budget::default();
    let root = if package.contains("_rels/.rels") {
        let xml = package.read("_rels/.rels", &mut budget)?;
        let targets = model_relationships(&xml, "")?;
        if targets.len() != 1 {
            return Err("3MF package must have exactly one root model relationship".into());
        }
        targets
            .into_iter()
            .next()
            .ok_or("3MF root model is missing")?
    } else {
        package_path("3D/3dmodel.model")?
    };
    let xml = package.read(&root, &mut budget)?;
    let mut root_part = parse_part(&xml, true, &mut budget)?;
    load_textures(&mut package, &root, &mut root_part, &mut budget)?;
    let mut targets: HashSet<_> = root_part
        .objects
        .values()
        .flat_map(|object| &object.components)
        .chain(&root_part.build)
        .filter_map(|reference| reference.part.clone())
        .collect();
    if targets.len() >= MAX_PARTS {
        return Err("3MF package exceeds the model-part limit".into());
    }
    if !targets.is_empty() {
        let (directory, name) = root.rsplit_once('/').unwrap_or(("", root.as_str()));
        let relationships = if directory.is_empty() {
            format!("_rels/{name}.rels")
        } else {
            format!("{directory}/_rels/{name}.rels")
        };
        let xml = package.read(&relationships, &mut budget)?;
        let declared = model_relationships(&xml, directory)?;
        if targets.iter().any(|target| !declared.contains(target)) {
            return Err("3MF production part lacks a model relationship".into());
        }
    }
    targets.remove(&root);
    let mut targets: Vec<_> = targets.into_iter().collect();
    targets.sort();
    let mut parts = HashMap::from([(root.clone(), root_part)]);
    for target in targets {
        let xml = package.read(&target, &mut budget)?;
        let mut part = parse_part(&xml, false, &mut budget)?;
        load_textures(&mut package, &target, &mut part, &mut budget)?;
        parts.insert(target, part);
    }
    render_parts(&root, &parts)
}

/// Percent-decode a package URI without permitting filesystem/remote targets.
///
/// # Errors
///
/// Escapes, UTF-8, delimiters or forbidden path characters are invalid.
fn decode_uri(target: &str) -> Result<String> {
    let bytes = target.as_bytes();
    let mut decoded = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' {
            if i + 2 >= bytes.len() {
                return Err("invalid escape in 3MF package target".into());
            }
            decoded.push(u8::from_str_radix(
                std::str::from_utf8(&bytes[i + 1..i + 3])?,
                16,
            )?);
            i += 3;
        } else {
            decoded.push(bytes[i]);
            i += 1;
        }
    }
    Ok(String::from_utf8(decoded)?)
}

/// Validate and canonicalize an already decoded package part name.
///
/// # Errors
///
/// The name contains invalid, empty, relative or traversal segments.
fn part_name(value: &str) -> Result<String> {
    let path = value.strip_prefix('/').unwrap_or(value);
    if value.contains([':', '\0', '\\', '?', '#'])
        || path.is_empty()
        || path.split('/').any(|p| matches!(p, "" | "." | ".."))
    {
        return Err("invalid 3MF package target".into());
    }
    Ok(path.to_ascii_lowercase())
}

/// Decode and canonicalize a package-local model part URI.
///
/// # Errors
///
/// The URI is malformed, external or contains invalid/traversal segments.
fn package_path(target: &str) -> Result<String> {
    part_name(&decode_uri(target)?)
}

/// Resolve a relationship target relative to its package part directory.
///
/// # Errors
///
/// The target is external, malformed or cannot resolve to a valid package-local part.
fn relationship_target(target: &str, directory: &str) -> Result<String> {
    let target = decode_uri(target)?;
    if target.contains([':', '\0', '\\', '?', '#']) || target.starts_with("//") {
        return Err("invalid 3MF relationship target".into());
    }
    let mut segments: Vec<_> = if target.starts_with('/') || directory.is_empty() {
        Vec::new()
    } else {
        directory.split('/').collect()
    };
    for segment in target.strip_prefix('/').unwrap_or(&target).split('/') {
        match segment {
            "" => return Err("invalid 3MF relationship target".into()),
            "." => {}
            ".." => {
                segments
                    .pop()
                    .ok_or("3MF relationship escapes the package")?;
            }
            value => segments.push(value),
        }
    }
    part_name(&segments.join("/"))
}

/// Collect supported internal model-part relationship targets.
///
/// # Errors
///
/// XML relationships are invalid, external, duplicated or above the part limit.
fn model_relationships(xml: &str, directory: &str) -> Result<HashSet<String>> {
    relationship_targets(xml, directory, MODEL_RELATIONSHIP, MAX_PARTS, "model")
}

/// Collect canonical internal targets for one required OPC relationship type.
///
/// # Errors
/// Returns an error if relationship XML or IDs are invalid, a matching target is
/// external, duplicate, or escapes the package, or the target count exceeds its limit.
fn relationship_targets(
    xml: &str,
    directory: &str,
    kind: &str,
    limit: usize,
    label: &str,
) -> Result<HashSet<String>> {
    let doc = roxmltree::Document::parse(xml)?;
    let root = doc.root_element();
    if !root.has_tag_name((RELATIONSHIPS, "Relationships")) {
        return Err("expected 3MF OPC Relationships element".into());
    }
    let mut ids = HashSet::new();
    let mut targets = HashSet::new();
    for relation in root
        .children()
        .filter(|n| n.has_tag_name((RELATIONSHIPS, "Relationship")))
    {
        if !ids.insert(attribute(relation, "Id")?) {
            return Err("duplicate 3MF relationship ID".into());
        }
        if relation.attribute("Type") != Some(kind) {
            continue;
        }
        if relation
            .attribute("TargetMode")
            .is_some_and(|mode| mode != "Internal")
        {
            return Err(format!("external 3MF {label} relationships are unsupported").into());
        }
        let target = attribute(relation, "Target")?;
        let target = relationship_target(target, directory)?;
        if !targets.insert(target) {
            return Err(format!("duplicate 3MF {label} relationship target").into());
        }
        if targets.len() > limit {
            return Err(format!("3MF relationships exceed the {label} target limit").into());
        }
    }
    Ok(targets)
}

/// Resolve one model part's direct texture resources through its typed OPC relationships.
///
/// # Errors
/// Returns an error for absent or invalid owning-part relationships, a missing
/// texture target, image/MIME decoding errors, or exceeded byte and pixel budgets.
fn load_textures(
    package: &mut Package,
    owner: &str,
    part: &mut ModelPart,
    budget: &mut Budget,
) -> Result<()> {
    if part.textures.is_empty() {
        return Ok(());
    }
    let (directory, name) = owner.rsplit_once('/').unwrap_or(("", owner));
    let relationships = if directory.is_empty() {
        format!("_rels/{name}.rels")
    } else {
        format!("{directory}/_rels/{name}.rels")
    };
    let xml = package.read(&relationships, budget)?;
    let declared = relationship_targets(
        &xml,
        directory,
        TEXTURE_RELATIONSHIP,
        MAX_RESOURCES,
        "texture",
    )?;
    // Stable source-ID order makes resource-limit errors deterministic.
    let mut identifiers: Vec<_> = part.textures.keys().copied().collect();
    identifiers.sort_unstable();
    for identifier in identifiers {
        let texture = part
            .textures
            .get_mut(&identifier)
            .ok_or("3MF texture resource is missing")?;
        if !declared.contains(&texture.path) {
            return Err("3MF texture lacks an owning-model texture relationship".into());
        }
        texture.image = Some(package.texture(&texture.path, texture.format, budget)?);
    }
    Ok(())
}

/// Parse texture addressing; a direct base layer ignores alpha so `none` uses clamp.
///
/// # Errors
/// Returns an error if the authored tile-style spelling is not supported by 3MF.
fn texture_wrap(value: Option<&str>) -> Result<TextureWrap> {
    match value.unwrap_or("wrap") {
        "wrap" => Ok(TextureWrap::Repeat),
        "mirror" => Ok(TextureWrap::MirroredRepeat),
        "clamp" | "none" => Ok(TextureWrap::ClampToEdge),
        _ => Err("invalid 3MF texture tile style".into()),
    }
}

/// Parse one namespace-qualified packaged PNG/JPEG texture and its sampler state.
///
/// # Errors
/// Returns an error for an invalid namespace, path, content type, or sampler setting.
fn texture_resource(node: roxmltree::Node<'_, '_>) -> Result<TextureResource> {
    if !node.has_tag_name((MATERIAL, "texture2d")) {
        return Err("3MF texture2d must use the materials namespace".into());
    }
    let path = attribute(node, "path")?;
    if !path.starts_with('/') {
        return Err("3MF texture path must be an absolute package part name".into());
    }
    let format = match attribute(node, "contenttype")? {
        "image/png" => ImageFormat::Png,
        "image/jpeg" => ImageFormat::Jpeg,
        _ => return Err("3MF texture content type must be image/png or image/jpeg".into()),
    };
    let filter = match node.attribute("filter").unwrap_or("auto") {
        "auto" | "linear" => TextureFilter::Linear,
        "nearest" => TextureFilter::Nearest,
        _ => return Err("invalid 3MF texture filter".into()),
    };
    Ok(TextureResource {
        path: package_path(path)?,
        format,
        wrap_s: texture_wrap(node.attribute("tilestyleu"))?,
        wrap_t: texture_wrap(node.attribute("tilestylev"))?,
        filter,
        image: None,
    })
}

/// Read a materials texture-coordinate group with lower-left to upper-left conversion.
///
/// # Errors
/// Returns an error for invalid namespaces, resource IDs, non-finite or malformed
/// UV coordinates, unsupported display properties, or excessive coordinate counts.
fn texture_group(node: roxmltree::Node<'_, '_>, budget: &mut Budget) -> Result<TextureGroup> {
    if !node.has_tag_name((MATERIAL, "texture2dgroup")) {
        return Err("3MF texture2dgroup must use the materials namespace".into());
    }
    if node.attribute("displaypropertiesid").is_some() {
        return Err("3MF texture display properties are not implemented".into());
    }
    let mut coordinates = Vec::new();
    for coordinate in node.children().filter(roxmltree::Node::is_element) {
        if !coordinate.has_tag_name((MATERIAL, "tex2coord")) {
            return Err("3MF texture group contains an invalid coordinate element".into());
        }
        consume(&mut budget.texcoords, MAX_TRIANGLES, "texture coordinate")?;
        let u: f64 = attribute(coordinate, "u")?.parse()?;
        let v: f64 = attribute(coordinate, "v")?.parse()?;
        let uv = [u, 1.0 - v];
        if !u.is_finite() || !v.is_finite() || !uv[1].is_finite() {
            return Err("3MF texture coordinates must be finite".into());
        }
        coordinates.push(uv);
    }
    if coordinates.is_empty() {
        return Err("3MF texture coordinate group must not be empty".into());
    }
    Ok(TextureGroup {
        texture: id(node, "texid")?,
        coordinates,
    })
}

/// Read a required unqualified 3MF XML attribute.
///
/// # Errors
///
/// The element lacks the named attribute.
fn attribute<'a>(node: roxmltree::Node<'a, '_>, name: &str) -> Result<&'a str> {
    node.attribute(name)
        .ok_or_else(|| format!("3MF {} is missing {name}", node.tag_name().name()).into())
}

/// Parse a required numeric 3MF resource/reference identifier.
///
/// # Errors
///
/// The attribute is missing or is not an unsigned 32-bit integer.
fn id(node: roxmltree::Node<'_, '_>, name: &str) -> Result<u32> {
    Ok(attribute(node, name)?.parse()?)
}

/// Find an optional unique child in the 3MF core namespace.
///
/// # Errors
///
/// The element contains duplicate core children of the requested name.
fn core_child<'a, 'input>(
    node: roxmltree::Node<'a, 'input>,
    name: &str,
) -> Result<Option<roxmltree::Node<'a, 'input>>> {
    let mut matches = node.children().filter(|n| n.has_tag_name((CORE, name)));
    let child = matches.next();
    if matches.next().is_some() {
        return Err(format!("duplicate 3MF {name} element").into());
    }
    Ok(child)
}

/// Decode supported #RRGGBB or #RRGGBBAA color syntax to its RGB channels.
///
/// # Errors
///
/// The spelling has an invalid prefix, length, character set or hexadecimal components.
fn color(value: &str) -> Result<[u8; 3]> {
    let value = value
        .strip_prefix('#')
        .ok_or("3MF color must start with #")?;
    if (value.len() != 6 && value.len() != 8) || !value.is_ascii() {
        return Err("3MF color must be #RRGGBB or #RRGGBBAA".into());
    }
    Ok([
        u8::from_str_radix(&value[0..2], 16)?,
        u8::from_str_radix(&value[2..4], 16)?,
        u8::from_str_radix(&value[4..6], 16)?,
    ])
}

/// Resolve a supported 3MF model unit to millimetres.
///
/// # Errors
///
/// The unit spelling is unsupported.
fn unit_scale(model: roxmltree::Node<'_, '_>) -> Result<f64> {
    match model.attribute("unit").unwrap_or("millimeter") {
        "micron" => Ok(0.001),
        "millimeter" => Ok(1.),
        "centimeter" => Ok(10.),
        "inch" => Ok(25.4),
        "foot" => Ok(304.8),
        "meter" => Ok(1000.),
        _ => Err("unsupported 3MF model unit".into()),
    }
}

/// Read a placed component/build reference with package-local production-path rules.
///
/// # Errors
///
/// Paths, namespaces, identifiers or transforms are invalid/unsupported, or reference limits are exceeded.
fn reference(
    node: roxmltree::Node<'_, '_>,
    root: bool,
    unit: f64,
    budget: &mut Budget,
) -> Result<Reference> {
    consume(&mut budget.references, MAX_REFERENCES, "object reference")?;
    let mut part = None;
    for value in node.attributes().filter(|value| value.name() == "path") {
        if value.namespace() != Some(PRODUCTION) {
            return Err("3MF path attribute must use the production namespace".into());
        }
        if !root {
            return Err("3MF production paths are allowed only in the root model part".into());
        }
        if !value.value().starts_with('/') {
            return Err("3MF production path must be absolute within the package".into());
        }
        part = Some(package_path(value.value())?);
    }
    let mut transform = Transform::from_3mf(node.attribute("transform"))?;
    // Translations use the referencing model's units; the linear matrix is
    // dimensionless. Normalizing both vertices and translations avoids scaling
    // a parent's translation with a referenced child's different unit.
    for translation in &mut transform.0[3][..3] {
        *translation *= unit;
    }
    if transform.0.iter().flatten().any(|n| !n.is_finite()) {
        return Err("3MF transform exceeds numeric range".into());
    }
    Ok(Reference {
        part,
        object: id(node, "objectid")?,
        transform,
    })
}

/// Read one unit-normalized model part with resource identifiers scoped to that part.
///
/// # Errors
///
/// Core/extension XML, resources, meshes, materials or aggregate budgets are invalid or unsupported.
#[allow(
    clippy::cast_possible_truncation,
    reason = "The mean of three bounded RGB bytes remains within the byte range."
)]
#[allow(
    clippy::too_many_lines,
    reason = "Keep the format record dispatch, validation and its resource checks together without changing geometry evaluation."
)]
fn parse_part(xml: &str, root: bool, budget: &mut Budget) -> Result<ModelPart> {
    let doc = roxmltree::Document::parse(xml)?;
    let model = doc.root_element();
    if !model.has_tag_name((CORE, "model")) {
        return Err("expected a 3MF core model element".into());
    }
    if let Some(extensions) = model.attribute("requiredextensions") {
        for prefix in extensions.split_whitespace() {
            let namespace = model.lookup_namespace_uri(Some(prefix));
            // Direct colors and textures are supported; complex property resources are rejected below.
            if !matches!(namespace, Some(MATERIAL | PRODUCTION)) {
                return Err(format!("required 3MF extension {prefix} is not implemented").into());
            }
        }
    }
    let unit = unit_scale(model)?;
    let resources = core_child(model, "resources")?.ok_or("3MF model has no resources")?;
    let mut all_ids = HashSet::new();
    let mut colors: HashMap<u32, Vec<[u8; 3]>> = HashMap::new();
    let mut textures = HashMap::new();
    let mut groups = HashMap::new();
    for resource in resources.children().filter(roxmltree::Node::is_element) {
        consume(&mut budget.resources, MAX_RESOURCES, "resource")?;
        let resource_id = id(resource, "id")?;
        if resource_id == 0 {
            return Err("3MF resource IDs must be positive".into());
        }
        if !all_ids.insert(resource_id) {
            return Err("duplicate 3MF resource ID".into());
        }
        match resource.tag_name().name() {
            "basematerials" | "colorgroup" => {
                let palette = resource
                    .children()
                    .filter(roxmltree::Node::is_element)
                    .map(|n| {
                        color(attribute(
                            n,
                            if n.tag_name().name() == "base" {
                                "displaycolor"
                            } else {
                                "color"
                            },
                        )?)
                    })
                    .collect::<Result<Vec<_>>>()?;
                colors.insert(resource_id, palette);
            }
            "object" => {}
            "texture2d" => {
                textures.insert(resource_id, texture_resource(resource)?);
            }
            "texture2dgroup" => {
                groups.insert(resource_id, texture_group(resource, budget)?);
            }
            // Complex texture/material properties cannot be rendered faithfully by this importer.
            "compositematerials" | "multiproperties" => {
                return Err(
                    "3MF composite materials and multiproperties are not implemented".into(),
                );
            }
            _ => {
                return Err(
                    format!("unsupported 3MF resource {}", resource.tag_name().name()).into(),
                );
            }
        }
    }
    if groups
        .values()
        .any(|group| !textures.contains_key(&group.texture))
    {
        return Err("3MF texture coordinate group references a missing texture".into());
    }
    let mut objects = HashMap::new();
    for resource in resources
        .children()
        .filter(|n| n.has_tag_name((CORE, "object")))
    {
        let object_id = id(resource, "id")?;
        let property_group: Option<u32> = resource.attribute("pid").map(str::parse).transpose()?;
        let object_pindex: usize = resource
            .attribute("pindex")
            .map(str::parse)
            .transpose()?
            .unwrap_or(0);
        let mut object = Object {
            triangles: Vec::new(),
            textures: BTreeMap::new(),
            components: Vec::new(),
        };
        let mesh = core_child(resource, "mesh")?;
        let components = core_child(resource, "components")?;
        if mesh.is_some() && components.is_some() {
            return Err("3MF object cannot contain both mesh and components".into());
        }
        if let Some(mesh) = mesh {
            let vertices_node = core_child(mesh, "vertices")?.ok_or("3MF mesh has no vertices")?;
            let mut vertices = Vec::new();
            for node in vertices_node
                .children()
                .filter(|n| n.has_tag_name((CORE, "vertex")))
            {
                consume(&mut budget.vertices, MAX_TRIANGLES, "source vertex")?;
                let vertex = Vec3::new(
                    attribute(node, "x")?.parse()?,
                    attribute(node, "y")?.parse()?,
                    attribute(node, "z")?.parse()?,
                ) * unit;
                if !vertex.is_finite() {
                    return Err("3MF contains non-finite vertices".into());
                }
                vertices.push(vertex);
            }
            let triangles = core_child(mesh, "triangles")?.ok_or("3MF mesh has no triangles")?;
            for node in triangles
                .children()
                .filter(|n| n.has_tag_name((CORE, "triangle")))
            {
                consume(&mut budget.triangles, MAX_TRIANGLES, "source triangle")?;
                let indices = [id(node, "v1")?, id(node, "v2")?, id(node, "v3")?];
                if indices.iter().any(|&i| i as usize >= vertices.len()) {
                    return Err("3MF triangle references a missing vertex".into());
                }
                let pid: Option<u32> = node
                    .attribute("pid")
                    .map(str::parse)
                    .transpose()?
                    .or(property_group);
                let triangle_color = if let Some(pid) = pid {
                    let p1: usize = node
                        .attribute("p1")
                        .map(str::parse)
                        .transpose()?
                        .unwrap_or(object_pindex);
                    let p2: usize = node
                        .attribute("p2")
                        .map(str::parse)
                        .transpose()?
                        .unwrap_or(p1);
                    let p3: usize = node
                        .attribute("p3")
                        .map(str::parse)
                        .transpose()?
                        .unwrap_or(p1);
                    if let Some(palette) = colors.get(&pid) {
                        if [p1, p2, p3].iter().any(|&i| i >= palette.len()) {
                            return Err("3MF color index is out of range".into());
                        }
                        Some(std::array::from_fn(|channel| {
                            ((u32::from(palette[p1][channel])
                                + u32::from(palette[p2][channel])
                                + u32::from(palette[p3][channel]))
                                / 3) as u8
                        }))
                    } else if let Some(group) = groups.get(&pid) {
                        if [p1, p2, p3]
                            .iter()
                            .any(|&index| index >= group.coordinates.len())
                        {
                            return Err("3MF texture coordinate index is out of range".into());
                        }
                        object.textures.insert(
                            object.triangles.len(),
                            TextureMapping {
                                texture: group.texture,
                                coordinates: [p1, p2, p3].map(|index| group.coordinates[index]),
                            },
                        );
                        None
                    } else {
                        return Err("3MF color or texture property group is missing".into());
                    }
                } else {
                    None
                };
                object.triangles.push(Triangle {
                    vertices: indices.map(|i| vertices[i as usize]),
                    color: triangle_color,
                });
            }
        }
        if let Some(components) = components {
            for component in components
                .children()
                .filter(|n| n.has_tag_name((CORE, "component")))
            {
                object
                    .components
                    .push(reference(component, root, unit, budget)?);
            }
        }
        objects.insert(object_id, object);
    }
    let mut build = Vec::new();
    if root {
        let element = core_child(model, "build")?.ok_or("3MF root model has no build")?;
        for item in element
            .children()
            .filter(|n| n.has_tag_name((CORE, "item")))
        {
            build.push(reference(item, true, unit, budget)?);
        }
    }
    // Production consumers ignore child builds, including invalid or absent
    // child build entries. Only the selected root model drives the scene.
    Ok(ModelPart {
        objects,
        build,
        textures,
    })
}

/// Validate the multipart object graph and instantiate only the root build items.
///
/// # Errors
///
/// Parts/objects are missing, cyclic or exceed nesting/output limits.
fn render_parts(root: &str, parts: &HashMap<String, ModelPart>) -> Result<Scene> {
    let mut heights = HashMap::new();
    let mut active = HashSet::new();
    for (name, part) in parts {
        for &id in part.objects.keys() {
            validate_object(name, id, parts, &mut heights, &mut active)?;
        }
    }
    let part = parts.get(root).ok_or("3MF root part is missing")?;
    let mut scene = Scene::default();
    let mut instances = 0;
    for item in &part.build {
        instantiate(
            item.part.as_deref().unwrap_or(root),
            item.object,
            item.transform,
            parts,
            &mut scene,
            &mut instances,
        )?;
    }
    scene.validate()?;
    Ok(scene)
}

/// Validate reachable component dependencies and memoize their bounded expanded triangle counts.
///
/// # Errors
///
/// Object/part references are missing, cyclic or exceed depth/triangle limits.
fn validate_object(
    part: &str,
    id: u32,
    parts: &HashMap<String, ModelPart>,
    heights: &mut HashMap<(String, u32), usize>,
    active: &mut HashSet<(String, u32)>,
) -> Result<usize> {
    let key = (part.to_owned(), id);
    if let Some(height) = heights.get(&key) {
        return Ok(*height);
    }
    if active.len() >= MAX_DEPTH || !active.insert(key.clone()) {
        return Err("3MF components are cyclic or too deep".into());
    }
    let model = parts
        .get(part)
        .ok_or("3MF references a missing model part")?;
    let object = model
        .objects
        .get(&id)
        .ok_or("3MF references a missing object in its model part")?;
    let mut height = 1;
    for child in &object.components {
        height = height.max(
            1 + validate_object(
                child.part.as_deref().unwrap_or(part),
                child.object,
                parts,
                heights,
                active,
            )?,
        );
    }
    if height > MAX_DEPTH {
        return Err("3MF components exceed the nesting limit".into());
    }
    active.remove(&key);
    heights.insert(key, height);
    Ok(height)
}

/// Append one placed object and recursively expand its referenced components.
///
/// # Errors
///
/// References or transforms are invalid, cyclic or exceed recursion/output limits.
fn instantiate(
    part: &str,
    id: u32,
    transform: Transform,
    parts: &HashMap<String, ModelPart>,
    scene: &mut Scene,
    instances: &mut usize,
) -> Result<()> {
    consume(instances, MAX_REFERENCES, "instantiated object")?;
    if transform.0.iter().flatten().any(|value| !value.is_finite()) {
        return Err("3MF composed transform exceeds numeric range".into());
    }
    let model = parts
        .get(part)
        .ok_or("3MF references a missing model part")?;
    let object = model
        .objects
        .get(&id)
        .ok_or("3MF references a missing object in its model part")?;
    if scene.triangles.len().saturating_add(object.triangles.len()) > MAX_TRIANGLES {
        return Err("3MF instantiated scene exceeds triangle limit".into());
    }
    let offset = scene.triangles.len();
    scene
        .triangles
        .extend(object.triangles.iter().map(|triangle| Triangle {
            vertices: triangle.vertices.map(|v| transform.apply(v)),
            color: triangle.color,
        }));
    for (&index, mapping) in &object.textures {
        let texture = model
            .textures
            .get(&mapping.texture)
            .ok_or("3MF triangle references a missing texture")?;
        let image = texture
            .image
            .as_ref()
            .ok_or("3MF texture image has not been loaded")?;
        scene.appearances.insert(
            offset + index,
            TriangleAppearance {
                texcoords: Some(mapping.coordinates),
                texture: Some(Texture {
                    image: Arc::clone(image),
                    wrap_s: texture.wrap_s,
                    wrap_t: texture.wrap_t,
                    filter: texture.filter,
                    min_filter: texture.filter,
                    interpolation_space: TextureInterpolationSpace::Srgb,
                }),
                ..TriangleAppearance::default()
            },
        );
    }
    for child in &object.components {
        instantiate(
            child.part.as_deref().unwrap_or(part),
            child.object,
            transform.then(child.transform),
            parts,
            scene,
            instances,
        )?;
    }
    Ok(())
}

#[cfg(test)]
/// Parse a single authored XML part without constructing a ZIP test package.
fn parse(xml: &str) -> Result<Scene> {
    let part = parse_part(xml, true, &mut Budget::default())?;
    render_parts("root.model", &HashMap::from([("root.model".into(), part)]))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fmt::Write as _;
    use std::io::Write;

    fn model(resources: &str, build: &str) -> String {
        format!(
            "<model xmlns=\"{CORE}\"><resources>{resources}</resources><build>{build}</build></model>"
        )
    }
    const MESH: &str = "<object id=\"1\"><mesh><vertices><vertex x=\"0\" y=\"0\" z=\"0\"/><vertex x=\"1\" y=\"0\" z=\"0\"/><vertex x=\"0\" y=\"1\" z=\"0\"/></vertices><triangles><triangle v1=\"0\" v2=\"1\" v3=\"2\"/></triangles></mesh></object>";
    #[test]
    fn build_and_component_transforms_compose() {
        let xml = model(
            &format!(
                "{MESH}<object id=\"2\"><components><component objectid=\"1\" transform=\"1 0 0 0 1 0 0 0 1 10 0 0\"/></components></object>"
            ),
            "<item objectid=\"2\" transform=\"2 0 0 0 2 0 0 0 2 0 3 0\"/>",
        );
        let scene = parse(&xml).unwrap();
        assert_eq!(scene.triangles[0].vertices[0], Vec3::new(20., 3., 0.));
        assert_eq!(scene.triangles[0].vertices[1], Vec3::new(22., 3., 0.));
    }
    #[test]
    fn cycles_missing_objects_and_bad_indices_fail() {
        assert!(
            parse(&model(
                "<object id=\"1\"><components><component objectid=\"1\"/></components></object>",
                "<item objectid=\"1\"/>"
            ))
            .is_err()
        );
        assert!(parse(&model(MESH, "<item objectid=\"2\"/>")).is_err());
        assert!(
            parse(&model(
                &MESH.replace("v3=\"2\"", "v3=\"3\""),
                "<item objectid=\"1\"/>"
            ))
            .is_err()
        );
    }
    #[test]
    fn package_paths_decode_and_validate() {
        assert_eq!(package_path("/3D/a%20b.model").unwrap(), "3d/a b.model");
        assert_eq!(package_path("/3D/100%25.model").unwrap(), "3d/100%.model");
        assert_eq!(
            relationship_target("../parts/a.model", "3d").unwrap(),
            "parts/a.model"
        );
        for path in [
            "../a.model",
            "file:/tmp/a.model",
            "//3D/a.model",
            "/3D/%2e%2e/a.model",
            "/3D/a%2fb.model/../c.model",
            "/3D/a.model?x",
            "/3D/a%00.model",
        ] {
            assert!(package_path(path).is_err(), "accepted {path}");
        }
        assert!(relationship_target("../../a.model", "3d").is_err());
    }

    fn production_model(unit: &str, resources: &str, build: Option<&str>) -> String {
        let build = build
            .map(|items| format!("<build>{items}</build>"))
            .unwrap_or_default();
        format!(
            "<model xmlns=\"{CORE}\" xmlns:p=\"{PRODUCTION}\" requiredextensions=\"p\" unit=\"{unit}\"><resources>{resources}</resources>{build}</model>"
        )
    }

    fn relationships(targets: &[&str]) -> String {
        let relations = targets
            .iter()
            .enumerate()
            .fold(String::new(), |mut text, (i, target)| {
                let _ = write!(
                    text,
                    "<Relationship Type=\"{MODEL_RELATIONSHIP}\" Target=\"{target}\" Id=\"r{i}\"/>"
                );
                text
            });
        format!("<Relationships xmlns=\"{RELATIONSHIPS}\">{relations}</Relationships>")
    }

    /// Each test owns a unique archive and removes it even after an error.
    fn with_package<T>(
        entries: &[(&str, &str)],
        read: impl FnOnce(&Path) -> Result<T>,
    ) -> Result<T> {
        let bytes: Vec<_> = entries
            .iter()
            .map(|&(name, contents)| (name, contents.as_bytes()))
            .collect();
        with_byte_package(&bytes, read)
    }

    /// Write a temporary ZIP containing arbitrary XML or image bytes and clean it up.
    ///
    /// # Errors
    /// Returns an error if ZIP writing or the supplied package operation fails.
    fn with_byte_package<T>(
        entries: &[(&str, &[u8])],
        read: impl FnOnce(&Path) -> Result<T>,
    ) -> Result<T> {
        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
        struct Temp(std::path::PathBuf);
        impl Drop for Temp {
            fn drop(&mut self) {
                let _ = std::fs::remove_file(&self.0);
            }
        }
        let path = Temp(std::env::temp_dir().join(format!(
            "catwalk-3mf-test-{}-{}.3mf",
            std::process::id(),
            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
        )));
        let mut writer = zip::ZipWriter::new(std::fs::File::create(&path.0)?);
        for &(name, contents) in entries {
            writer.start_file(
                name,
                zip::write::SimpleFileOptions::default()
                    .compression_method(zip::CompressionMethod::Deflated),
            )?;
            writer.write_all(contents)?;
        }
        writer.finish()?;
        read(&path.0)
    }

    fn package_scene(entries: &[(&str, &str)]) -> Result<Scene> {
        with_package(entries, load)
    }

    fn split_scene(root: &str, child: &str) -> Result<Scene> {
        package_scene(&[
            ("_rels/.rels", &relationships(&["/3D/main.model"])),
            (
                "3D/_rels/main.model.rels",
                &relationships(&["Objects/part%20one.model"]),
            ),
            ("3D/main.model", root),
            ("3D/Objects/part one.model", child),
        ])
    }

    fn close(actual: Vec3, expected: Vec3) {
        assert!(
            (actual - expected).length() < 1e-9,
            "actual={actual:?}, expected={expected:?}"
        );
    }

    #[test]
    fn multipart_ids_colors_units_and_nested_transforms_are_scoped() {
        let root_mesh = MESH.replace("id=\"1\"", "id=\"1\" pid=\"3\"");
        let child_mesh = root_mesh.clone();
        let root = production_model(
            "centimeter",
            &format!(
                "<basematerials id=\"3\"><base displaycolor=\"#FF0000\"/></basematerials>{root_mesh}<object id=\"2\"><components><component p:path=\"/3D/Objects/part%20one.model\" objectid=\"2\" transform=\"2 0 0 0 2 0 0 0 2 3 0 0\"/></components></object>"
            ),
            Some(
                "<item objectid=\"1\"/><item objectid=\"2\" transform=\"0 1 0 -1 0 0 0 0 1 0 4 0\"/>",
            ),
        );
        let child = production_model(
            "inch",
            &format!(
                "<basematerials id=\"3\"><base displaycolor=\"#0000FF\"/></basematerials>{child_mesh}<object id=\"2\"><components><component objectid=\"1\" transform=\"1 0 0 0 1 0 0 0 1 1 0 0\"/></components></object>"
            ),
            None,
        );
        let scene = split_scene(&root, &child).unwrap();
        assert_eq!(scene.triangles.len(), 2);
        assert_eq!(scene.triangles[0].color, Some([255, 0, 0]));
        assert_eq!(scene.triangles[1].color, Some([0, 0, 255]));
        close(scene.triangles[0].vertices[1], Vec3::new(10., 0., 0.));
        close(scene.triangles[1].vertices[0], Vec3::new(0., 120.8, 0.));
        close(scene.triangles[1].vertices[1], Vec3::new(0., 171.6, 0.));
        close(scene.triangles[1].vertices[2], Vec3::new(-50.8, 120.8, 0.));
        let v = scene.triangles[1].vertices;
        assert!(((v[1] - v[0]).cross(v[2] - v[0]).length() / 2. - 1290.32).abs() < 1e-8);
    }

    #[test]
    fn direct_build_path_accepts_alternate_prefix_and_ignores_child_build() {
        let root = production_model(
            "millimeter",
            "",
            Some("<item p:path=\"/3D/Objects/part%20one.model\" objectid=\"1\"/>"),
        )
        .replace("xmlns:p=", "xmlns:q=")
        .replace("requiredextensions=\"p\"", "requiredextensions=\"q\"")
        .replace("p:path=", "q:path=");
        let child = production_model(
            "meter",
            MESH,
            Some("<item objectid=\"999\" p:path=\"/missing.model\" transform=\"bad\"/>"),
        );
        let scene = split_scene(&root, &child).unwrap();
        close(scene.triangles[0].vertices[1], Vec3::new(1000., 0., 0.));
        assert_eq!(scene.triangles.len(), 1);
    }

    #[test]
    fn production_namespace_and_required_extensions_remain_strict() {
        let root = production_model(
            "millimeter",
            "",
            Some("<item p:path=\"/3D/Objects/part%20one.model\" objectid=\"1\"/>"),
        );
        let child = production_model("millimeter", MESH, None);
        assert!(split_scene(&root.replace(PRODUCTION, "urn:unknown"), &child).is_err());
        assert!(split_scene(&root.replace("p:path=", "path="), &child).is_err());
        assert!(
            split_scene(
                &root.replace(
                    "/3D/Objects/part%20one.model",
                    "3D/Objects/part%20one.model"
                ),
                &child
            )
            .is_err()
        );
        assert!(
            split_scene(
                &root.replace(
                    "requiredextensions=\"p\"",
                    "xmlns:x=\"urn:unknown\" requiredextensions=\"p x\""
                ),
                &child
            )
            .is_err()
        );
        assert!(split_scene(&root, &child.replace(PRODUCTION, "urn:unknown")).is_err());
    }

    #[test]
    fn missing_parts_relationships_and_object_ids_fail() {
        let root = production_model(
            "millimeter",
            MESH,
            Some("<item p:path=\"/3D/Objects/part%20one.model\" objectid=\"1\"/>"),
        );
        let child = production_model("millimeter", &MESH.replace("id=\"1\"", "id=\"2\""), None);
        let error = split_scene(&root, &child).unwrap_err().to_string();
        assert!(
            error.contains("missing object in its model part"),
            "{error}"
        );
        assert!(
            package_scene(&[
                ("_rels/.rels", &relationships(&["/3D/main.model"])),
                ("3D/main.model", &root)
            ])
            .is_err()
        );
        assert!(
            package_scene(&[
                ("_rels/.rels", &relationships(&["/3D/main.model"])),
                ("3D/main.model", &root),
                (
                    "3D/_rels/main.model.rels",
                    &relationships(&["/3D/Objects/part%20one.model"])
                )
            ])
            .is_err()
        );
        assert!(
            package_scene(&[
                ("_rels/.rels", &relationships(&["/3D/main.model"])),
                ("3D/main.model", &root),
                (
                    "3D/_rels/main.model.rels",
                    &relationships(&["/3D/other.model"])
                ),
                ("3D/Objects/part one.model", &child)
            ])
            .is_err()
        );
    }

    #[test]
    fn duplicate_package_parts_resources_and_relationships_fail() {
        let root = model(MESH, "<item objectid=\"1\"/>");
        assert!(
            package_scene(&[("3D/3dmodel.model", &root), ("3d/3DMODEL.model", &root)]).is_err()
        );
        assert!(parse(&model(&format!("{MESH}{MESH}"), "<item objectid=\"1\"/>")).is_err());
        assert!(
            parse(&model(
                &MESH.replace("id=\"1\"", "id=\"0\""),
                "<item objectid=\"0\"/>"
            ))
            .is_err()
        );
        assert!(model_relationships(&relationships(&["/3D/a.model", "/3d/A.model"]), "").is_err());
        assert!(
            model_relationships(
                &relationships(&["/3D/a.model", "/3D/b.model"]).replace("Id=\"r1\"", "Id=\"r0\""),
                ""
            )
            .is_err()
        );
        assert!(
            model_relationships(
                &relationships(&["/3D/a.model"]).replace("Id=", "TargetMode=\"External\" Id="),
                ""
            )
            .is_err()
        );
    }

    #[test]
    fn child_external_components_and_local_cycles_fail() {
        let root = production_model(
            "millimeter",
            "",
            Some("<item p:path=\"/3D/Objects/part%20one.model\" objectid=\"1\"/>"),
        );
        let child = production_model(
            "millimeter",
            "<object id=\"1\"><components><component p:path=\"/3D/main.model\" objectid=\"1\"/></components></object>",
            None,
        );
        assert!(split_scene(&root, &child).is_err());
        let child = production_model(
            "millimeter",
            "<object id=\"1\"><components><component objectid=\"2\"/></components></object><object id=\"2\"><components><component objectid=\"1\"/></components></object>",
            None,
        );
        assert!(split_scene(&root, &child).is_err());
    }

    #[test]
    fn aggregate_source_and_decompressed_budgets_are_enforced() {
        let xml = model(MESH, "<item objectid=\"1\"/>");
        for mut budget in [
            Budget {
                vertices: MAX_TRIANGLES,
                ..Budget::default()
            },
            Budget {
                triangles: MAX_TRIANGLES,
                ..Budget::default()
            },
            Budget {
                resources: MAX_RESOURCES,
                ..Budget::default()
            },
            Budget {
                references: MAX_REFERENCES,
                ..Budget::default()
            },
        ] {
            assert!(parse_part(&xml, true, &mut budget).is_err());
        }
        let error = with_package(&[("3D/3dmodel.model", &xml)], |path| {
            let mut package = Package::open(path)?;
            package.read(
                "3d/3dmodel.model",
                &mut Budget {
                    bytes: MAX_INPUT_BYTES - xml.len() as u64 + 1,
                    ..Budget::default()
                },
            )
        })
        .unwrap_err()
        .to_string();
        assert!(error.contains("aggregate 512 MiB"), "{error}");
        assert!(parse(&xml.replace("x=\"1\"", "x=\"inf\"")).is_err());
        assert!(parse(&xml.replace("<model ", "<model unit=\"unsupported\" ")).is_err());
        assert!(
            parse(&model(
                &MESH.replace("</object>", "<components/></object>"),
                "<item objectid=\"1\"/>"
            ))
            .is_err()
        );
    }

    #[test]
    fn texture_cache_preserves_mime_and_counts_each_distinct_image_once() {
        let mut png = Vec::new();
        crate::render::write_png(
            &RgbaImage::from_pixel(1, 1, image::Rgba([31, 47, 63, 79])),
            &mut png,
        )
        .unwrap();
        with_byte_package(&[("first.png", &png), ("second.png", &png)], |path| {
            let mut package = Package::open(path)?;
            let mut budget = Budget {
                pixels: MAX_TOTAL_TEXTURE_PIXELS - 1,
                ..Budget::default()
            };
            let first = package.texture("first.png", ImageFormat::Png, &mut budget)?;
            assert_eq!(budget.pixels, MAX_TOTAL_TEXTURE_PIXELS);
            let consumed = budget.bytes;
            let same = package.texture("first.png", ImageFormat::Png, &mut budget)?;
            assert!(Arc::ptr_eq(&first, &same));
            assert_eq!(budget.bytes, consumed);
            assert_eq!(budget.pixels, MAX_TOTAL_TEXTURE_PIXELS);
            assert!(
                package
                    .texture("first.png", ImageFormat::Jpeg, &mut budget)
                    .unwrap_err()
                    .to_string()
                    .contains("content type")
            );
            assert_eq!(budget.bytes, consumed);
            assert!(
                package
                    .texture("second.png", ImageFormat::Png, &mut budget)
                    .unwrap_err()
                    .to_string()
                    .contains("aggregate pixel budget")
            );
            Ok(())
        })
        .unwrap();
    }

    #[test]
    fn encoded_texture_and_coordinate_counts_obey_aggregate_limits() {
        let mut png = Vec::new();
        crate::render::write_png(&RgbaImage::new(1, 1), &mut png).unwrap();
        with_byte_package(&[("image.png", &png)], |path| {
            let mut package = Package::open(path)?;
            let error = package
                .texture(
                    "image.png",
                    ImageFormat::Png,
                    &mut Budget {
                        bytes: MAX_INPUT_BYTES,
                        ..Budget::default()
                    },
                )
                .unwrap_err()
                .to_string();
            assert!(error.contains("aggregate 512 MiB"));
            assert!(package.images.is_empty());
            Ok(())
        })
        .unwrap();
        let xml = format!(
            "<m:texture2dgroup xmlns:m=\"{MATERIAL}\" id=\"1\" texid=\"2\"><m:tex2coord u=\"0\" v=\"0\"/></m:texture2dgroup>"
        );
        let document = roxmltree::Document::parse(&xml).unwrap();
        let error = texture_group(
            document.root_element(),
            &mut Budget {
                texcoords: MAX_TRIANGLES,
                ..Budget::default()
            },
        )
        .err()
        .unwrap()
        .to_string();
        assert!(error.contains("texture coordinate"));
    }

    #[test]
    fn production_model_part_count_is_bounded() {
        let build = (0..MAX_PARTS).fold(String::new(), |mut text, n| {
            let _ = write!(text, "<item p:path=\"/3D/{n}.model\" objectid=\"1\"/>");
            text
        });
        let root = production_model("millimeter", "", Some(&build));
        let error = package_scene(&[("3D/3dmodel.model", &root)])
            .unwrap_err()
            .to_string();
        assert!(error.contains("model-part limit"), "{error}");
    }

    #[test]
    fn deep_and_exponentially_instanced_components_are_bounded() {
        let mut resources = MESH.to_owned();
        for id in 2..=MAX_DEPTH + 1 {
            let _ = write!(
                resources,
                "<object id=\"{id}\"><components><component objectid=\"{}\"/></components></object>",
                id - 1
            );
        }
        assert!(
            parse(&model(
                &resources,
                &format!("<item objectid=\"{}\"/>", MAX_DEPTH + 1)
            ))
            .is_err()
        );
        let mut resources = "<object id=\"1\"><components/></object>".to_owned();
        for id in 2..=21 {
            let _ = write!(
                resources,
                "<object id=\"{id}\"><components><component objectid=\"{}\"/><component objectid=\"{}\"/></components></object>",
                id - 1,
                id - 1
            );
        }
        let error = parse(&model(&resources, "<item objectid=\"21\"/>"))
            .unwrap_err()
            .to_string();
        assert!(error.contains("instantiated object"), "{error}");
    }

    fn zip_bytes(zip64_comment: Option<&[u8]>) -> Vec<u8> {
        let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
        if let Some(extension) = zip64_comment {
            writer.set_raw_zip64_extensible_data_sector(extension.into());
        }
        writer
            .set_comment("a package comment containing PK\u{5}\u{6}")
            .unwrap();
        writer
            .start_file("3D/3dmodel.model", zip::write::SimpleFileOptions::default())
            .unwrap();
        writer
            .write_all(model(MESH, "<item objectid=\"1\"/>").as_bytes())
            .unwrap();
        writer.finish().unwrap().into_inner()
    }

    fn eocd_offset(bytes: &[u8]) -> usize {
        bytes
            .windows(22)
            .enumerate()
            .rev()
            .find(|(i, record)| {
                record.starts_with(b"PK\x05\x06")
                    && i + 22 + usize::from(zip_u16(record, 20).unwrap()) == bytes.len()
            })
            .unwrap()
            .0
    }

    #[test]
    #[allow(
        clippy::cast_possible_truncation,
        reason = "Small authored test payload lengths fit their native field widths; preserve the exact binary fixture encoding."
    )]
    fn raw_zip_duplicates_are_rejected_before_library_coalescing() {
        let mut bytes = zip_bytes(None);
        let eocd = eocd_offset(&bytes);
        let directory = zip_u32(&bytes, eocd + 16).unwrap() as usize;
        let record = bytes[directory..eocd].to_vec();
        bytes.splice(eocd..eocd, record.iter().copied());
        let eocd = eocd + record.len();
        bytes[eocd + 8..eocd + 12].copy_from_slice(&[2, 0, 2, 0]);
        bytes[eocd + 12..eocd + 16].copy_from_slice(&(2 * record.len() as u32).to_le_bytes());
        // The library accepts the two records and silently exposes one entry.
        assert_eq!(
            zip::ZipArchive::new(std::io::Cursor::new(&bytes))
                .unwrap()
                .len(),
            1
        );
        let error = validate_zip_directory(&mut std::io::Cursor::new(&bytes), bytes.len() as u64)
            .unwrap_err()
            .to_string();
        assert!(error.contains("duplicate ZIP archive part"), "{error}");
    }

    #[test]
    fn zip64_directory_handles_extensions_comments_and_archive_prefixes() {
        for comment in [Vec::new(), b"ZIP64 metadata".to_vec(), vec![0; 70_000]] {
            let bytes = zip_bytes(Some(&comment));
            assert_eq!(
                validate_zip_directory(&mut std::io::Cursor::new(&bytes), bytes.len() as u64)
                    .unwrap(),
                1
            );
            assert_eq!(
                zip::ZipArchive::new(std::io::Cursor::new(&bytes))
                    .unwrap()
                    .len(),
                1
            );
            let mut prefixed = b"an archive prefix with no filesystem effect".to_vec();
            prefixed.extend_from_slice(&bytes);
            assert_eq!(
                validate_zip_directory(&mut std::io::Cursor::new(&prefixed), prefixed.len() as u64)
                    .unwrap(),
                1
            );
        }
    }

    #[test]
    #[allow(
        clippy::cast_possible_truncation,
        reason = "Small authored test payload lengths fit their native field widths; preserve the exact binary fixture encoding."
    )]
    fn raw_zip_directory_counts_and_extents_are_bounded() {
        let original = zip_bytes(None);
        for length in 0..original.len() {
            assert!(
                validate_zip_directory(
                    &mut std::io::Cursor::new(&original[..length]),
                    length as u64
                )
                .is_err()
            );
        }
        for (offset, value) in [
            (8, [0, 0, 0, 0]),
            (12, u32::MAX.to_le_bytes()),
            (16, u32::MAX.to_le_bytes()),
        ] {
            let mut bytes = original.clone();
            let eocd = eocd_offset(&bytes);
            bytes[eocd + offset..eocd + offset + 4].copy_from_slice(&value);
            assert!(
                validate_zip_directory(&mut std::io::Cursor::new(&bytes), bytes.len() as u64)
                    .is_err()
            );
        }
        let mut bytes = zip_bytes(Some(&[]));
        let eocd = eocd_offset(&bytes);
        let locator = eocd - 20;
        let zip64 = zip_u64(&bytes, locator + 8).unwrap() as usize;
        bytes[zip64 + 24..zip64 + 40].copy_from_slice(
            &[
                (MAX_RESOURCES as u64 + 1).to_le_bytes(),
                (MAX_RESOURCES as u64 + 1).to_le_bytes(),
            ]
            .concat(),
        );
        bytes[eocd + 8..eocd + 12].fill(255);
        let error = validate_zip_directory(&mut std::io::Cursor::new(&bytes), bytes.len() as u64)
            .unwrap_err()
            .to_string();
        assert!(error.contains("too many archive entries"), "{error}");
    }
}