diff --git a/crates/io/src/mutate.rs b/crates/io/src/mutate.rs index 9eb106170..6d2a6e66a 100644 --- a/crates/io/src/mutate.rs +++ b/crates/io/src/mutate.rs @@ -467,6 +467,21 @@ outer survives("3MF (production extension)", &mutations(&production, false, 0x2089), usize::MAX, |b| { crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) }); + // Its model parts' XML mutated and zipped again: mutations of the zip mostly stop at its + // checksums, these reach the `p:path` and `objectid` handling. + let parts = crate::threemf::tests::production_parts(); + for (k, (name, xml)) in parts.iter().enumerate() { + let rezipped: Vec> = mutations(xml.as_bytes(), true, 0x2089 + k as u64) + .iter() + .map(|m| { + let entries: Vec<(&str, &[u8])> = parts.iter().map(|(n, x)| (*n, if n == name { m.as_slice() } else { x.as_bytes() })).collect(); + crate::threemf::tests::package_bytes(&entries) + }) + .collect(); + survives(&format!("3MF (production extension, {name} mutated)"), &rezipped, usize::MAX, |b| { + crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) + }); + } } #[test] diff --git a/crates/io/src/threemf.rs b/crates/io/src/threemf.rs index 534827def..736a4b257 100644 --- a/crates/io/src/threemf.rs +++ b/crates/io/src/threemf.rs @@ -8,10 +8,12 @@ //! precision so the receiver gets the tessellation exactly. Reading: every build item becomes one mesh //! (components flattened with their transforms), converted to millimetres. Components and build //! items may name an object in another model part of the package (`p:path`, the 3MF Production -//! extension, which slicers use for multi-part projects); those parts are read too. Packages are -//! untrusted: sizes, entry counts, model parts, mesh sizes and component nesting are capped. +//! extension, which slicers use for multi-part projects); those parts are read too. Only the root +//! model's build counts (readers must ignore the others), and a part that can't be read fails +//! only the placements that need it. Packages are untrusted: sizes, entry counts, model parts, +//! mesh sizes and component nesting are capped. -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap}; use std::fmt::Write as _; use std::io::{Cursor, Read, Write}; @@ -352,10 +354,30 @@ fn bad(msg: impl Into) -> Result { Err(IoError::Invalid(format!("3MF: {}", msg.into()))) } -/// The name a part is looked up by: no leading `/`, in lower case (part names compare -/// case-insensitively). +/// The name a part is looked up by: `%XX` escapes decoded, no leading `/`, in lower case (part +/// names are URIs and compare case-insensitively). fn part_key(name: &str) -> String { - name.replace('\\', "/").trim_start_matches('/').to_ascii_lowercase() + let b = name.as_bytes(); + let hex = |k: usize| b.get(k).and_then(|h| char::from(*h).to_digit(16)); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while let Some(&c) = b.get(i) { + match (c, hex(i + 1), hex(i + 2)) { + (b'%', Some(hi), Some(lo)) => { + out.push((hi * 16 + lo) as u8); + i += 3; + } + (b'\\', ..) => { + out.push(b'/'); + i += 1; + } + _ => { + out.push(c); + i += 1; + } + } + } + String::from_utf8_lossy(&out).trim_start_matches('/').to_ascii_lowercase() } fn read_part(zip: &mut zip::ZipArchive>, name: &str) -> Result>> { @@ -363,20 +385,22 @@ fn read_part(zip: &mut zip::ZipArchive>, name: &str) -> Result Ok(Some(data)), + None => bad(format!("{name} expands to more than 1 GB")), + } } -fn read_entry(zip: &mut zip::ZipArchive>, idx: usize, name: &str) -> Result> { +/// Entry `idx` uncompressed, or `None` when it expands to more than `limit` bytes (zip bombs stop +/// there). +fn read_entry(zip: &mut zip::ZipArchive>, idx: usize, name: &str, limit: u64) -> Result>> { let mut f = zip.by_index(idx).map_err(|e| IoError::Invalid(format!("3MF {name}: {e}")))?; - if f.size() > MAX_PART { - return bad(format!("{name} expands to {} bytes", f.size())); + if f.size() > limit { + return Ok(None); } let mut out = Vec::with_capacity(f.size().min(16 << 20) as usize); - (&mut f).take(MAX_PART + 1).read_to_end(&mut out).map_err(|e| IoError::Invalid(format!("3MF {name}: {e}")))?; - if out.len() as u64 > MAX_PART { - return bad(format!("{name} expands to more than 1 GB")); - } - Ok(out) + (&mut f).take(limit.saturating_add(1)).read_to_end(&mut out).map_err(|e| IoError::Invalid(format!("3MF {name}: {e}")))?; + Ok((out.len() as u64 <= limit).then_some(out)) } fn attrs(e: &BytesStart) -> HashMap { @@ -435,10 +459,16 @@ fn det(m: &Xf) -> f64 { m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + m[2] * (m[3] * m[7] - m[4] * m[6]) } -/// A component or build item: object `id` placed by `xf`, in model part `part` (its key, from -/// `p:path`) or, without one, in the part that names it. +/// A model part named by `p:path`: its key ([`part_key`]) and the name as written, for messages. +struct PartName { + key: String, + path: String, +} + +/// A component or build item: object `id` placed by `xf`, in model part `part` or, without one, +/// in the part that names it. struct Ref { - part: Option, + part: Option, id: u32, xf: Xf, } @@ -453,19 +483,29 @@ struct Object { } /// One model part. Positions and translations are in millimetres (converted with the part's -/// unit as it is read), so objects of parts in different units fit together. +/// unit as it is read), so objects of parts in different units fit together. Objects are kept in +/// id order, so the parts they name are read, and reported, in the same order every run. #[derive(Default)] struct Model { - unit: f64, - objects: HashMap, + objects: BTreeMap, materials: HashMap>>, build: Vec, } -/// The model parts read from a package, by key, and the key of the root model. +/// The model parts of a package by key: the root model's key, the parts read, the parts that are +/// in the package but could not be read (with the error), and each part's name as first written. struct Package { root: String, parts: HashMap, + failed: HashMap, + names: HashMap, +} + +impl Package { + /// Part `key` as the package names it. + fn shown<'a>(&'a self, key: &'a str) -> &'a str { + self.names.get(key).map_or(key, String::as_str) + } } fn color(s: &str) -> Option<[f32; 3]> { @@ -489,11 +529,19 @@ fn unit_mm(u: &str) -> Option { }) } -fn parse_model(xml: &[u8]) -> Result { +/// The model part's name in `p:path`, if any. +fn part_name(a: &HashMap) -> Option { + a.get("path").map(|p| PartName { key: part_key(p), path: p.clone() }) +} + +/// Model part `xml`. Only the `root` model's build items are read: the spec has readers ignore +/// the build sections of the other parts (slicers leave them empty or point them anywhere). +fn parse_model(xml: &[u8], root: bool) -> Result { let mut rd = Reader::from_reader(xml); rd.config_mut().trim_text(true); let mut buf = Vec::new(); - let mut m = Model { unit: 1.0, ..Default::default() }; + let mut m = Model::default(); + let mut unit = 1.0; let mut depth = 0usize; let mut cur: Option<(u32, Object)> = None; let mut cur_mat: Option = None; @@ -541,7 +589,7 @@ fn parse_model(xml: &[u8]) -> Result { b"model" => { seen_model = true; if let Some(u) = a.get("unit") { - m.unit = unit_mm(u).ok_or_else(|| IoError::Invalid(format!("3MF: unknown unit `{u}`")))?; + unit = unit_mm(u).ok_or_else(|| IoError::Invalid(format!("3MF: unknown unit `{u}`")))?; } } b"basematerials" => { @@ -573,7 +621,7 @@ fn parse_model(xml: &[u8]) -> Result { return bad("too many vertices"); } let (Some(x), Some(y), Some(z)) = (num("x"), num("y"), num("z")) else { return bad("vertex without x, y, z") }; - o.positions.push(Vec3::new(x, y, z) * m.unit); + o.positions.push(Vec3::new(x, y, z) * unit); } b"triangle" => { let Some((_, o)) = cur.as_mut() else { return bad("triangle outside an object") }; @@ -586,11 +634,13 @@ fn parse_model(xml: &[u8]) -> Result { b"component" => { let Some((_, o)) = cur.as_mut() else { return bad("component outside an object") }; let target = id("objectid").ok_or_else(|| IoError::Invalid("3MF: component without objectid".into()))?; - o.components.push(Ref { part: a.get("path").map(|p| part_key(p)), id: target, xf: in_mm(parse_xf(a.get("transform"))?, m.unit) }); + // The spec allows `p:path` only in the root model's components; a reader can still + // follow it from any part (loops and depth are checked when placing). + o.components.push(Ref { part: part_name(&a), id: target, xf: in_mm(parse_xf(a.get("transform"))?, unit) }); } - b"item" => { + b"item" if root => { let target = id("objectid").ok_or_else(|| IoError::Invalid("3MF: build item without objectid".into()))?; - m.build.push(Ref { part: a.get("path").map(|p| part_key(p)), id: target, xf: in_mm(parse_xf(a.get("transform"))?, m.unit) }); + m.build.push(Ref { part: part_name(&a), id: target, xf: in_mm(parse_xf(a.get("transform"))?, unit) }); } _ => {} } @@ -602,29 +652,30 @@ fn parse_model(xml: &[u8]) -> Result { Ok(m) } -/// Queue the model parts `m` names that were not seen yet. -fn queue_parts(m: &Model, seen: &mut HashSet, pending: &mut Vec) -> Result<()> { - for key in m.objects.values().flat_map(|o| &o.components).chain(&m.build).filter_map(|r| r.part.as_ref()) { - if !seen.contains(key) { +/// Queue the model parts `m` names that were not seen yet, noting how each is spelled (`m.build` +/// is empty but for the root). +fn queue_parts(m: &Model, names: &mut HashMap, pending: &mut Vec) -> Result<()> { + for p in m.objects.values().flat_map(|o| &o.components).chain(&m.build).filter_map(|r| r.part.as_ref()) { + if !names.contains_key(&p.key) { // A package holds no more parts than it has entries. - if seen.len() >= MAX_ENTRIES { + if names.len() >= MAX_ENTRIES { return bad(format!("objects name more than {MAX_ENTRIES} model parts")); } - seen.insert(key.clone()); - pending.push(key.clone()); + names.insert(p.key.clone(), p.path.clone()); + pending.push(p.key.clone()); } } Ok(()) } -/// An error reading model part `key`, saying which part it was. -fn in_part(key: &str, e: IoError) -> IoError { +/// An error reading model part `name`, saying which part it was. +fn in_part(name: &str, e: IoError) -> String { match e { IoError::Invalid(msg) => { let msg = msg.strip_prefix("3MF: ").or_else(|| msg.strip_prefix("3MF ")).unwrap_or(&msg); - IoError::Invalid(format!("3MF model part `{key}`: {msg}")) + format!("3MF model part `{name}`: {msg}") } - e => e, + e => e.to_string(), } } @@ -638,15 +689,22 @@ fn flatten<'a>( stack: &mut Vec<(&'a str, u32)>, total: &mut usize, ) -> Result<()> { - if stack.len() > MAX_COMPONENT_DEPTH || stack.contains(&(part, id)) { - return bad("components nested too deeply or recursive"); + // Loops are keyed by (part, object): parts number their objects on their own, so object 1 of + // the root placing object 1 of another part is no loop. + if stack.contains(&(part, id)) { + return bad("components place each other in a loop"); } - let m = pkg.parts.get(part).ok_or_else(|| IoError::Invalid(format!("3MF: no model part `{part}`")))?; + if stack.len() > MAX_COMPONENT_DEPTH { + return bad(format!("components nested more than {MAX_COMPONENT_DEPTH} deep")); + } + let Some(m) = pkg.parts.get(part) else { + return Err(IoError::Invalid(pkg.failed.get(part).cloned().unwrap_or_else(|| format!("3MF: no model part `{}`", pkg.shown(part))))); + }; let o = m.objects.get(&id).ok_or_else(|| { IoError::Invalid(if part == pkg.root { format!("3MF: missing object {id}") } else { - format!("3MF: missing object {id} in model part `{part}`") + format!("3MF: missing object {id} in model part `{}`", pkg.shown(part)) }) })?; // Every placement costs at least one unit of the budget, so objects that only place other @@ -695,7 +753,8 @@ fn flatten<'a>( } stack.push((part, id)); for c in &o.components { - flatten(pkg, c.part.as_deref().unwrap_or(part), c.id, &compose(&c.xf, xf), out, stack, total)?; + // Without `p:path` a component is in the part that names it, not in the root. + flatten(pkg, c.part.as_ref().map_or(part, |p| p.key.as_str()), c.id, &compose(&c.xf, xf), out, stack, total)?; } stack.pop(); Ok(()) @@ -733,40 +792,56 @@ pub fn read_3mf(bytes: &[u8]) -> Result<(Vec, Vec)> { } } let xml = read_part(&mut zip, &root)?.ok_or_else(|| IoError::Invalid(format!("3MF: no model part `{root}`")))?; - let root = part_key(&root); - let model = parse_model(&xml)?; - let mut model_bytes = xml.len(); + let root_name = root; + let root = part_key(&root_name); + let model = parse_model(&xml, true)?; + // All model parts together may expand to 1 GB; only one is held as XML at a time. + let mut model_bytes = xml.len() as u64; + drop(xml); // The model parts objects name (production extension), each read once. The entries are - // indexed first, so a package naming thousands of parts costs no scan per name; a name - // with no entry is left out, and the placements that need it say so. + // indexed first, so a package naming thousands of parts costs no scan per name. A name with + // no entry is left out and a part that can't be read is noted: either way only the + // placements that need it fail, and say why. let mut entries = HashMap::new(); for i in 0..zip.len() { if let Some(Ok(n)) = zip.name_for_index(i) { entries.entry(part_key(&n)).or_insert(i); } } - let mut seen = HashSet::from([root.clone()]); + let mut names = HashMap::from([(root.clone(), root_name)]); let mut pending = Vec::new(); - queue_parts(&model, &mut seen, &mut pending)?; + queue_parts(&model, &mut names, &mut pending)?; let mut parts = HashMap::from([(root.clone(), model)]); + let mut failed = HashMap::new(); while let Some(key) = pending.pop() { let Some(&idx) = entries.get(&key) else { continue }; - let xml = read_entry(&mut zip, idx, &key)?; - model_bytes = model_bytes.saturating_add(xml.len()); - if model_bytes as u64 > MAX_PART { - return bad("model parts expand to more than 1 GB"); + let name = names.get(&key).cloned().unwrap_or_else(|| key.clone()); + let read = match read_entry(&mut zip, idx, &name, MAX_PART.saturating_sub(model_bytes)) { + Ok(Some(xml)) => { + model_bytes = model_bytes.saturating_add(xml.len() as u64); + parse_model(&xml, false) + } + // The package-wide caps refuse the whole package, not just this part. + Ok(None) => return bad("model parts expand to more than 1 GB"), + Err(e) => Err(e), + }; + match read { + Ok(m) => { + queue_parts(&m, &mut names, &mut pending)?; + parts.insert(key, m); + } + Err(e) => { + failed.insert(key, in_part(&name, e)); + } } - let m = parse_model(&xml).map_err(|e| in_part(&key, e))?; - queue_parts(&m, &mut seen, &mut pending)?; - parts.insert(key, m); } - let pkg = Package { root, parts }; + let pkg = Package { root, parts, failed, names }; let Some(model) = pkg.parts.get(&pkg.root) else { return bad("no root model") }; let mut out = Vec::new(); let mut warnings = Vec::new(); let mut total = 0usize; for (k, item) in model.build.iter().enumerate() { - let part = item.part.as_deref().unwrap_or(&pkg.root); + let part = item.part.as_ref().map_or(pkg.root.as_str(), |p| p.key.as_str()); let mut mo = MeshObject::default(); match flatten(&pkg, part, item.id, &item.xf, &mut mo, &mut Vec::new(), &mut total) { Ok(()) if !mo.triangles.is_empty() => { @@ -814,16 +889,21 @@ pub(crate) mod tests { } /// A package of these parts (name, contents). - fn package_parts(parts: &[(&str, &str)]) -> Vec { + pub(crate) fn package_bytes(parts: &[(&str, &[u8])]) -> Vec { let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); let o = zip::write::SimpleFileOptions::default(); for (name, data) in parts { zip.start_file(*name, o).unwrap(); - zip.write_all(data.as_bytes()).unwrap(); + zip.write_all(data).unwrap(); } zip.finish().unwrap().into_inner() } + /// A package of these text parts (name, contents). + fn package_parts(parts: &[(&str, &str)]) -> Vec { + package_bytes(&parts.iter().map(|(n, d)| (*n, d.as_bytes())).collect::>()) + } + fn package(model: &str, rels: Option<&str>) -> Vec { let mut parts: Vec<(&str, &str)> = rels.map(|r| ("_rels/.rels", r)).into_iter().collect(); parts.push(("3D/3dmodel.model", model)); @@ -850,9 +930,9 @@ pub(crate) mod tests { o.triangles.iter().map(|t| p(t[0]).dot(p(t[1]).cross(p(t[2])))).sum::() / 6.0 } - /// A multi-part project as slicers save it: the root model's object is two components in - /// another model part, which holds the meshes. - pub(crate) fn production_package() -> Vec { + /// The model parts (name, XML) of a multi-part project as slicers save it: the root model's + /// object is two components in another model part, which holds the meshes. + pub(crate) fn production_parts() -> [(&'static str, String); 2] { let root = format!( r#" @@ -860,7 +940,12 @@ pub(crate) mod tests { "# ); let objects = model_part("millimeter", &format!("{}{}", tet_object(1, "A", 1.0), tet_object(2, "B", 2.0))); - package_parts(&[("3D/3dmodel.model", &root), (OBJECTS_PART, &objects)]) + [("3D/3dmodel.model", root), (OBJECTS_PART, objects)] + } + + pub(crate) fn production_package() -> Vec { + let [(r, root), (o, objects)] = production_parts(); + package_parts(&[(r, &root), (o, &objects)]) } /// Objects kept in a model part of their own (3MF Production extension) come in with their @@ -916,22 +1001,40 @@ pub(crate) mod tests { r#""#, ); let many: String = (0..=MAX_ENTRIES).map(|i| format!(r#""#)).collect(); + // Each with the message it must give: before the production extension was read, every + // one of these failed alike, on the first `p:path`. let cases = [ - // A part that isn't in the package, one outside it and an empty name. - package_parts(&[("3D/3dmodel.model", &root(r#""#))]), - package_parts(&[("3D/3dmodel.model", &root(r#""#)), (OBJECTS_PART, &tet)]), - package_parts(&[("3D/3dmodel.model", &root(r#""#)), (OBJECTS_PART, &tet)]), + // A part that isn't in the package (named as written), one outside it and an empty name. + ( + package_parts(&[("3D/3dmodel.model", &root(r#""#))]), + "no model part `/3D/Objects/Missing.model`", + ), + ( + package_parts(&[("3D/3dmodel.model", &root(r#""#)), (OBJECTS_PART, &tet)]), + "no model part `/../../etc/passwd`", + ), + (package_parts(&[("3D/3dmodel.model", &root(r#""#)), (OBJECTS_PART, &tet)]), "no model part ``"), // An object the part doesn't have. - package_parts(&[("3D/3dmodel.model", &root(r#""#)), (OBJECTS_PART, &tet)]), + ( + package_parts(&[ + ("3D/3dmodel.model", &root(r#""#)), + (OBJECTS_PART, &tet), + ]), + "missing object 7 in model part `/3D/Objects/object_1.model`", + ), // A part that is no model. - package_parts(&[("3D/3dmodel.model", &root(to_objects)), (OBJECTS_PART, "not xml")]), + ( + package_parts(&[("3D/3dmodel.model", &root(to_objects)), (OBJECTS_PART, "not xml")]), + "model part `/3D/Objects/object_1.model`: no element", + ), // Parts that place each other in a loop. - package_parts(&[("3D/3dmodel.model", &root(to_objects)), (OBJECTS_PART, &looped)]), + (package_parts(&[("3D/3dmodel.model", &root(to_objects)), (OBJECTS_PART, &looped)]), "components place each other in a loop"), // More part names than a package can hold. - package_parts(&[("3D/3dmodel.model", &root(&many))]), + (package_parts(&[("3D/3dmodel.model", &root(&many))]), "objects name more than 10000 model parts"), ]; - for (i, c) in cases.iter().enumerate() { - assert!(read_3mf(c).is_err(), "case {i}"); + for (i, (c, msg)) in cases.iter().enumerate() { + let err = read_3mf(c).map(|_| ()).unwrap_err().to_string(); + assert!(err.contains(msg), "case {i}: {err}"); } // A placement whose part is missing is reported; the others still come in. let two = format!( @@ -942,6 +1045,221 @@ pub(crate) mod tests { assert!(warnings.iter().any(|w| w.contains("build item 2") && w.contains("gone.model")), "{warnings:?}"); } + /// The root model: `objects`, and a build of `items`. + fn root_model(objects: &str, items: &str) -> String { + format!(r#"{objects}{items}"#) + } + + /// Object `id` made of components: (`p:path`, or "" for none, and object id). + fn assembly(id: u32, components: &[(&str, u32)]) -> String { + let c: String = components + .iter() + .map(|(path, oid)| match *path { + "" => format!(r#""#), + path => format!(r#""#), + }) + .collect(); + format!(r#"{c}"#) + } + + /// A component without `p:path` in another part is in that part, not in the root, which has + /// an object of the same id too (T1 of the review of #2127). + #[test] + fn components_without_a_path_stay_in_their_part() { + let root = + root_model(&format!("{}{}", tet_object(2, "Root", 5.0), assembly(10, &[("/3D/Objects/object_1.model", 1)])), r#""#); + let objects = model_part("millimeter", &format!("{}{}", assembly(1, &[("", 2)]), tet_object(2, "Child", 2.0))); + let (objs, warnings) = read_3mf(&package_parts(&[("3D/3dmodel.model", &root), (OBJECTS_PART, &objects)])).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(objs.len(), 1); + assert!((volume(&objs[0]) - 8.0 / 6.0).abs() < 1e-9, "the child's object 2, not the root's: {}", volume(&objs[0])); + } + + /// Parts number their objects on their own, so root object 1 placing object 1 of another part + /// is no loop (T2). + #[test] + fn the_same_id_in_two_parts_is_no_loop() { + let root = root_model(&assembly(1, &[("/3D/Objects/object_1.model", 1)]), r#""#); + let objects = model_part("millimeter", &tet_object(1, "A", 1.0)); + let (objs, warnings) = read_3mf(&package_parts(&[("3D/3dmodel.model", &root), (OBJECTS_PART, &objects)])).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(objs.len() == 1 && (volume(&objs[0]) - 1.0 / 6.0).abs() < 1e-9); + } + + /// A package shaped like a slicer project (Bambu Studio, OrcaSlicer): object UUIDs, printable + /// build items, thumbnails, slicer configs, and the meshes in a part of their own with an empty + /// build (T3). Each object on the plate is one body with all its volumes. The slicer's config + /// (names, which volumes are modifiers) isn't read, so the bodies are named `MeshN` and the + /// modifier comes in as solid. + #[test] + fn slicer_project_package() { + let ns = r#"xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" xmlns:BambuStudio="http://schemas.bambulab.com/package/2021" xmlns:p="http://schemas.microsoft.com/3dmanufacturing/production/2015/06" requiredextensions="p""#; + let uuid = |n: u32| format!("{n:08x}-61cb-4c03-9d28-80fed5dfa1dc"); + let component = |oid: u32| { + format!( + r#""#, + uuid(100 + oid) + ) + }; + let root = format!( + r#" + + BambuStudio-02.03.00.70 + 1 + + {} + {}{} + + + + + +"#, + uuid(2), + component(1), + uuid(4), + component(3), + component(5), + uuid(200), + uuid(201), + uuid(202) + ); + let mesh = |id: u32, s: f64| tet_object(id, "", s).replace(r#" name="""#, &format!(r#" p:UUID="{}""#, uuid(300 + id))); + let objects = format!( + r#" + + 1 + {}{}{} + +"#, + mesh(1, 10.0), + mesh(3, 20.0), + mesh(5, 4.0) + ); + let settings = r#" + + + + +"#; + let content_types = r#""#; + let rels = format!( + r#""# + ); + let model_rels = format!( + r#""# + ); + let png: &[u8] = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR"; + let package = package_bytes(&[ + ("[Content_Types].xml", content_types.as_bytes()), + ("_rels/.rels", rels.as_bytes()), + ("3D/3dmodel.model", root.as_bytes()), + ("3D/_rels/3dmodel.model.rels", model_rels.as_bytes()), + (OBJECTS_PART, objects.as_bytes()), + ("Metadata/model_settings.config", settings.as_bytes()), + ("Metadata/project_settings.config", br#"{"layer_height": "0.2"}"#), + ("Metadata/plate_1.png", png), + ("Metadata/plate_1_small.png", png), + ]); + let (objs, warnings) = read_3mf(&package).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let names: Vec<&str> = objs.iter().map(|o| o.name.as_str()).collect(); + assert_eq!(names, ["Mesh1", "Mesh2"]); + assert_eq!((objs[0].triangles.len(), objs[1].triangles.len()), (4, 8)); + assert!((volume(&objs[0]) - 1000.0 / 6.0).abs() < 1e-6, "{}", volume(&objs[0])); + assert!((volume(&objs[1]) - (8000.0 + 64.0) / 6.0).abs() < 1e-6, "{}", volume(&objs[1])); + assert!(objs[0].positions.iter().all(|p| p.x >= 128.0 - 1e-9 && p.y >= 128.0 - 1e-9)); + } + + /// Placements in every part draw on one budget (T4): three parts fanning out 300 ways each + /// (27 million placements of an empty object) stop at it, and only the build item that went + /// over fails. + #[test] + fn parts_share_the_placement_budget() { + let t = std::time::Instant::now(); + let fan = |id: u32, path: &str| assembly(id, &vec![(path, 1); 300]); + let root = root_model(&fan(10, "/3D/Objects/a.model"), r#""#); + let a = model_part("millimeter", &format!("{}{}", fan(1, "/3D/Objects/b.model"), tet_object(9, "Tet", 1.0))); + let b = model_part("millimeter", &fan(1, "/3D/Objects/c.model")); + let c = model_part("millimeter", r#""#); + let package = + package_parts(&[("3D/3dmodel.model", &root), ("3D/Objects/a.model", &a), ("3D/Objects/b.model", &b), ("3D/Objects/c.model", &c)]); + let (objs, warnings) = read_3mf(&package).unwrap(); + assert_eq!(objs.len(), 1); + assert!(warnings.len() == 1 && warnings[0].starts_with("build item 2") && warnings[0].contains("placements"), "{warnings:?}"); + assert!(t.elapsed() < std::time::Duration::from_secs(30), "took {:?}", t.elapsed()); + } + + /// A loop through three parts with different object ids is found, and a chain of parts deeper + /// than the cap stops there while one level less still comes in (T5). + #[test] + fn loops_and_deep_chains_across_parts() { + let read = |parts: &[(String, String)]| read_3mf(&package_parts(&parts.iter().map(|(n, x)| (n.as_str(), x.as_str())).collect::>())); + let part = |name: &str, objects: String| (name.to_string(), model_part("millimeter", &objects)); + let looped = [ + ("3D/3dmodel.model".to_string(), root_model("", r#""#)), + part("3D/Objects/a.model", assembly(1, &[("/3D/Objects/b.model", 2)])), + part("3D/Objects/b.model", assembly(2, &[("/3D/Objects/c.model", 3)])), + part("3D/Objects/c.model", assembly(3, &[("/3D/Objects/a.model", 1)])), + ]; + let err = read(&looped).map(|_| ()).unwrap_err().to_string(); + assert!(err.contains("components place each other in a loop"), "{err}"); + // Object k of part k places object k + 1 of part k + 1; the last one is a mesh. + let chain = |n: u32| { + let name = |k: u32| format!("3D/Objects/c{k}.model"); + let mut parts = vec![("3D/3dmodel.model".to_string(), root_model("", &format!(r#""#, name(1))))]; + for k in 1..=n { + let object = if k == n { tet_object(k, "End", 1.0) } else { assembly(k, &[(format!("/{}", name(k + 1)).as_str(), k + 1)]) }; + parts.push(part(&name(k), object)); + } + read(&parts) + }; + let deepest = MAX_COMPONENT_DEPTH as u32 + 1; + let (objs, warnings) = chain(deepest).unwrap(); + assert!(objs.len() == 1 && warnings.is_empty(), "{warnings:?}"); + let err = chain(deepest + 1).map(|_| ()).unwrap_err().to_string(); + assert!(err.contains(&format!("components nested more than {MAX_COMPONENT_DEPTH} deep")), "{err}"); + } + + /// A part that can't be read fails only the placements that need it, and none when only + /// objects nobody places name it. The build sections of other parts are ignored, even ones + /// pointing at a thumbnail or missing their object id (T6). + #[test] + fn broken_parts_and_the_builds_of_other_parts() { + let root = root_model( + &assembly(20, &[("/3D/Objects/unused.model", 1)]), + r#""#, + ); + let objects = format!( + r#"{}"#, + tet_object(1, "A", 1.0) + ); + let package = package_parts(&[ + ("3D/3dmodel.model", &root), + (OBJECTS_PART, &objects), + ("3D/Objects/broken.model", "not xml"), + ("3D/Objects/unused.model", " element"), + "{warnings:?}" + ); + } + + /// Part names are URIs: a `%XX` escape matches the character it stands for, either way round. + #[test] + fn escaped_part_names() { + let root = root_model("", r#""#); + let tet = model_part("millimeter", &tet_object(1, "A", 1.0)); + let package = package_parts(&[("3D/3dmodel.model", &root), ("3D/Objects/my part.model", &tet), ("3D/Objects/caf%C3%A9.model", &tet)]); + let (objs, warnings) = read_3mf(&package).unwrap(); + assert!(warnings.is_empty() && objs.len() == 2, "{warnings:?}"); + } + #[test] fn package_is_well_formed() { let mut t = tetra("A <&> \"b\""); diff --git a/docs/book/src/guide/files.md b/docs/book/src/guide/files.md index 63b9eb104..87b25f4df 100644 --- a/docs/book/src/guide/files.md +++ b/docs/book/src/guide/files.md @@ -35,8 +35,11 @@ mirrored nodes are baked into their meshes. Compressed meshes (Draco, meshopt) a message: save the file uncompressed first. A 3MF project saved by a slicer comes in too, also when it keeps its objects in model parts of -their own inside the file (the 3MF Production extension): each object on the build plate becomes -a mesh body, with its parts where the slicer placed them. +their own inside the file (the 3MF Production extension): each object on the build plates becomes +one mesh body, with all its volumes merged where the slicer placed them. Slicer-only data +(modifier, negative and support volumes, painting, per-object settings, and names kept in the +slicer's metadata) is not read: modifier and negative volumes come in as ordinary solid geometry, +and objects without a name in the model itself are called Mesh1, Mesh2, … **File → Export STL…** and **File → Export 3MF…** (also on the Mesh tab under Modify as Save as mesh, and in the right-click menu of a body) open the same dialog with that format chosen; it saves