Skip to main content

brep_kernel/io/three_mf/
mod.rs

1//! 3MF (3D Manufacturing Format) import and export. [`write_3mf`] exports
2//! solids; [`write_3mf_meshes`] preserves imported mesh appearance.
3//!
4//! [`read_3mf`] reads a 3MF package (an OPC ZIP container) and returns the
5//! meshes its `<resources>` define plus the flattened list of instances the
6//! `<build>` places, in millimetres. It is a READER: the triangle soup it
7//! produces goes into the same mesh-to-solid chain STL and OBJ use
8//! (`brep_reconstruction::stl_conversion::convert_stl_mesh_to_step`); no
9//! geometry is built here.
10//!
11//! # What is supported
12//!
13//! The core specification (3MF Core Specification 1.x,
14//! `http://schemas.microsoft.com/3dmanufacturing/core/2015/02`):
15//!
16//! * `<model unit>` — `micron`, `millimeter`, `centimeter`, `inch`, `foot`,
17//!   `meter`, defaulting to `millimeter`; every coordinate and translation is
18//!   converted to millimetres, the unit the kernel works in.
19//! * `<resources>` with `<object id type>` carrying either a `<mesh>`
20//!   (`<vertices><vertex x y z>`, `<triangles><triangle v1 v2 v3>`) or a
21//!   `<components>` list of `<component objectid transform>`.
22//! * `<build>` with `<item objectid transform>`.
23//! * The 3x4 row-vector `transform` attribute on components and items, composed
24//!   inner-to-outer, with the winding of a mirrored instance reversed so the
25//!   soup stays outward-facing.
26//!
27//! # Colours
28//!
29//! The core specification's one property group IS read: `<basematerials>` with
30//! its `<base displaycolor="#RRGGBB">` entries, an object's `pid`/`pindex`
31//! default and a triangle's own `pid`/`p1`. Each triangle of
32//! [`ThreeMfMesh::triangle_colors`] (and of the flattened
33//! [`ThreeMfReadResult::triangle_colors`]) is the colour it resolves to, or
34//! `None` — a triangle with no resolvable RGB property. The vectors are empty
35//! when no triangle resolves. Legacy malformed or dangling base-material
36//! references remain `None`; extension references are checked explicitly. This is what the
37//! writer ([`write_3mf`]) emits, so an export re-imports with its colours.
38//!
39//! # Materials extensions
40//!
41//! Colour groups preserve RGBA at each triangle corner. Texture groups retain
42//! per-corner UVs, packaged PNG bytes and sampling settings. Composite materials
43//! retain their constituent display colours and fractions. RGB-only consumers
44//! receive a per-triangle preview; textures have no invented flat colour.
45//! [`write_3mf_meshes`] exports this appearance without solid reconstruction.
46//!
47//! Required extension prefixes are resolved by namespace URI. Unknown required
48//! extensions and unsupported material resources refuse by name. Simple beam
49//! lattices remain named, placed non-solid data alongside their triangle meshes.
50//! Clipping, balls, beam properties and representation meshes refuse precisely;
51//! consumers must not present the triangle soup alone as the complete solid.
52//! Other optional extension subtrees and metadata are skipped.
53//!
54//! Anything the core specification makes required and the file omits — the
55//! start-part relationship, an object id, a triangle's vertex indices, a
56//! component's or item's `objectid` — is refused with a [`ThreeMfError`]
57//! naming the package part it was read from.
58//!
59//! # Bounds
60//!
61//! Nothing here grows to fit its input. The container refuses encryption,
62//! ZIP64, multi-disk packages and any compression but stored and deflate; a
63//! part is refused before decompression when it DECLARES more than
64//! [`MAX_PART_BYTES`], the deflate output stops at the declared size, and every
65//! part's CRC-32 and length are verified after it. The XML reader refuses a
66//! `<!DOCTYPE>` outright (so no entity is expanded, internal or external) and
67//! caps nesting. The model is held to [`MAX_MESH_VERTICES`],
68//! [`MAX_MESH_TRIANGLES`], [`MAX_INSTANCES`], [`MAX_TOTAL_TRIANGLES`] and
69//! [`MAX_COMPONENT_DEPTH`]. Every offset in the container is computed with
70//! `checked_add`, because the kernel's release profile sets
71//! `overflow-checks = false`.
72//!
73//! # Dependency review (why the container is hand-rolled)
74//!
75//! `BREP_kernel` publishes to crates.io and compiles to wasm on nine declared
76//! dependencies, seven of them unconditional; `zip` and `flate2` appear nowhere
77//! in `BREP_kernel/Cargo.lock` (they are in `BREP_app`'s lock only, pulled in by
78//! the egui/image stack, not by anything the kernel links). `zip` with
79//! `default-features = false, features = ["deflate"]` still adds `flate2`,
80//! `miniz_oxide`, `crc32fast`, `adler2` and their support crates to a published
81//! geometry kernel. The container here is ~1000 lines of reader for a format the
82//! kernel needs in one place, matching how STEP, IGES, STL and OBJ are already
83//! read: [`zip`] parses the central directory, [`inflate`] implements RFC 1951,
84//! [`xml`] is a bounded pull parser. Every one of them refuses rather than grows.
85
86pub(crate) mod inflate;
87mod model;
88mod bambu_write;
89mod mesh_write;
90pub use mesh_write::write_3mf_meshes;
91mod write;
92mod xml;
93mod zip;
94
95pub use bambu_write::{write_3mf_bambu, ThreeMfBambuReport, BAMBU_MODEL_SETTINGS_PART};
96pub use write::{write_3mf, ThreeMfSolid, ThreeMfWriteReport};
97
98
99use serde::Serialize;
100
101/// The 3MF core-specification namespace this reader accepts elements from.
102pub const MATERIAL_NAMESPACE: &str = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02";
103pub const BEAM_NAMESPACE: &str = "http://schemas.microsoft.com/3dmanufacturing/beamlattice/2017/02";
104pub const CORE_NAMESPACE: &str = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02";
105/// The OPC relationships namespace of `_rels/.rels`.
106const RELATIONSHIP_NAMESPACE: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
107/// The relationship type naming the package's primary 3D model part.
108const MODEL_RELATIONSHIP: &str = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel";
109/// The package-level relationships part; required of every OPC package.
110const RELATIONSHIP_PART: &str = "_rels/.rels";
111
112/// Largest part this reader will expand, compressed or stored. A 3MF model part
113/// is XML: 256 MiB is roughly five million triangles of it.
114pub const MAX_PART_BYTES: usize = 256 * 1024 * 1024;
115/// Largest vertex and triangle counts accepted for one `<mesh>`.
116pub const MAX_MESH_VERTICES: usize = 8_000_000;
117pub const MAX_MESH_TRIANGLES: usize = 16_000_000;
118/// Largest number of placements the `<build>` may flatten to.
119pub const MAX_INSTANCES: usize = 65_536;
120/// Largest flattened triangle total across all instances.
121pub const MAX_TOTAL_TRIANGLES: usize = 32_000_000;
122/// Deepest `<components>` nesting followed when flattening. The core spec's
123/// "an object must be defined before it is referenced" already forbids cycles;
124/// this bounds the work a legal but pathological file can ask for.
125pub const MAX_COMPONENT_DEPTH: usize = 32;
126
127/// Why a 3MF package was refused. Every variant that belongs to a package part
128/// names it, so the message says where in the container the fault is.
129#[derive(Clone, Debug, PartialEq, Eq)]
130pub enum ThreeMfError {
131    /// The bytes are not a readable OPC/ZIP container at all.
132    Container(String),
133    /// A part is in the container but its bytes cannot be recovered: a bad
134    /// local header, a short read, a failed CRC-32.
135    Damaged { part: String, detail: String },
136    /// A part the core specification requires is absent.
137    MissingPart { part: String, detail: String },
138    /// A container or format feature this reader refuses on purpose.
139    Unsupported { part: String, detail: String },
140    /// A part exceeds one of this reader's documented bounds.
141    Bounds { part: String, detail: String },
142    /// A part is not well-formed XML.
143    Xml { part: String, detail: String },
144    /// A part is well-formed XML but violates the core specification.
145    Model { part: String, detail: String },
146}
147
148impl ThreeMfError {
149    /// The package part the failure was found in, when it belongs to one.
150    pub fn part(&self) -> Option<&str> {
151        match self {
152            Self::Container(_) => None,
153            Self::Damaged { part, .. }
154            | Self::MissingPart { part, .. }
155            | Self::Unsupported { part, .. }
156            | Self::Bounds { part, .. }
157            | Self::Xml { part, .. }
158            | Self::Model { part, .. } => Some(part),
159        }
160    }
161}
162
163impl core::fmt::Display for ThreeMfError {
164    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
165        match self {
166            Self::Container(detail) => write!(f, "3MF package: {detail}"),
167            Self::Damaged { part, detail } => write!(f, "3MF '{part}' is damaged: {detail}"),
168            Self::MissingPart { part, detail } => write!(f, "3MF '{part}' is missing: {detail}"),
169            Self::Unsupported { part, detail } => write!(f, "3MF '{part}': {detail}"),
170            Self::Bounds { part, detail } => write!(f, "3MF '{part}' exceeds a bound: {detail}"),
171            Self::Xml { part, detail } => write!(f, "3MF '{part}' is not well-formed: {detail}"),
172            Self::Model { part, detail } => write!(f, "3MF '{part}': {detail}"),
173        }
174    }
175}
176
177impl std::error::Error for ThreeMfError {}
178
179/// The `unit` a model part declares, with its conversion to millimetres.
180#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
181pub enum ThreeMfUnit {
182    Micron,
183    Millimeter,
184    Centimeter,
185    Inch,
186    Foot,
187    Meter,
188}
189
190impl ThreeMfUnit {
191    /// The spec's unit table (3MF Core, `<model unit>`), in millimetres.
192    pub fn millimetres(self) -> f64 {
193        match self {
194            Self::Micron => 0.001,
195            Self::Millimeter => 1.0,
196            Self::Centimeter => 10.0,
197            Self::Inch => 25.4,
198            Self::Foot => 304.8,
199            Self::Meter => 1000.0,
200        }
201    }
202
203    pub fn name(self) -> &'static str {
204        match self {
205            Self::Micron => "micron",
206            Self::Millimeter => "millimeter",
207            Self::Centimeter => "centimeter",
208            Self::Inch => "inch",
209            Self::Foot => "foot",
210            Self::Meter => "meter",
211        }
212    }
213
214    fn parse(text: &str) -> Option<Self> {
215        Some(match text {
216            "micron" => Self::Micron,
217            "millimeter" => Self::Millimeter,
218            "centimeter" => Self::Centimeter,
219            "inch" => Self::Inch,
220            "foot" => Self::Foot,
221            "meter" => Self::Meter,
222            _ => return None,
223        })
224    }
225}
226
227/// Lossless per-corner appearance, in triangle winding order.
228#[derive(Clone, Debug, PartialEq, Serialize)]
229pub enum ThreeMfAppearance {
230    Colors([[u8; 4]; 3]),
231    Texture { texture_id: u32, uv: [[f64; 2]; 3] },
232    Composite { colors: Vec<[u8; 3]>, weights: [Vec<f64>; 3] },
233}
234
235impl ThreeMfAppearance {
236    /// RGB preview for consumers that support only one colour per face.
237    pub fn preview_rgb(&self) -> Option<[u8; 3]> {
238        let mut rgb = [0; 3];
239        match self {
240            Self::Colors(colors) => {
241                // Core 3MF requires a consumer without gradients to use p1.
242                rgb.copy_from_slice(&colors[0][..3]);
243            }
244            Self::Composite { colors, weights } => {
245                let weights = &weights[0];
246                let sum: f64 = weights.iter().take(colors.len()).sum();
247                for i in 0..3 {
248                    let mixed: f64 = colors.iter().enumerate().map(|(j, c)| {
249                        let fraction = if sum > 0.0 { weights.get(j).copied().unwrap_or(0.0) / sum }
250                            else { 1.0 / colors.len() as f64 };
251                        c[i] as f64 * fraction
252                    }).sum();
253                    rgb[i] = mixed.round().clamp(0.0,255.0) as u8;
254                }
255            }
256            Self::Texture { .. } => return None,
257        }
258        Some(rgb)
259    }
260    fn reverse(&mut self) {
261        match self {
262            Self::Colors(c) => c.swap(1, 2),
263            Self::Texture { uv, .. } => uv.swap(1, 2),
264            Self::Composite { weights, .. } => weights.swap(1, 2),
265        }
266    }
267}
268
269/// Beam parameters retained as non-solid data, in object-local millimetres.
270/// Apply the containing instance's full affine transform to the beam surface;
271/// transforming only the endpoints/radii is insufficient for shear or scaling.
272#[derive(Clone, Debug, PartialEq, Serialize)]
273pub struct ThreeMfBeam {
274    pub vertices: [u32; 2],
275    pub radii: [f64; 2],
276    pub caps: [String; 2],
277}
278
279/// A lattice retained independently of the triangle soup, never claimed as a solid.
280#[derive(Clone, Debug, PartialEq, Serialize)]
281pub struct ThreeMfBeamLattice {
282    pub min_length: f64,
283    pub beams: Vec<ThreeMfBeam>,
284}
285
286/// A packaged PNG and its sampling settings. Pixels remain encoded.
287#[derive(Clone, Debug, PartialEq, Serialize)]
288pub struct ThreeMfTexture {
289    pub id: u32,
290    pub path: String,
291    pub png: Vec<u8>,
292    pub tile_u: String,
293    pub tile_v: String,
294    pub filter: String,
295}
296
297/// One `<object>`'s mesh, in millimetres and in the object's own coordinates.
298/// Shared: an object placed three times is ONE entry here and three
299/// [`ThreeMfInstance`]s.
300#[derive(Clone, Debug, Default, PartialEq, Serialize)]
301pub struct ThreeMfMesh {
302    /// The id of the `<object>` this mesh belongs to.
303    pub object_id: u32,
304    /// Non-solid lattice data; named and placed through the mesh instances.
305    pub beam_lattice: Option<ThreeMfBeamLattice>,
306    /// Vertex coordinates as xyz triples, millimetres.
307    pub positions: Vec<f64>,
308    /// Triangle corners, three indices into `positions`/3.
309    pub indices: Vec<u32>,
310    /// One entry per triangle — the 8-bit sRGB colour its base material gives
311    /// it, or `None` — when at least one triangle of the mesh resolves to a
312    /// colour; EMPTY otherwise. See the module doc's "Colours".
313    pub triangle_colors: Vec<Option<[u8; 3]>>,
314    /// Lossless appearance parallel to triangles; empty when absent.
315    pub triangle_appearance: Vec<Option<ThreeMfAppearance>>,
316}
317
318impl ThreeMfMesh {
319    pub fn vertex_count(&self) -> usize {
320        self.positions.len() / 3
321    }
322    pub fn triangle_count(&self) -> usize {
323        self.indices.len() / 3
324    }
325}
326
327/// One placement of one mesh: a `<build><item>`, or a `<component>` reached
328/// through one, with the transforms from the item down composed.
329#[derive(Clone, Debug, PartialEq, Serialize)]
330pub struct ThreeMfInstance {
331    /// The mesh-bearing object placed (not the item's `objectid` when the item
332    /// pointed at a `<components>` object).
333    pub object_id: u32,
334    /// Index into [`ThreeMfReadResult::meshes`].
335    pub mesh: usize,
336    /// The composed 3x4 row-vector transform, in 3MF attribute order
337    /// (`m00 m01 m02 m10 m11 m12 m20 m21 m22 m30 m31 m32`), translation in mm.
338    pub transform: [f64; 12],
339    /// Where this instance's geometry sits in the flattened buffers: its
340    /// vertices are `positions[first_vertex * 3 ..][.. vertex_count * 3]` and
341    /// its triangles `indices[first_triangle * 3 ..][.. triangle_count * 3]`.
342    /// Instances are laid out in order and never share a vertex, which is what
343    /// lets a consumer take one body out without re-flattening the build.
344    pub first_vertex: usize,
345    pub vertex_count: usize,
346    pub first_triangle: usize,
347    pub triangle_count: usize,
348    /// The placed object's `name`, or failing that the nearest named
349    /// `<components>` object above it; `None` when nothing on the way was
350    /// named. Carries no geometry.
351    pub name: Option<String>,
352}
353
354impl ThreeMfInstance {
355    /// Place an object-local point: `x' = x·m00 + y·m10 + z·m20 + m30`.
356    pub fn transform_point(&self, point: [f64; 3]) -> [f64; 3] {
357        transform_point(&self.transform, point)
358    }
359}
360
361/// Everything [`read_3mf`] recovered from a package.
362#[derive(Clone, Debug, Serialize)]
363pub struct ThreeMfReadResult {
364    /// The part the model was read from (from the start-part relationship).
365    pub model_part: String,
366    /// The unit the file declared, before conversion.
367    pub unit: ThreeMfUnit,
368    /// Packaged textures referenced by material resources.
369    pub textures: Vec<ThreeMfTexture>,
370    /// One entry per mesh-bearing `<object>` in `<resources>`, in document
371    /// order — including any the build never places.
372    pub meshes: Vec<ThreeMfMesh>,
373    /// The `<build>`, flattened through `<components>`: one entry per placed
374    /// mesh. Objects of a type other than `model` are not placed.
375    pub instances: Vec<ThreeMfInstance>,
376    /// Every instance's triangles in world coordinates, millimetres — the soup
377    /// the mesh-to-solid chain reads.
378    pub positions: Vec<f64>,
379    /// Triangle corners into `positions`/3, winding preserved (reversed for a
380    /// mirrored instance so the result stays outward-facing).
381    pub indices: Vec<u32>,
382    /// Parallel to the flattened triangles (`indices.len() / 3` entries, each
383    /// following its triangle through the instance order and a mirrored
384    /// placement's winding reversal) when any placed triangle resolves to a
385    /// colour; EMPTY otherwise.
386    pub triangle_colors: Vec<Option<[u8; 3]>>,
387    /// Lossless appearance parallel to triangles; empty when absent.
388    pub triangle_appearance: Vec<Option<ThreeMfAppearance>>,
389}
390
391impl ThreeMfReadResult {
392    pub fn vertex_count(&self) -> usize {
393        self.positions.len() / 3
394    }
395    pub fn triangle_count(&self) -> usize {
396        self.indices.len() / 3
397    }
398
399    /// ONE instance's triangle soup: its world-space vertices and its triangles
400    /// rebased onto them. A multi-instance build is several bodies in one
401    /// buffer — this is how a consumer takes them apart by PLACEMENT without
402    /// knowing how `read_3mf` laid them out. The importer does not need it: the
403    /// mesh-to-solid chain splits the whole soup into its vertex-connected
404    /// components and reconstructs each as its own body. It is the answer when
405    /// the question is which instance a body came from, which the geometry
406    /// alone cannot say (two instances that touch are one component).
407    pub fn instance_mesh(&self, instance: usize) -> Option<(Vec<f64>, Vec<u32>)> {
408        let instance = self.instances.get(instance)?;
409        let positions = self
410            .positions
411            .get(instance.first_vertex * 3..(instance.first_vertex + instance.vertex_count) * 3)?
412            .to_vec();
413        let base = instance.first_vertex as u32;
414        let indices = self
415            .indices
416            .get(
417                instance.first_triangle * 3
418                    ..(instance.first_triangle + instance.triangle_count) * 3,
419            )?
420            .iter()
421            .map(|index| index - base)
422            .collect();
423        Some((positions, indices))
424    }
425}
426
427/// The identity 3x4 transform, in 3MF attribute order.
428pub const IDENTITY: [f64; 12] = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0];
429
430/// Place a point with a 3MF row-vector transform.
431pub fn transform_point(transform: &[f64; 12], point: [f64; 3]) -> [f64; 3] {
432    let [x, y, z] = point;
433    [
434        x * transform[0] + y * transform[3] + z * transform[6] + transform[9],
435        x * transform[1] + y * transform[4] + z * transform[7] + transform[10],
436        x * transform[2] + y * transform[5] + z * transform[8] + transform[11],
437    ]
438}
439
440/// Compose `inner` then `outer` (row vectors: `p · inner · outer`) — a
441/// component's transform inside the item that placed it.
442pub fn compose(inner: &[f64; 12], outer: &[f64; 12]) -> [f64; 12] {
443    let mut out = [0.0; 12];
444    for row in 0..4 {
445        for column in 0..3 {
446            let mut sum = if row == 3 { outer[9 + column] } else { 0.0 };
447            for k in 0..3 {
448                sum += inner[row * 3 + k] * outer[k * 3 + column];
449            }
450            out[row * 3 + column] = sum;
451        }
452    }
453    out
454}
455
456/// The determinant of the transform's linear part; negative means the instance
457/// is mirrored and its triangle winding has to be reversed.
458fn determinant(transform: &[f64; 12]) -> f64 {
459    let m = transform;
460    m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6])
461        + m[2] * (m[3] * m[7] - m[4] * m[6])
462}
463
464/// Read a 3MF package: locate the model part through the OPC relationships,
465/// parse the core model, and flatten the build into a millimetre triangle soup.
466///
467/// See the module documentation for what is read, what is ignored, and the
468/// bounds every part is held to.
469pub fn read_3mf(bytes: &[u8]) -> Result<ThreeMfReadResult, ThreeMfError> {
470    let archive = zip::ZipArchive::open(bytes).map_err(map_zip)?;
471    let relationships = archive.find(RELATIONSHIP_PART).ok_or_else(|| {
472        ThreeMfError::MissingPart {
473            part: RELATIONSHIP_PART.into(),
474            detail: "an OPC package must carry the package relationships part".into(),
475        }
476    })?;
477    let relationships_text = read_text(&archive, relationships, RELATIONSHIP_PART)?;
478    let model_part = start_part(&relationships_text)?;
479    let model_entry = archive.find(&model_part).ok_or_else(|| ThreeMfError::MissingPart {
480        part: model_part.clone(),
481        detail: format!("'{RELATIONSHIP_PART}' names it as the 3D model start part"),
482    })?;
483    let model_text = read_text(&archive, model_entry, &model_part)?;
484    let mut document = model::parse_model(&model_part, &model_text)?;
485    let mut texture_bytes = 0usize;
486    for texture in &mut document.textures {
487        let entry = archive.find(&texture.path).ok_or_else(|| ThreeMfError::MissingPart {
488            part: texture.path.clone(), detail: format!("texture2d {} references this PNG", texture.id),
489        })?;
490        texture.png = archive.read(entry, MAX_PART_BYTES.saturating_sub(texture_bytes)).map_err(map_zip)?;
491        texture_bytes += texture.png.len();
492        if !texture.png.starts_with(b"\x89PNG\r\n\x1a\n") {
493            return Err(ThreeMfError::Model { part: texture.path.clone(), detail: "texture2d is not a PNG".into() });
494        }
495    }
496    flatten(model_part, document)
497}
498
499/// Map a container fault onto the typed refusal, keeping the part name.
500fn map_zip(error: zip::ZipError) -> ThreeMfError {
501    let part = error.entry.clone().unwrap_or_else(|| "[package]".into());
502    match error.fault {
503        zip::ZipFault::Container => match &error.entry {
504            Some(entry) => ThreeMfError::Container(format!("{entry}: {}", error.message)),
505            None => ThreeMfError::Container(error.message),
506        },
507        zip::ZipFault::Damaged => ThreeMfError::Damaged { part, detail: error.message },
508        zip::ZipFault::Unsupported => ThreeMfError::Unsupported { part, detail: error.message },
509        zip::ZipFault::Bounds => ThreeMfError::Bounds { part, detail: error.message },
510    }
511}
512
513fn read_text(
514    archive: &zip::ZipArchive<'_>,
515    entry: &zip::ZipEntry,
516    part: &str,
517) -> Result<String, ThreeMfError> {
518    let bytes = archive.read(entry, MAX_PART_BYTES).map_err(map_zip)?;
519    String::from_utf8(bytes).map_err(|_| ThreeMfError::Xml {
520        part: part.to_owned(),
521        detail: "the part is not UTF-8 text".into(),
522    })
523}
524
525/// The `Target` of the package's 3D-model start-part relationship.
526fn start_part(text: &str) -> Result<String, ThreeMfError> {
527    let mut reader = xml::XmlReader::new(text);
528    loop {
529        let event = reader.next().map_err(|error| ThreeMfError::Xml {
530            part: RELATIONSHIP_PART.into(),
531            detail: error.to_string(),
532        })?;
533        match event {
534            xml::Event::Start(tag) => {
535                if tag.namespace != RELATIONSHIP_NAMESPACE {
536                    reader.skip_subtree(&tag).map_err(|error| ThreeMfError::Xml {
537                        part: RELATIONSHIP_PART.into(),
538                        detail: error.to_string(),
539                    })?;
540                    continue;
541                }
542                if tag.name != "Relationship" {
543                    continue;
544                }
545                if tag.attribute("Type") != Some(MODEL_RELATIONSHIP) {
546                    continue;
547                }
548                let target = tag.attribute("Target").ok_or_else(|| ThreeMfError::Model {
549                    part: RELATIONSHIP_PART.into(),
550                    detail: "the 3D model relationship has no Target".into(),
551                })?;
552                let target = target.trim_start_matches('/');
553                if target.is_empty() {
554                    return Err(ThreeMfError::Model {
555                        part: RELATIONSHIP_PART.into(),
556                        detail: "the 3D model relationship has an empty Target".into(),
557                    });
558                }
559                return Ok(target.to_owned());
560            }
561            xml::Event::End { .. } => {}
562            xml::Event::Eof => break,
563        }
564    }
565    Err(ThreeMfError::MissingPart {
566        part: RELATIONSHIP_PART.into(),
567        detail: format!("no relationship of type '{MODEL_RELATIONSHIP}' names a 3D model part"),
568    })
569}
570
571/// Walk the build, composing transforms, into instances and one triangle soup.
572fn flatten(
573    model_part: String,
574    document: model::ModelDocument,
575) -> Result<ThreeMfReadResult, ThreeMfError> {
576    let scale = document.unit.millimetres();
577    let meshes = document
578        .meshes
579        .iter()
580        .map(|mesh| {
581            let mut triangle_appearance = mesh.properties.iter()
582                .map(|p| document.appearance(p.or(mesh.object_property), &model_part))
583                .collect::<Result<Vec<_>, _>>()?;
584            let mut triangle_colors: Vec<_> = triangle_appearance.iter()
585                .map(|a| a.as_ref().and_then(ThreeMfAppearance::preview_rgb)).collect();
586            if triangle_appearance.iter().all(Option::is_none) { triangle_appearance.clear(); }
587            if triangle_colors.iter().all(Option::is_none) {
588                triangle_colors.clear();
589            }
590            Ok(ThreeMfMesh {
591                object_id: mesh.object_id,
592                beam_lattice: mesh.beam_lattice.clone().map(|mut lattice| {
593                    lattice.min_length *= scale;
594                    for beam in &mut lattice.beams { for r in &mut beam.radii { *r *= scale; } }
595                    lattice
596                }),
597                positions: mesh.positions.iter().map(|value| value * scale).collect(),
598                indices: mesh.indices.clone(),
599                triangle_colors,
600                triangle_appearance,
601            })
602        })
603        .collect::<Result<Vec<_>, ThreeMfError>>()?;
604    let mut instances = Vec::new();
605    for item in &document.items {
606        let mut transform = item.transform;
607        for value in &mut transform[9..12] {
608            *value *= scale;
609        }
610        place(&document, &model_part, item.object_id, transform, 0, None, &mut instances)?;
611    }
612    let mut positions = Vec::new();
613    let mut indices = Vec::new();
614    let mut triangle_colors: Vec<Option<[u8; 3]>> = Vec::new();
615    let colored = instances.iter().any(|instance| !meshes[instance.mesh].triangle_colors.is_empty());
616    let mut triangle_appearance = Vec::new();
617    let has_appearance = instances.iter().any(|i| !meshes[i.mesh].triangle_appearance.is_empty());
618    let mut triangles = 0usize;
619    for instance in &mut instances {
620        let mesh = &meshes[instance.mesh];
621        triangles += mesh.triangle_count();
622        if triangles > MAX_TOTAL_TRIANGLES {
623            return Err(ThreeMfError::Bounds {
624                part: model_part,
625                detail: format!(
626                    "the build places more than {MAX_TOTAL_TRIANGLES} triangles in total"
627                ),
628            });
629        }
630        instance.first_vertex = positions.len() / 3;
631        instance.vertex_count = mesh.vertex_count();
632        instance.first_triangle = indices.len() / 3;
633        instance.triangle_count = mesh.triangle_count();
634        let base = instance.first_vertex as u32;
635        for point in mesh.positions.chunks_exact(3) {
636            let placed = instance.transform_point([point[0], point[1], point[2]]);
637            positions.extend(placed);
638        }
639        // A mirrored placement turns the mesh inside out; reversing the winding
640        // keeps every triangle facing out of the body, which is what the
641        // mesh-to-solid chain reads.
642        let mirrored = determinant(&instance.transform) < 0.0;
643        for triangle in mesh.indices.chunks_exact(3) {
644            if mirrored {
645                indices.extend([base + triangle[0], base + triangle[2], base + triangle[1]]);
646            } else {
647                indices.extend([base + triangle[0], base + triangle[1], base + triangle[2]]);
648            }
649        }
650        if has_appearance {
651            for i in 0..mesh.triangle_count() {
652                let mut appearance = mesh.triangle_appearance.get(i).cloned().flatten();
653                if mirrored { if let Some(a) = &mut appearance { a.reverse(); } }
654                triangle_appearance.push(appearance);
655            }
656        }
657        // A colour rides with its triangle whichever way it is wound.
658        if colored {
659            if mesh.triangle_colors.is_empty() {
660                triangle_colors.extend(std::iter::repeat(None).take(mesh.triangle_count()));
661            } else {
662                triangle_colors.extend_from_slice(&mesh.triangle_colors);
663            }
664        }
665    }
666    Ok(ThreeMfReadResult {
667        model_part,
668        unit: document.unit,
669        textures: document.textures,
670        meshes,
671        instances,
672        positions,
673        indices,
674        triangle_colors,
675        triangle_appearance,
676    })
677}
678
679/// Place `object_id` under `transform`, recursing through `<components>`.
680fn place(
681    document: &model::ModelDocument,
682    model_part: &str,
683    object_id: u32,
684    transform: [f64; 12],
685    depth: usize,
686    inherited_name: Option<&str>,
687    instances: &mut Vec<ThreeMfInstance>,
688) -> Result<(), ThreeMfError> {
689    if depth > MAX_COMPONENT_DEPTH {
690        return Err(ThreeMfError::Bounds {
691            part: model_part.to_owned(),
692            detail: format!("components nest deeper than {MAX_COMPONENT_DEPTH} levels"),
693        });
694    }
695    let object = document.object(object_id).ok_or_else(|| ThreeMfError::Model {
696        part: model_part.to_owned(),
697        detail: format!("object {object_id} is placed but never defined"),
698    })?;
699    let name = object.name.as_deref().or(inherited_name);
700    match &object.content {
701        model::ObjectContent::Mesh(mesh) => {
702            // Only PRINTABLE geometry reaches the soup: support, surface and
703            // "other" objects describe the print job, not the part.
704            if object.model_type {
705                if instances.len() + 1 > MAX_INSTANCES {
706                    return Err(ThreeMfError::Bounds {
707                        part: model_part.to_owned(),
708                        detail: format!("the build places more than {MAX_INSTANCES} instances"),
709                    });
710                }
711                instances.push(ThreeMfInstance {
712                    object_id: object.id,
713                    mesh: *mesh,
714                    transform,
715                    // Filled by `flatten` when the soup is laid out.
716                    first_vertex: 0,
717                    vertex_count: 0,
718                    first_triangle: 0,
719                    triangle_count: 0,
720                    name: name.map(str::to_owned),
721                });
722            }
723            Ok(())
724        }
725        model::ObjectContent::Components(components) => {
726            for component in components {
727                let mut inner = component.transform;
728                // The component's translation is in the file's unit; the
729                // enclosing transform is already in millimetres, so scaling
730                // here (not in `flatten`) keeps one conversion per level.
731                let scale = document.unit.millimetres();
732                for value in &mut inner[9..12] {
733                    *value *= scale;
734                }
735                let composed = compose(&inner, &transform);
736                place(
737                    document,
738                    model_part,
739                    component.object_id,
740                    composed,
741                    depth + 1,
742                    name,
743                    instances,
744                )?;
745            }
746            Ok(())
747        }
748    }
749}