From d8d22cd52afb66a130692f077191a5bbc3d22603 Mon Sep 17 00:00:00 2001 From: austin62jake Date: Thu, 29 Oct 2026 03:35:38 +0000 Subject: [PATCH] 3MF export: a component's bodies as one object with parts (#8139) (#8187) * claim: #8139 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FAWPuFoh9qxn2uS2j53QZ * 3MF export: a component's bodies as one object with parts (#8139) file.export and file.save_mesh wrote every body as its own 3MF object and build item, so a slicer loaded a multi-body part as separate objects and could arrange them apart on the bed. With objects: "component", each placed component that holds two or more bodies is written as one object whose are its bodies' meshes, built once, so PrusaSlicer, OrcaSlicer, Bambu Studio and Cura load it as one object with a part per body, each of which can take its own filament. The design's own bodies, and a component with a single body, stay objects of their own. The default (objects: "body") writes the same file as before. - io: model_xml_parts and write_3mf_parts write the parts; export_with_parts maps body names to them. model_xml_with and export_with_quality give the same output as before. - engine: mesh_parts reads `objects` (component is refused for formats other than 3MF); component_parts groups the placed bodies by placement, each part named after its occurrence (Bracket:1, Bracket:2). - file.save_mesh passes the parts on when it also sends the file to a slicer; file.send_to_slicer's own folder export is unchanged. Fixes #8139. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FAWPuFoh9qxn2uS2j53QZ --------- Co-authored-by: Claude --- crates/engine/src/cmd/file.rs | 119 +++++++++++++++++++++++++++-- crates/engine/src/cmd/file_send.rs | 4 +- crates/io/src/lib.rs | 23 +++++- crates/io/src/threemf.rs | 74 +++++++++++++++++- docs/book/src/guide/files.md | 7 ++ 5 files changed, 215 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 9440a3998..211f70e94 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -56,12 +56,12 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("file.export", "Export", export) .icon("export") .noundo() - .params("path; format?: stl|stla|obj|step|3mf|3mf-tagged|urdf|json (default from extension; 3mf-tagged: 3MF whose triangles carry their B-rep face, at full precision, for meshing and analysis tools; docs/formats/3mf-face-tags.md; obj: the colours of the bodies go in a material library (`.mtl`) written next to the mesh file; urdf: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md); bodies?: [names] (JSON and URDF export the complete design); urdf only: mesh_prefix? (before each mesh file name, e.g. package://robot/meshes/), effort? (default 1000), velocity? (default 10); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard)"), + .params("path; format?: stl|stla|obj|step|3mf|3mf-tagged|urdf|json (default from extension; 3mf-tagged: 3MF whose triangles carry their B-rep face, at full precision, for meshing and analysis tools; docs/formats/3mf-face-tags.md; obj: the colours of the bodies go in a material library (`.mtl`) written next to the mesh file; urdf: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md); bodies?: [names] (JSON and URDF export the complete design); urdf only: mesh_prefix? (before each mesh file name, e.g. package://robot/meshes/), effort? (default 1000), velocity? (default 10); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard); objects?: body|component (3MF only: one object per body, the default, or one object for each placed component with two or more bodies, with those bodies as its parts, so a slicer loads them as one object with parts)"), CommandSpec::new("file.save_mesh", "Save As Mesh", save_mesh) .at("INSERT", "FILES") .icon("mesh_export") .noundo() - .params("path; format?: stl|3mf|3mf-tagged (default from the extension, else stl; 3mf-tagged: docs/formats/3mf-face-tags.md); bodies?: [names] (default: all); ascii?: bool (STL); slicer?: id or name from file.slicers, the program path it lists, or a program the user added under Custom… (send the saved file there, through the same steps as file.send_to_slicer: a slicer that has to be started first is waited for; may be deprecated later in favour of file.send_to_slicer or a Send to App workflow, kept for scripts); single_instance?: bool (default true; see file.send_to_slicer); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard)"), + .params("path; format?: stl|3mf|3mf-tagged (default from the extension, else stl; 3mf-tagged: docs/formats/3mf-face-tags.md); bodies?: [names] (default: all); ascii?: bool (STL); slicer?: id or name from file.slicers, the program path it lists, or a program the user added under Custom… (send the saved file there, through the same steps as file.send_to_slicer: a slicer that has to be started first is waited for; may be deprecated later in favour of file.send_to_slicer or a Send to App workflow, kept for scripts); single_instance?: bool (default true; see file.send_to_slicer); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard); objects?: body|component (3MF only: one object per body, the default, or one object for each placed component with two or more bodies, with those bodies as its parts, so a slicer loads them as one object with parts)"), CommandSpec::new("file.send_to_slicer", "Send to Slicer", send_to_slicer) .enabled(starts_programs) .at("INSERT", "FILES") @@ -618,7 +618,52 @@ fn mesh_quality(p: &Value, cmd: &str) -> Result { } } -fn export_to(s: &Session, path: &str, format: Format, bodies: &[String], quality: solidcraft_io::MeshQuality) -> Result { +/// The 3MF parts a mesh export's `objects` asks for (#8139): none for `body` (the default, one +/// object per body), or for `component` one part per placement of a component with two or more +/// bodies ([`component_parts`]). Other formats have no parts, so `component` is refused there. +pub(super) fn mesh_parts(s: &Session, p: &Value, cmd: &str, format: Format) -> Result)>> { + match p.get("objects") { + None | Some(Value::Null) => Ok(Vec::new()), + Some(v) => match v.as_str() { + Some("body") => Ok(Vec::new()), + Some("component") if matches!(format, Format::ThreeMf | Format::ThreeMfTagged) => Ok(component_parts(s)), + Some("component") => Err(bad(cmd, "`objects: component` is for 3MF: other formats have no parts")), + _ => Err(bad(cmd, format!("`objects` must be body or component, not {v}"))), + }, + } +} + +/// Each placement of a component that holds two or more bodies, by its occurrence's name, with +/// the names its bodies have where they are placed (as the export names them). The design's own +/// bodies and a component's single body are left out: they stay objects of their own. +fn component_parts(s: &Session) -> Vec<(String, Vec)> { + let doc = &s.doc; + if doc.occurrences.is_empty() { + return Vec::new(); + } + let st = s.model.state(); + let owners = doc.model_body_components(&st); + let names = solidcraft_doc::WorldNames::new(doc, &st); + doc.placements() + .into_iter() + .filter(|(comp, _, _)| *comp != 0) + .filter_map(|(comp, path, _)| { + let bodies: Vec = + st.bodies.iter().zip(&owners).filter(|(_, owner)| **owner == comp).map(|(b, _)| names.name(&b.name, comp, &path)).collect(); + let name = path.last().and_then(|id| doc.occurrences.iter().find(|o| o.id == *id)).map(|o| o.name.clone()).unwrap_or_default(); + (bodies.len() >= 2).then_some((name, bodies)) + }) + .collect() +} + +fn export_to( + s: &Session, + path: &str, + format: Format, + bodies: &[String], + parts: &[(String, Vec)], + quality: solidcraft_io::MeshQuality, +) -> Result { if format == Format::Obj { // The colours of the bodies go in a material library beside the mesh file. return export_obj(s, path, bodies, quality); @@ -635,7 +680,7 @@ fn export_to(s: &Session, path: &str, format: Format, bodies: &[String], quality } else { // Bodies carry the colour they are shown in (appearance, material or imported), and the // file the design's properties where the format has a place for them. - solidcraft_io::export_with_quality(&s.doc.painted(&s.world_state()), bodies, format, &name, &s.doc.metadata, quality)? + solidcraft_io::export_with_parts(&s.doc.painted(&s.world_state()), bodies, parts, format, &name, &s.doc.metadata, quality)? }; solidcraft_io::vfs::write(path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; Ok(json!({"path": path, "bytes": bytes.len(), "format": format!("{format:?}")})) @@ -649,7 +694,8 @@ fn export(s: &mut Session, p: &Value) -> Result { return export_urdf(s, path, p); } let quality = mesh_quality(p, cmd)?; - export_to(s, path, format, &string_list(cmd, p, "bodies")?, quality) + let parts = mesh_parts(s, p, cmd, format)?; + export_to(s, path, format, &string_list(cmd, p, "bodies")?, &parts, quality) } /// The OBJ export: the mesh file and the material library beside it, with the colours of the @@ -755,10 +801,11 @@ fn save_mesh(s: &mut Session, p: &Value) -> Result { // and may be deprecated later in favour of `file.send_to_slicer` or a Send to App workflow; that is // a possibility, not a plan. let quality = mesh_quality(p, cmd)?; + let parts = mesh_parts(s, p, cmd, format)?; if let Some(spec) = str_(p, "slicer") { #[cfg(target_arch = "wasm32")] { - let _ = spec; + let _ = (spec, parts); return Err(bad(cmd, "a slicer can't be started from the browser")); } #[cfg(not(target_arch = "wasm32"))] @@ -769,6 +816,7 @@ fn save_mesh(s: &mut Session, p: &Value) -> Result { kind: crate::slicers::TargetKind::Slicer, spec, bodies: string_list(cmd, p, "bodies")?, + parts, format, quality, dest: send::Dest::Path(path), @@ -777,7 +825,7 @@ fn save_mesh(s: &mut Session, p: &Value) -> Result { }, ); } - export_to(s, path, format, &string_list(cmd, p, "bodies")?, quality) + export_to(s, path, format, &string_list(cmd, p, "bodies")?, &parts, quality) } /// The browser build can't start a program. @@ -811,6 +859,7 @@ fn send_to_slicer(s: &mut Session, p: &Value) -> Result { kind: crate::slicers::TargetKind::Slicer, spec, bodies: string_list(cmd, p, "bodies")?, + parts: Vec::new(), format, quality: Default::default(), dest: send::Dest::Folder, @@ -883,6 +932,62 @@ mod urdf_tests; mod tests { use super::*; + /// #8139: with `objects: "component"` a 3MF has one object for each placement of a component + /// with two or more bodies, its bodies the object's parts; the design's own bodies stay objects + /// of their own. The default (and `objects: "body"`) is one object per body, as before. Read + /// back, an object with parts is one mesh with all its parts' triangles. + #[test] + fn a_components_bodies_export_to_3mf_as_one_object_with_parts() { + let dir = std::env::temp_dir().join(format!("solidcraft-3mf-parts-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = |n: &str| dir.join(n).to_string_lossy().to_string(); + let read = |p: &str| -> Vec<(String, usize)> { + let (objects, warnings) = solidcraft_io::read_3mf(&std::fs::read(p).unwrap()).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + objects.iter().map(|o| (o.name.clone(), o.triangles.len())).collect() + }; + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "corner": [-30, 0, 0], "body_name": "Loose"})).unwrap(); + s.execute("component.create", &json!({"name": "Bracket"})).unwrap(); + s.execute("solid.box", &json!({"length": 20, "width": 20, "height": 10, "body_name": "Base"})).unwrap(); + s.execute("solid.cylinder", &json!({"radius": 5, "height": 10, "base": [10, 10, 10], "operation": "new", "body_name": "Boss"})).unwrap(); + s.execute("component.activate", &json!({"component": "root"})).unwrap(); + + s.execute("file.export", &json!({"path": path("bodies.3mf")})).unwrap(); + let bodies = read(&path("bodies.3mf")); + assert_eq!(bodies.len(), 3, "one object per body: {bodies:?}"); + s.execute("file.export", &json!({"path": path("body.3mf"), "objects": "body"})).unwrap(); + assert_eq!(read(&path("body.3mf")), bodies); + let loose = bodies.iter().find(|(n, _)| n == "Loose").map(|(_, t)| *t).unwrap_or(0); + let bracket: usize = bodies.iter().filter(|(n, _)| n != "Loose").map(|(_, t)| t).sum(); + + s.execute("file.export", &json!({"path": path("parts.3mf"), "objects": "component"})).unwrap(); + let parts = read(&path("parts.3mf")); + assert_eq!(parts, [("Loose".to_string(), loose), ("Bracket:1".to_string(), bracket)], "{bodies:?}"); + s.execute("file.save_mesh", &json!({"path": path("saved.3mf"), "objects": "component"})).unwrap(); + assert_eq!(read(&path("saved.3mf")), parts); + s.execute("file.export", &json!({"path": path("tagged.3mf"), "format": "3mf-tagged", "objects": "component"})).unwrap(); + assert_eq!(read(&path("tagged.3mf")), parts); + + // Placed again, each placement is an object of its own. + s.execute("occurrence.copy", &json!({"component": "Bracket", "translate": [0, 40, 0]})).unwrap(); + s.execute("file.export", &json!({"path": path("two.3mf"), "objects": "component"})).unwrap(); + let two = read(&path("two.3mf")); + assert_eq!(two, [("Loose".to_string(), loose), ("Bracket:1".to_string(), bracket), ("Bracket:2".to_string(), bracket)]); + + // Other formats have no parts, and `objects` is body or component. + let e = s.execute("file.export", &json!({"path": path("parts.stl"), "objects": "component"})).unwrap_err().to_string(); + assert!(e.contains("`objects: component` is for 3MF"), "{e}"); + let e = s.execute("file.save_mesh", &json!({"path": path("parts.stl"), "objects": "component"})).unwrap_err().to_string(); + assert!(e.contains("`objects: component` is for 3MF"), "{e}"); + for bad in [json!("parts"), json!(true), json!(2)] { + let e = s.execute("file.export", &json!({"path": path("bad.3mf"), "objects": bad})).unwrap_err().to_string(); + assert!(e.contains("`objects` must be body or component"), "{bad}: {e}"); + } + assert!(!std::path::Path::new(&path("parts.stl")).exists() && !std::path::Path::new(&path("bad.3mf")).exists()); + let _ = std::fs::remove_dir_all(&dir); + } + /// #4747: a mesh export's `quality` follows curved faces more closely. A 3 mm hole in a /// 200 mm plate gets more triangles at fine and more again at finest, in STL and 3MF alike /// (Save As Mesh too); standard is what the export always gave; anything else is refused. diff --git a/crates/engine/src/cmd/file_send.rs b/crates/engine/src/cmd/file_send.rs index 6f70b71cb..1ed3d64bc 100644 --- a/crates/engine/src/cmd/file_send.rs +++ b/crates/engine/src/cmd/file_send.rs @@ -53,6 +53,8 @@ pub(super) struct Send<'a> { /// The target as the caller named it: an id, a name, or a program path. pub spec: &'a str, pub bodies: Vec, + /// 3MF objects with parts (`objects: "component"`, #8139). Only for [`Dest::Path`]. + pub parts: Vec<(String, Vec)>, pub format: Format, /// Only for [`Dest::Path`]; the slicer folder's file is always standard. pub quality: solidcraft_io::MeshQuality, @@ -79,7 +81,7 @@ pub(super) fn send(s: &mut Session, r: Send<'_>) -> Result { return Err(bad(r.cmd, format!("{} does not take {}", target.name, format_name(r.format)))); } let mut out = match r.dest { - Dest::Path(path) => export_to(s, path, r.format, &r.bodies, r.quality)?, + Dest::Path(path) => export_to(s, path, r.format, &r.bodies, &r.parts, r.quality)?, Dest::Folder => write_in_folder(s, &r)?, }; let path = out.get("path").and_then(Value::as_str).unwrap_or_default().to_string(); diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 25467c82d..ff4e14958 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -48,7 +48,9 @@ mod gltf_in; pub use gltf_in::{GltfImport, Loader, MAX_GLTF_BYTES, MeshPlan, PlanPlace, glb_container, is_gltf_path, read_gltf}; mod obj; pub use obj::read_obj; -pub use threemf::{MAX_3MF_BYTES, MeshObject, model_xml, model_xml_with, read_3mf, weld, write_3mf, write_3mf_with}; +pub use threemf::{ + MAX_3MF_BYTES, MeshObject, model_xml, model_xml_parts, model_xml_with, read_3mf, weld, write_3mf, write_3mf_parts, write_3mf_with, +}; pub use urdf::{UrdfOptions, UrdfPackage, urdf}; use solidcraft_doc::{Document, Metadata, ModelState}; @@ -682,6 +684,21 @@ pub fn export_with_quality( name: &str, meta: &Metadata, quality: MeshQuality, +) -> Result> { + export_with_parts(state, bodies, &[], format, name, meta, quality) +} + +/// [`export_with_quality`], and in 3MF each of `parts` (a name and the names of its bodies) +/// written as one object with those bodies as its parts ([`model_xml_parts`], #8139). +/// Bodies of a part that are not exported are left out of it. Other formats have no parts. +pub fn export_with_parts( + state: &ModelState, + bodies: &[String], + parts: &[(String, Vec)], + format: Format, + name: &str, + meta: &Metadata, + quality: MeshQuality, ) -> Result> { let sel = selected(state, bodies)?; Ok(match format { @@ -716,7 +733,9 @@ pub fn export_with_quality( } Format::ThreeMf | Format::ThreeMfTagged => { let objs: Vec = sel.iter().map(|b| mesh_object(b, format == Format::ThreeMfTagged, quality)).collect::>()?; - write_3mf_with(&objs, &threemf_metadata(meta))? + let index = |n: &String| sel.iter().position(|b| &b.name == n); + let parts: Vec<(String, Vec)> = parts.iter().map(|(p, names)| (p.clone(), names.iter().filter_map(index).collect())).collect(); + write_3mf_parts(&objs, &parts, &threemf_metadata(meta))? } Format::Design => return Err(IoError::Format("sc (save the document instead)".into())), Format::Urdf => return Err(IoError::Format("urdf (an assembly package; use file.export)".into())), diff --git a/crates/io/src/threemf.rs b/crates/io/src/threemf.rs index 65c703a2c..c2c768baf 100644 --- a/crates/io/src/threemf.rs +++ b/crates/io/src/threemf.rs @@ -251,6 +251,15 @@ pub fn model_xml(objects: &[MeshObject]) -> String { /// The model part's XML with model metadata after `Application`: (3MF metadata name, such as /// `Title` or `Designer`, and its text). pub fn model_xml_with(objects: &[MeshObject], metadata: &[(&str, &str)]) -> String { + model_xml_parts(objects, &[], metadata) +} + +/// [`model_xml_with`], with `parts`: each a name and the indices of two or more `objects` written +/// as one object whose `` are their meshes, built once, so a slicer loads them as +/// one object with parts (#8139). An index out of range or already in an earlier part is left +/// out of it, and a part left with fewer than two objects is not made: those objects are built +/// on their own, as every object not in a part is. +pub fn model_xml_parts(objects: &[MeshObject], parts: &[(String, Vec)], metadata: &[(&str, &str)]) -> String { let mut x = String::new(); x.push_str("\n"); let ft = if objects.iter().any(MeshObject::tagged) { format!(" xmlns:ft=\"{FACE_TAGS_NS}\"") } else { String::new() }; @@ -314,10 +323,37 @@ pub fn model_xml_with(objects: &[MeshObject], metadata: &[(&str, &str)]) -> Stri } x.push_str(" \n \n \n"); } + // Each part an object after the meshes it names (a component refers back), built in their + // place; the meshes in it are not built on their own. + let mut in_part = vec![false; objects.len()]; + let mut built: Vec = Vec::new(); + for (name, members) in parts { + let mut kept: Vec = Vec::new(); + for &k in members { + if k < objects.len() && !in_part[k] && !kept.contains(&k) { + kept.push(k); + } + } + if kept.len() < 2 { + continue; + } + let id = objects.len() + 2 + built.len(); + let _ = writeln!(x, " ", esc(name)); + x.push_str(" \n"); + for &k in &kept { + in_part[k] = true; + let _ = writeln!(x, " ", k + 2); + } + x.push_str(" \n \n"); + built.push(id); + } x.push_str(" \n \n"); - for k in 0..objects.len() { + for k in (0..objects.len()).filter(|&k| !in_part[k]) { let _ = writeln!(x, " ", k + 2); } + for id in built { + let _ = writeln!(x, " "); + } x.push_str(" \n\n"); x } @@ -329,6 +365,11 @@ pub fn write_3mf(objects: &[MeshObject]) -> Result> { /// A 3MF package of meshes with model metadata (see [`model_xml_with`]). pub fn write_3mf_with(objects: &[MeshObject], metadata: &[(&str, &str)]) -> Result> { + write_3mf_parts(objects, &[], metadata) +} + +/// A 3MF package of meshes, some of them written as objects with parts (see [`model_xml_parts`]). +pub fn write_3mf_parts(objects: &[MeshObject], parts: &[(String, Vec)], metadata: &[(&str, &str)]) -> Result> { if objects.is_empty() { return Err(IoError::Empty); } @@ -336,7 +377,7 @@ pub fn write_3mf_with(objects: &[MeshObject], metadata: &[(&str, &str)]) -> Resu let rels = format!( "\n\n \n\n" ); - let model = model_xml_with(objects, metadata); + let model = model_xml_parts(objects, parts, metadata); let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); for (name, data) in [("[Content_Types].xml", content_types.as_bytes()), ("_rels/.rels", rels.as_bytes()), ("3D/3dmodel.model", model.as_bytes())] { @@ -965,6 +1006,35 @@ pub(crate) mod tests { } } + /// #8139: objects in a part are written once as meshes and built once, as one object whose + /// components are those meshes; the others are built on their own, as before. Read back, the + /// part is one object named after it, with every triangle of its meshes. + #[test] + fn a_part_is_one_object_whose_components_are_its_meshes() { + let objects = [tetra("Cube"), tetra("Dome"), tetra("Loose")]; + let x = model_xml_parts(&objects, &[("Bracket:1".into(), vec![0, 1])], &[]); + assert_eq!(x.matches("").count(), 3, "{x}"); + assert!(x.contains(""), "{x}"); + assert!(x.contains("") && x.contains(""), "{x}"); + let build = x.split("").nth(1).unwrap_or_default(); + assert_eq!(build.matches(" = read.iter().map(|o| o.name.as_str()).collect(); + assert_eq!(names, ["Loose", "Bracket:1"]); + assert_eq!(read[1].triangles.len(), 8); + // Without parts the file is as before: one built object per mesh. + assert_eq!(model_xml_parts(&objects, &[], &[]), model_xml_with(&objects, &[])); + assert_eq!(model_xml_with(&objects, &[]).split("").nth(1).unwrap_or_default().matches("