3MF export: a component's bodies as one object with parts (#8139) (#8187)

* claim: #8139

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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
<components> 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FAWPuFoh9qxn2uS2j53QZ

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
austin62jake
2026-10-29 03:35:38 +00:00
committed by GitHub
parent 40ff251e5f
commit d8d22cd52a
5 changed files with 215 additions and 12 deletions
+112 -7
View File
@@ -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<solidcraft_io::MeshQuality> {
}
}
fn export_to(s: &Session, path: &str, format: Format, bodies: &[String], quality: solidcraft_io::MeshQuality) -> Result<Value> {
/// 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<Vec<(String, Vec<String>)>> {
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<String>)> {
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<String> =
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<String>)],
quality: solidcraft_io::MeshQuality,
) -> Result<Value> {
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<Value> {
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<Value> {
// 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<Value> {
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<Value> {
},
);
}
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<Value> {
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.
+3 -1
View File
@@ -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<String>,
/// 3MF objects with parts (`objects: "component"`, #8139). Only for [`Dest::Path`].
pub parts: Vec<(String, Vec<String>)>,
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<Value> {
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();