Preserve imported part names and IGES assembly structure (#1609)

Build on #1426's import components and nested STEP assembly instances.
Replace placeholder solid labels with meaningful part or instance names.
Translate IGES groups and subfigure instances through the existing STEP
component path, preserving nesting and placements and sewing surfaces
within each group. Bound assembly walks and reuse work buffers.

Related to:
- tangency-labs/solidcraft#1386
- tangency-labs/solidcraft#1426

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Luke JonesandCodex authored and GitHub committed 2026-10-21 00:39:08 +00:00
1 parent 2f43ad5c5b
commit 26c0c19ef7
10 files changed
+571 -90

No files matched your search

+6 -5
View File
@@ -20,11 +20,11 @@ pub static COMMANDS: &[CommandSpec] = &[
.icon("open")
.key("Ctrl+O")
.noundo()
.params("path: .solidcraft design, or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step)"),
.params("path: .solidcraft design, or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: auto|solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step)"),
CommandSpec::new("file.insert_step", "Insert STEP", insert_step)
.at("SOLID", "INSERT")
.icon("import")
.params("path: STEP, IGES, FreeCAD .FCStd or Rhino .3dm file (its bodies join the design as an Import base feature in a new component named after the file, placed in the active component; an assembly's products become nested components, a repeated part one component with an occurrence per placement, all held as one rigid group until component.unlock → component, component_name, occurrence, subcomponents?, rigid_joints?); name? (the feature's and the component's); up?: z|y (default z: the file's axes are kept; y: the file has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence); names?: solid|product|instance (what the bodies are named after: the solid's own name, else the product's (default); the name of the product (part) that holds the body; the name of the assembly occurrence (instance), else the product's); matrix?: [12 or 16 numbers] (where the new component's occurrence sits in the active component, after `up`: a rigid row-major 3x4 rotation-and-translation or 4x4 matrix, flat or as rows, as occurrence.move takes it; a scale, shear or mirror is refused before the file is read); tolerance? (see occurrence.move)"),
.params("path: STEP, IGES, FreeCAD .FCStd or Rhino .3dm file (its bodies join the design as an Import base feature in a new component named after the file, placed in the active component; an assembly's products become nested components, a repeated part one component with an occurrence per placement, all held as one rigid group until component.unlock → component, component_name, occurrence, subcomponents?, rigid_joints?); name? (the feature's and the component's); up?: z|y (default z: the file's axes are kept; y: the file has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence); names?: auto|solid|product|instance (default auto: keep meaningful solid names, replace placeholders with the nearest named product, else instance; solid: the solid's own name; product: the part's name; instance: the occurrence's name, else the product's); matrix?: [12 or 16 numbers] (where the new component's occurrence sits in the active component, after `up`: a rigid row-major 3x4 rotation-and-translation or 4x4 matrix, flat or as rows, as occurrence.move takes it; a scale, shear or mirror is refused before the file is read); tolerance? (see occurrence.move)"),
CommandSpec::new("file.insert_mesh", "Insert Mesh", insert_mesh)
.at("SOLID", "INSERT")
.icon("import")
@@ -89,9 +89,10 @@ fn step_options(p: &Value, cmd: &str) -> Result<StepOptions> {
};
let names = match p.get("names") {
None | Some(Value::Null) => solidcraft_io::StepNames::default(),
Some(v) => {
v.as_str().and_then(solidcraft_io::StepNames::parse).ok_or_else(|| bad(cmd, "`names` must be \"solid\", \"product\" or \"instance\""))?
}
Some(v) => v
.as_str()
.and_then(solidcraft_io::StepNames::parse)
.ok_or_else(|| bad(cmd, "`names` must be \"auto\", \"solid\", \"product\" or \"instance\""))?,
};
Ok(StepOptions { y_up, names })
}
+29 -2
View File
@@ -170,8 +170,8 @@ fn wrong_up_and_names_are_refused() {
assert_eq!(kinds(&s), ["BoxFeature", "BaseFeature"]);
}
/// `names` says what the bodies are called: the solid's own name (the default), the part's, or
/// the assembly occurrence's. Repeated names are numbered as ever.
/// Explicit naming choices select the solid, part or occurrence; automatic naming keeps
/// meaningful solid names.
#[test]
fn the_bodies_are_named_after_the_solid_the_product_or_the_instance() {
let path = frame_file("names");
@@ -185,6 +185,7 @@ fn the_bodies_are_named_after_the_solid_the_product_or_the_instance() {
// The post is placed twice: one component, two occurrences, its body built once (#1386).
let solids = ["Cut-Extrude3", "Boss-Extrude1"];
assert_eq!(named(json!({"path": path})), solids);
assert_eq!(named(json!({"path": path, "names": "auto"})), solids);
assert_eq!(named(json!({"path": path, "names": "solid"})), solids);
assert_eq!(named(json!({"path": path, "names": "product"})), ["Plate", "Post"]);
assert_eq!(named(json!({"path": path, "names": "Instance"})), ["Plate-1", "Post-1"]);
@@ -228,3 +229,29 @@ fn a_step_file_can_be_inserted_at_a_matrix() {
assert!(e.contains("not rigid"), "{e}");
assert!(d.doc.features.is_empty() && d.doc.occurrences.is_empty());
}
/// Generated body labels become part names, and the saved assembly retains its components
/// and repeated placements without needing the source file.
#[test]
fn automatic_part_names_and_assembly_survive_reopening() {
let path = frame_file("automatic");
let text = std::fs::read_to_string(&path).unwrap().replace("'Cut-Extrude3'", "'Body1'").replace("'Boss-Extrude1'", "'Body 2 (3)'");
std::fs::write(&path, text).unwrap();
let mut s = Session::default();
let r = run(&mut s, "file.insert_step", json!({"path": path}));
assert_eq!(body_names(&s), ["Plate", "Post"]);
let top = r["component"].as_u64().unwrap();
let parts: Vec<_> = s.doc.components.iter().filter(|c| c.parent == top).collect();
assert_eq!(parts.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["Plate", "Post"]);
assert_eq!(s.doc.occurrences.iter().filter(|o| o.component == parts[1].id && o.parent == top).count(), 2);
let design = std::path::Path::new(&path).with_file_name("automatic.solidcraft");
run(&mut s, "file.save_as", json!({"path": design.to_string_lossy()}));
std::fs::remove_file(&path).unwrap();
let mut again = Session::default();
run(&mut again, "doc.open", json!({"path": design.to_string_lossy()}));
assert_eq!(body_names(&again), ["Plate", "Post"]);
assert_eq!(again.doc.components, s.doc.components);
assert_eq!(again.doc.occurrences, s.doc.occurrences);
assert!(near(extent(&again).0, [0.0, 0.0, 0.0]) && near(extent(&again).1, [40.0, 34.0, 20.0]));
assert!((total_volume(&mut again) - (40.0 * 4.0 * 20.0 + 2.0 * 4.0 * 30.0 * 4.0)).abs() < 1e-6);
}
+31 -12
View File
@@ -101,8 +101,10 @@ pub fn is_iges_path(path: &str) -> bool {
/// nothing), so the caller chooses.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StepNames {
/// The solid's own name in the file, else the name of the product that holds it.
/// Keep meaningful solid names; replace placeholders with the nearest named product.
#[default]
Auto,
/// The solid's own name in the file, else the name of the product that holds it.
Solid,
/// The name of the product (part) that holds the body, else the solid's name.
Product,
@@ -112,9 +114,10 @@ pub enum StepNames {
}
impl StepNames {
/// `solid`, `product` or `instance` (any case); `None` for anything else.
/// `auto`, `solid`, `product` or `instance` (any case); `None` for anything else.
pub fn parse(s: &str) -> Option<StepNames> {
match s.trim().to_ascii_lowercase().as_str() {
"auto" => Some(StepNames::Auto),
"solid" => Some(StepNames::Solid),
"product" => Some(StepNames::Product),
"instance" => Some(StepNames::Instance),
@@ -126,7 +129,16 @@ impl StepNames {
/// A name that says nothing about its body: empty, or the placeholder a file or the importer
/// gives to something it has no name for.
fn generic_name(n: &str) -> bool {
n.trim().is_empty() || n.starts_with('(') || n.eq_ignore_ascii_case("import") || n.eq_ignore_ascii_case("unnamed")
let n = n.trim();
n.is_empty()
|| n.starts_with('(')
|| n.eq_ignore_ascii_case("import")
|| n.eq_ignore_ascii_case("unnamed")
|| ["body", "solid", "shell"].iter().any(|prefix| {
n.get(..prefix.len()).is_some_and(|s| s.eq_ignore_ascii_case(prefix))
&& n.get(prefix.len()..)
.is_some_and(|s| s.chars().all(|c| c.is_ascii_digit() || c.is_ascii_whitespace() || matches!(c, '_' | '-' | '(' | ')')))
})
}
/// The name an imported body gets under the `names` choice; the solid's name when the chosen
@@ -134,6 +146,8 @@ fn generic_name(n: &str) -> bool {
fn body_name(b: &solidcraft_kernel::ImportedBody, names: StepNames) -> String {
let usable = |n: &&String| !generic_name(n);
let chosen = match names {
StepNames::Auto if !generic_name(&b.name) => Some(&b.name),
StepNames::Auto => b.path.iter().rev().find(usable).or_else(|| b.instance.as_ref().filter(usable)),
StepNames::Solid => None,
StepNames::Product => b.path.last().filter(usable),
StepNames::Instance => b.instance.as_ref().filter(usable).or(b.path.last().filter(usable)),
@@ -146,8 +160,7 @@ pub struct StepFeature {
/// Timeline name: the root product's name, else the file name.
pub name: String,
pub kind: solidcraft_doc::FeatureKind,
/// Body names from the file, as [`StepNames`] chose them (by default the solid names, else
/// the product names).
/// Body names from the file, as [`StepNames`] chose them (automatic by default).
pub body_names: Vec<String>,
pub warnings: Vec<String>,
/// The file as read. Hold it until the feature has been evaluated: the timeline then reuses
@@ -748,7 +761,7 @@ mod tests {
let step = String::from_utf8(export_with_metadata(&m.state(), &[], Format::Step, "t", &meta).unwrap()).unwrap();
assert!(step.contains("FILE_DESCRIPTION(('Vented Geh\\X2\\00E4\\X0\\use for a Pi'),'2;1');"), "{}", &step[..300]);
assert!(step.contains("FILE_NAME('t.step','',('Jane O''Brien'),('ACME'),"), "{}", &step[..300]);
assert_eq!(step_import_feature(step.as_bytes(), "t.step").unwrap().body_names, ["Body1"], "still reads back");
assert_eq!(step_import_feature(step.as_bytes(), "t.step").unwrap().body_names, ["t"], "still reads back");
let iges = String::from_utf8(export_with_metadata(&m.state(), &[], Format::Iges, "t", &meta).unwrap()).unwrap();
assert!(iges.contains("12HJane O'Brien") && iges.contains("4HACME"));
let model_xml = |bytes: Vec<u8>| {
@@ -812,7 +825,7 @@ mod tests {
let f = step_import_feature(s.as_bytes(), "/tmp/My Part.step").unwrap();
// Named after the exported product (the export was called `t`).
assert_eq!(f.name, "t");
assert_eq!(f.body_names, ["Body1"]);
assert_eq!(f.body_names, ["t"]);
assert_eq!(f.body_names.len(), 1);
assert!(matches!(&f.kind, FeatureKind::Import { file, .. } if file == "My Part.step"));
let mut imported = Document::new("Imported STEP round trip");
@@ -862,9 +875,8 @@ mod tests {
step_export_products(&products, 0, &StepHeader::default()).unwrap()
}
/// The bodies of a STEP file are named after the solid (the default), the product that holds
/// them, or the assembly occurrence; a name the file leaves out or fills with a placeholder
/// falls back to the next one.
/// Automatic names keep meaningful solid labels and replace placeholders with part names.
/// Explicit choices still select the solid, product or occurrence.
#[test]
fn step_import_names_follow_the_choice() {
let text = frame_step();
@@ -872,10 +884,15 @@ mod tests {
assert_eq!(names(&text, StepNames::Solid), ["Cut-Extrude3", "Boss-Extrude1", "Boss-Extrude1"]);
assert_eq!(names(&text, StepNames::Product), ["Plate", "Post", "Post"]);
assert_eq!(names(&text, StepNames::Instance), ["Plate-1", "Post-1", "Post-2"]);
// Without a choice it is the solid's name, as before.
// Meaningful solid names survive automatic naming, including SolidCraft exports.
assert_eq!(step_import_feature(text.as_bytes(), "frame.step").unwrap().body_names, names(&text, StepNames::Solid));
let generic = text.replace("'Cut-Extrude3'", "'Body1'").replace("'Boss-Extrude1'", "'Body 2 (3)'");
assert_eq!(step_import_feature(generic.as_bytes(), "frame.step").unwrap().body_names, ["Plate", "Post", "Post"]);
assert_eq!(names(&generic, StepNames::Solid), ["Body1", "Body 2 (3)", "Body 2 (3)"]);
let named = generic.replace("'Body1'", "'Body housing'");
assert_eq!(names(&named, StepNames::Auto), ["Body housing", "Post", "Post"]);
// The timeline entry is the root product's name whatever the bodies are called.
for choice in [StepNames::Solid, StepNames::Product, StepNames::Instance] {
for choice in [StepNames::Auto, StepNames::Solid, StepNames::Product, StepNames::Instance] {
assert_eq!(step_import_feature_named(text.as_bytes(), "frame.step", choice).unwrap().name, "Frame");
}
// A product the file leaves unnamed says nothing: its bodies keep the solid's name.
@@ -887,6 +904,8 @@ mod tests {
assert_eq!(names(&part, StepNames::Solid), ["Body1"]);
assert_eq!(names(&part, StepNames::Product), ["Bracket"]);
assert_eq!(names(&part, StepNames::Instance), ["Bracket"]);
assert_eq!(names(&part, StepNames::Auto), ["Bracket"]);
assert_eq!(StepNames::parse(" AuTo "), Some(StepNames::Auto));
assert_eq!(StepNames::parse(" Product "), Some(StepNames::Product));
assert_eq!(StepNames::parse("INSTANCE"), Some(StepNames::Instance));
assert_eq!(StepNames::parse("label"), None);
+54 -57
View File
@@ -9,6 +9,8 @@
use std::collections::HashMap;
use std::fmt::Write as _;
mod assembly;
/// Largest IGES file we read.
pub const MAX_IGES_BYTES: usize = 512 << 20;
const MAX_ENTITIES: usize = 2_000_000;
@@ -1240,77 +1242,42 @@ fn translate(text: &str) -> std::result::Result<(String, Vec<String>), String> {
// Entities used by others (a B-rep's faces, a trimmed surface's curves) are not roots;
// physically dependent entities have status digits 01 in columns 3–4, but files are lax:
// collect references instead.
let mut solids: Vec<(u64, String)> = Vec::new();
let assembly = assembly::Assembly::read(&t, &seqs)?;
let mut solids = HashMap::new();
let mut styles: Vec<(u64, [f32; 3])> = Vec::new();
let mut n = 0usize;
let mut fallback = String::new();
let watch = crate::watch::current();
for &s in &seqs {
if watch.as_ref().is_some_and(|w| w.cancelled()) {
return Err("IGES import cancelled".into());
}
let Some(de) = f.des.get(&s) else { continue };
if de.typ != 186 {
continue;
}
n += 1;
// A name property (406 form 15) among the solid's trailing pointers, else the label.
let named = f.params.get(&s).and_then(|p| {
p.iter().skip(4).filter_map(|x| int(x)).filter(|x| *x > 0).find_map(|ptr| {
let d = f.des.get(&usize::try_from(ptr).ok()?)?;
(d.typ == 406 && d.form == 15).then(|| f.params.get(&usize::try_from(ptr).ok()?)?.get(2).cloned()).flatten()
})
});
let name = match named.filter(|x| !x.trim().is_empty()) {
Some(x) => x.trim().to_string(),
None if de.label.is_empty() => format!("Body{n}"),
None => de.label.clone(),
let name = if let Some(name) = assembly::entity_name(&f, s) {
name
} else {
fallback.clear();
let _ = write!(fallback, "Body{n}");
fallback.as_str()
};
match brep(&mut t, s as i64, &mut styles) {
Ok((id, color)) => {
let named = {
// Re-label the solid with its name.
let line = t.o.lines.get(id as usize - 1).cloned().unwrap_or_default();
line.replacen("('',", &format!("('{}',", name.replace('\'', "''")), 1)
};
if let Some(l) = t.o.lines.get_mut(id as usize - 1) {
*l = named;
*l = l.replacen("('',", &format!("('{}',", name.replace('\'', "''")), 1);
}
if let Some(c) = color {
styles.push((id, c));
}
solids.push((id, name));
solids.insert(s, id);
}
Err(e) => t.warn(format!("solid {name}: not read: {e}")),
}
}
// Trimmed and bounded surfaces not used by anything else: sewn into shells.
let mut faces = Vec::new();
let mut sw = Sewer { tol, verts: Vec::new(), grid: HashMap::new(), edges: Vec::new(), by_ends: HashMap::new() };
if solids.is_empty() {
for &s in &seqs {
let Some(de) = f.des.get(&s) else { continue };
if de.typ != 144 && de.typ != 143 && !(de.typ == 128 && is_root(&f, s)) {
continue;
}
match trimmed(&mut t, &mut sw, s as i64) {
Ok(fb) => faces.push(fb),
Err(e) => t.warn(format!("surface {s}: not read: {e}")),
}
}
if !faces.is_empty() {
orient(&mut faces);
let (shell, closed) = write_shell(&mut t.o, &sw, &faces, &mut styles);
let item = if closed {
t.o.add(format!("MANIFOLD_SOLID_BREP('Body1',#{shell})"))
} else {
t.warn("the surfaces do not close into a solid: imported as an open body");
t.o.add(format!("SHELL_BASED_SURFACE_MODEL('Body1',(#{shell}))"))
};
solids.push((item, "Body1".into()));
}
}
if solids.is_empty() {
let why = t.warnings.first().cloned().unwrap_or_else(|| "no solids or trimmed surfaces".into());
return Err(format!("IGES import: nothing to read ({why})"));
}
let items = solids.iter().map(|(i, _)| format!("#{i}")).collect::<Vec<_>>().join(",");
t.o.add(format!("ADVANCED_BREP_SHAPE_REPRESENTATION('',({items}),#{ctx})"));
assembly.write(&mut t, &seqs, &solids, &mut styles, ctx)?;
for (item, c) in styles {
let rgb = t.o.add(format!("COLOUR_RGB('',{},{},{})", r(c[0] as f64), r(c[1] as f64), r(c[2] as f64)));
let fasc = t.o.add(format!("FILL_AREA_STYLE_COLOUR('',#{rgb})"));
@@ -1331,12 +1298,42 @@ fn translate(text: &str) -> std::result::Result<(String, Vec<String>), String> {
Ok((s, t.warnings))
}
/// A surface entity nobody refers to (a bare B-spline patch is a face of its own).
fn is_root(f: &Iges, seq: usize) -> bool {
let target = seq.to_string();
!f.params
.iter()
.any(|(s, p)| *s != seq && f.des.get(s).is_some_and(|d| d.typ != 406 && d.typ != 402) && p.iter().skip(1).any(|x| x.trim() == target))
/// Sew surfaces within their owning group, keeping different parts separate.
fn sew_surfaces(
t: &mut Tr,
seqs: impl Iterator<Item = usize>,
name: &str,
styles: &mut Vec<(u64, [f32; 3])>,
faces: &mut Vec<FaceB>,
sw: &mut Sewer,
) -> R<Option<u64>> {
faces.clear();
sw.verts.clear();
sw.grid.clear();
sw.edges.clear();
sw.by_ends.clear();
let watch = crate::watch::current();
for seq in seqs {
if watch.as_ref().is_some_and(|w| w.cancelled()) {
return Err("IGES import cancelled".into());
}
match trimmed(t, sw, seq as i64) {
Ok(face) => faces.push(face),
Err(e) => t.warn(format!("surface {seq}: not read: {e}")),
}
}
if faces.is_empty() {
return Ok(None);
}
orient(faces);
let (shell, closed) = write_shell(&mut t.o, sw, faces, styles);
let name = name.replace('\'', "''");
Ok(Some(if closed {
t.o.add(format!("MANIFOLD_SOLID_BREP('{name}',#{shell})"))
} else {
t.warn("the surfaces do not close into a solid: imported as an open body");
t.o.add(format!("SHELL_BASED_SURFACE_MODEL('{name}',(#{shell}))"))
}))
}
/// A trimmed (144) or bounded (143) surface, or a bare B-spline surface, as a face.
+280
View File
@@ -0,0 +1,280 @@
//! IGES groups (402) and subfigures (308/408), from the published IGES specification.
//! Definitions become STEP products; instances refer to them without copying geometry.
//! Reference: https://nvlpubs.nist.gov/nistpubs/Legacy/IR/nbsir88-3813.pdf
use super::*;
use std::collections::HashSet;
const MAX_GROUPS: usize = 10_000;
const MAX_INSTANCES: usize = 100_000;
const MAX_REFERENCES: usize = 4 * MAX_ENTITIES;
struct Group {
seq: usize,
members: Vec<usize>,
}
struct Instance {
definition: usize,
transform: Xf,
}
pub(super) struct Assembly {
groups: Vec<Group>,
indices: HashMap<usize, usize>,
instances: HashMap<usize, Instance>,
referenced: HashSet<usize>,
surface_references: HashSet<usize>,
}
impl Assembly {
pub(super) fn read(t: &Tr, seqs: &[usize]) -> R<Self> {
let mut out = Self {
groups: Vec::new(),
indices: HashMap::new(),
instances: HashMap::new(),
referenced: HashSet::new(),
surface_references: HashSet::new(),
};
let mut references = 0usize;
let watch = crate::watch::current();
for &seq in seqs {
if watch.as_ref().is_some_and(|w| w.cancelled()) {
return Err("IGES import cancelled".into());
}
let de = t.de(seq as i64)?;
if de.typ == 308 || (de.typ == 402 && matches!(de.form, 1 | 7 | 14 | 15)) {
if out.groups.len() >= MAX_GROUPS {
return Err("too many IGES assembly definitions".into());
}
let field = if de.typ == 308 { 3 } else { 1 };
let count = usize::try_from(t.i(seq as i64, field)?).map_err(|_| "negative IGES group size")?;
references = references.saturating_add(count);
if count > MAX_LIST || references > MAX_REFERENCES {
return Err("IGES assembly references exceed the work limit".into());
}
let p = t.p(seq as i64)?;
let entries = p.get(field + 1..field + 1 + count).ok_or("truncated IGES group")?;
let mut members = Vec::with_capacity(count);
for entry in entries {
let child = int(entry).and_then(|x| usize::try_from(x).ok()).filter(|x| *x > 0).ok_or("invalid IGES group reference")?;
t.de(child as i64)?;
members.push(child);
out.referenced.insert(child);
}
out.indices.insert(seq, out.groups.len());
out.groups.push(Group { seq, members });
} else if de.typ == 408 {
if out.instances.len() >= MAX_INSTANCES {
return Err("too many IGES assembly instances".into());
}
let definition = usize::try_from(t.i(seq as i64, 1)?).map_err(|_| "invalid IGES subfigure reference")?;
if t.de(definition as i64)?.typ != 308 {
return Err("IGES instance does not refer to a subfigure definition".into());
}
let p = t.p(seq as i64)?;
let scale = match p.get(5).map(|s| s.trim()) {
None | Some("") => 1.0,
Some(s) => num(s).filter(|x| *x != 0.0).ok_or("invalid IGES instance scale")?,
};
let [x, y, z] = t.pt(seq as i64, 2)?;
let local = Xf([[scale, 0.0, 0.0, x], [0.0, scale, 0.0, y], [0.0, 0.0, scale, z]]);
let transform = t.own_xf(seq as i64, 0)?.then(&local).then(&t.own_xf(definition as i64, 0)?);
if !transform.0.iter().flatten().all(|v| v.is_finite()) {
return Err("non-finite IGES instance placement".into());
}
out.instances.insert(seq, Instance { definition, transform });
out.referenced.insert(definition);
}
}
// Index geometry references once instead of rescanning all parameters for each patch.
for (&seq, params) in &t.f.params {
if watch.as_ref().is_some_and(|w| w.cancelled()) {
return Err("IGES import cancelled".into());
}
if t.f.des.get(&seq).is_some_and(|d| matches!(d.typ, 308 | 402 | 406 | 408)) {
continue;
}
for p in params.iter().skip(1) {
let p = p.trim();
if p.starts_with('0') {
continue;
}
if let Ok(id) = p.parse::<usize>()
&& id != seq
&& t.f.des.get(&id).is_some_and(|d| d.typ == 128)
{
out.surface_references.insert(id);
}
}
}
let mut depths = HashMap::with_capacity(out.groups.len());
let mut placements = out.groups.iter().filter(|g| !out.referenced.contains(&g.seq)).count()
+ out.instances.keys().filter(|s| !out.referenced.contains(*s)).count();
for group in &out.groups {
placements += group.members.iter().filter(|s| out.indices.contains_key(*s) || out.instances.contains_key(*s)).count();
if placements > MAX_INSTANCES {
return Err("too many IGES assembly placements".into());
}
out.depth(group.seq, 0, &mut depths)?;
}
Ok(out)
}
fn depth(&self, seq: usize, depth: usize, seen: &mut HashMap<usize, Option<usize>>) -> R<usize> {
if depth >= MAX_DEPTH {
return Err("IGES assembly nesting is too deep".into());
}
if let Some(height) = seen.get(&seq) {
return height.ok_or_else(|| "cyclic IGES assembly".into());
}
seen.insert(seq, None);
let group = self.indices.get(&seq).and_then(|i| self.groups.get(*i)).ok_or("missing IGES assembly definition")?;
let mut height = 1;
for child in &group.members {
let definition = self.instances.get(child).map(|i| i.definition).unwrap_or(*child);
if self.indices.contains_key(&definition) {
height = height.max(1 + self.depth(definition, depth + 1, seen)?);
}
}
if height > MAX_DEPTH {
return Err("IGES assembly nesting is too deep".into());
}
seen.insert(seq, Some(height));
Ok(height)
}
pub(super) fn write(&self, t: &mut Tr, seqs: &[usize], solids: &HashMap<usize, u64>, styles: &mut Vec<(u64, [f32; 3])>, ctx: u64) -> R<()> {
let app = t.o.add("APPLICATION_CONTEXT('mechanical design')");
let pc = t.o.add(format!("PRODUCT_CONTEXT('',#{app},'mechanical')"));
let dc = t.o.add(format!("PRODUCT_DEFINITION_CONTEXT('part definition',#{app},'design')"));
let origin = t.o.placement([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]);
let mut products = HashMap::with_capacity(self.groups.len() + 1);
let mut items = Vec::new();
let mut list = String::new();
let mut fallback = String::new();
let mut made = 0usize;
let f = t.f;
let mut faces = Vec::new();
let mut sewer = Sewer { tol: t.tol, verts: Vec::new(), grid: HashMap::new(), edges: Vec::new(), by_ends: HashMap::new() };
let watch = crate::watch::current();
// A synthetic root holds loose geometry and top-level groups/instances.
for group in std::iter::once(None).chain(self.groups.iter().map(Some)) {
if watch.as_ref().is_some_and(|w| w.cancelled()) {
return Err("IGES import cancelled".into());
}
let seq = group.map(|g| g.seq).unwrap_or(0);
let name = if seq == 0 {
"Import"
} else if let Some(name) = entity_name(f, seq) {
name
} else {
fallback.clear();
let _ = write!(fallback, "Group {seq}");
fallback.as_str()
};
items.clear();
let members = group.map(|g| g.members.as_slice()).unwrap_or(seqs);
items.extend(members.iter().filter(|s| seq != 0 || !self.referenced.contains(*s)).filter_map(|s| solids.get(s).copied()));
let surfaces = members
.iter()
.copied()
.filter(|s| seq != 0 || !self.referenced.contains(s))
.filter(|s| f.des.get(s).is_some_and(|d| matches!(d.typ, 143 | 144) || (d.typ == 128 && !self.surface_references.contains(s))));
if let Some(item) = sew_surfaces(t, surfaces, if seq == 0 { "Body1" } else { name }, styles, &mut faces, &mut sewer)? {
items.push(item);
}
made += items.len();
list.clear();
let _ = write!(list, "#{origin}");
for item in &items {
let _ = write!(list, ",#{item}");
}
let rep = t.o.add(format!("ADVANCED_BREP_SHAPE_REPRESENTATION('',({list}),#{ctx})"));
let name = name.replace('\'', "''");
let product = t.o.add(format!("PRODUCT('{name}','{name}','',(#{pc}))"));
let formation = t.o.add(format!("PRODUCT_DEFINITION_FORMATION('','',#{product})"));
let pd = t.o.add(format!("PRODUCT_DEFINITION('design','',#{formation},#{dc})"));
let shape = t.o.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{pd})"));
t.o.add(format!("SHAPE_DEFINITION_REPRESENTATION(#{shape},#{rep})"));
products.insert(seq, (pd, rep));
}
if made == 0 {
let why = t.warnings.first().map(String::as_str).unwrap_or("no solids or trimmed surfaces");
return Err(format!("IGES import: nothing to read ({why})"));
}
for group in std::iter::once(None).chain(self.groups.iter().map(Some)) {
let parent = group.map(|g| g.seq).unwrap_or(0);
let members = group.map(|g| g.members.as_slice()).unwrap_or(seqs);
for &child in members {
if watch.as_ref().is_some_and(|w| w.cancelled()) {
return Err("IGES import cancelled".into());
}
if parent == 0 && self.referenced.contains(&child) {
continue;
}
let (definition, transform) = match self.instances.get(&child) {
Some(i) => (i.definition, i.transform),
None if self.indices.contains_key(&child) => (child, t.own_xf(child as i64, 0)?),
_ => continue,
};
let (parent_pd, parent_rep) = products.get(&parent).copied().ok_or("missing IGES assembly parent")?;
let (child_pd, child_rep) = products.get(&definition).copied().ok_or("missing IGES assembly child")?;
let label = entity_name(f, child).unwrap_or("").replace('\'', "''");
let nauo = t.o.add(format!("NEXT_ASSEMBLY_USAGE_OCCURRENCE('{child}','{label}','',#{parent_pd},#{child_pd},$)"));
let shape = t.o.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{nauo})"));
let op = transformation(&mut t.o, transform)?;
let rr = t.o.add(format!("(REPRESENTATION_RELATIONSHIP('','',#{child_rep},#{parent_rep})REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(#{op})SHAPE_REPRESENTATION_RELATIONSHIP())"));
t.o.add(format!("CONTEXT_DEPENDENT_SHAPE_REPRESENTATION(#{rr},#{shape})"));
}
}
Ok(())
}
}
fn transformation(out: &mut Out, xf: Xf) -> R<u64> {
if !xf.0.iter().flatten().all(|v| v.is_finite()) {
return Err("non-finite IGES assembly placement".into());
}
let [x, y, z] = [xf.dir([1.0, 0.0, 0.0]), xf.dir([0.0, 1.0, 0.0]), xf.dir([0.0, 0.0, 1.0])];
let [sx, sy, sz] = [norm(x), norm(y), norm(z)];
let scale = xf.scale();
if [sx, sy, sz, scale].iter().any(|s| !s.is_finite() || *s <= 1e-300) {
return Err("singular IGES assembly placement".into());
}
let (x, y, z, o) = (out.dir(mul(x, 1.0 / sx)), out.dir(mul(y, 1.0 / sy)), out.dir(mul(z, 1.0 / sz)), out.point(xf.point([0.0; 3])));
Ok(out.add(format!("CARTESIAN_TRANSFORMATION_OPERATOR_3D_NON_UNIFORM('','',#{x},#{y},#{o},{},#{z},{},{})", r(sx), r(sy), r(sz))))
}
/// Name properties follow the associativity pointers; member pointers are not properties.
pub(super) fn entity_name(f: &Iges, seq: usize) -> Option<&str> {
let de = f.des.get(&seq)?;
let p = f.params.get(&seq)?;
let count = |i: usize| p.get(i).and_then(|s| int(s)).and_then(|x| usize::try_from(x).ok()).filter(|n| *n <= MAX_LIST);
let end = match de.typ {
186 => count(3)?.checked_mul(2)?.checked_add(4)?,
308 => count(3)?.checked_add(4)?,
402 => count(1)?.checked_add(2)?,
408 => 6,
_ => p.len(),
};
let property = (|| {
let after = end.checked_add(count(end)?)?.checked_add(1)?;
let n = count(after)?;
p.get(after + 1..after + 1 + n)?.iter().find_map(|s| {
let id = int(s).and_then(|x| usize::try_from(x).ok())?;
let d = f.des.get(&id)?;
if d.typ != 406 || d.form != 15 {
return None;
}
f.params.get(&id)?.get(2).and_then(|s| name_text(s))
})
})();
property.or_else(|| if de.typ == 308 { p.get(2).and_then(|s| name_text(s)) } else { None }).or_else(|| name_text(&de.label))
}
/// Match the component-name limit before copying or repeating a shared name property.
fn name_text(s: &str) -> Option<&str> {
let end = s.char_indices().nth(128).map(|(i, _)| i).unwrap_or(s.len());
let name = s.get(..end)?.trim();
(!name.is_empty()).then_some(name)
}
+134 -6
View File
@@ -156,15 +156,116 @@ fn an_arc_revolved_about_its_centre_is_a_cap_not_a_ball() {
assert!(rel(area, cap) < 1e-3, "area {area} vs {cap}");
}
/// A unit-cube-like box (10 × 20 × 30) made of six trimmed bilinear B-spline patches whose
/// boundaries are lines: sewn into a closed solid.
/// An exported box inside a named group and nested subfigures, placed twice. The second
/// placement composes its translation and scale with a directory transformation.
fn assembly_file(form: i64, scale: f64) -> String {
let body = box_solid(Vec3::ZERO, Vec3::new(2.0, 3.0, 4.0)).unwrap();
let text = iges_export_bodies(&[ExportBody { name: "Body1".into(), body: &body, color: None }], &StepHeader::default()).unwrap();
let f = parse(&text).unwrap();
let mut ids: Vec<_> = f.des.keys().copied().collect();
ids.sort_unstable();
let solid = *ids.iter().find(|&&s| f.des[&s].typ == 186).unwrap();
let mut transforms: HashMap<_, _> = f.des.iter().map(|(seq, d)| (*seq, d.xform)).collect();
let mut ents: Vec<_> = ids
.iter()
.enumerate()
.map(|(k, seq)| {
assert_eq!(*seq, 2 * k + 1);
let d = &f.des[seq];
let p = f.params[seq]
.iter()
.skip(1)
.map(|s| if s.is_empty() || num(s).is_some() { s.clone() } else { format!("{}H{s}", s.chars().count()) })
.collect::<Vec<_>>()
.join(",");
(d.typ, d.form, p)
})
.collect();
let definition = 2 * ents.len() + 1;
ents.push((308, 0, format!("0,8HLead rod,1,{solid}")));
let first = 2 * ents.len() + 1;
ents.push((408, 0, format!("{definition},10.,0.,0.,1.")));
let rotation = 2 * ents.len() + 1;
ents.push((124, 0, "0.,-1.,0.,100.,1.,0.,0.,0.,0.,0.,1.,0.".into()));
let second = 2 * ents.len() + 1;
ents.push((408, 0, format!("{definition},0.,20.,0.,{scale}")));
transforms.insert(second, rotation as i64);
let frame = 2 * ents.len() + 1;
ents.push((308, 0, format!("1,5HFrame,2,{first},{second}")));
let property = 2 * ents.len() + 1;
ents.push((406, 15, "1,6HMotion".into()));
ents.push((402, form, format!("1,{frame},0,1,{property}")));
iges_file(&ents)
.lines()
.map(|line| {
if line.as_bytes()[72] != b'D' {
return line.to_string();
}
let seq: usize = line[73..80].trim().parse().unwrap();
match transforms.get(&seq) {
Some(xf) => format!("{}{:>8}{}", &line[..48], xf, &line[56..]),
None => line.to_string(),
}
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn trimmed_surfaces_sew_into_a_solid() {
let c =
|i: usize| -> [f64; 3] { [if i & 1 != 0 { 10.0 } else { 0.0 }, if i & 2 != 0 { 20.0 } else { 0.0 }, if i & 4 != 0 { 30.0 } else { 0.0 }] };
fn groups_and_subfigure_instances_keep_names_structure_and_placements() {
for (form, scale) in [(1, 1.0), (7, 2.0), (14, 1.0), (15, 2.0)] {
let imp = iges_import(&assembly_file(form, scale)).unwrap();
assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);
assert_eq!(imp.bodies.len(), 2);
assert_eq!(imp.tree.len(), 1);
let motion = &imp.tree[0].children[0];
assert_eq!(motion.name, "Motion");
let frame = &motion.children[0];
assert_eq!(frame.name, "Frame");
assert_eq!(frame.children.len(), 2);
assert!(frame.children.iter().all(|n| n.name == "Lead rod"));
assert!(imp.bodies.iter().all(|b| b.path == ["Import", "Motion", "Frame", "Lead rod"]));
assert_eq!(imp.bodies[0].source_item, imp.bodies[1].source_item);
let a = measure(&imp.bodies[0].body).unwrap();
let b = measure(&imp.bodies[1].body).unwrap();
assert!(rel(a.volume, 24.0) < 1e-6 && rel(b.volume, 24.0 * scale.powi(3)) < 1e-6);
assert!(a.bbox.min.dist(Vec3::new(10.0, 0.0, 0.0)) < 1e-6 && a.bbox.max.dist(Vec3::new(12.0, 3.0, 4.0)) < 1e-6);
assert!(b.bbox.min.dist(Vec3::new(80.0 - 3.0 * scale, 0.0, 0.0)) < 1e-6);
assert!(b.bbox.max.dist(Vec3::new(80.0, 2.0 * scale, 4.0 * scale)) < 1e-6);
}
}
#[test]
fn invalid_assembly_references_and_counts_fail_before_geometry() {
for (params, message) in [
("0,4HLoop,1,1".into(), "cyclic"),
("0,4HPart,1,999".into(), "missing entity"),
("0,4HPart,-1".into(), "negative IGES group size"),
(format!("0,4HPart,{}", MAX_LIST + 1), "work limit"),
] {
let error = iges_import(&iges_file(&[(308, 0, params)])).unwrap_err();
assert!(matches!(&error, crate::KernelError::Invalid(text) if text.contains(message)), "{error}");
}
let mut chain = Vec::new();
for k in 0..=MAX_DEPTH {
chain.push((308, 0, if k == MAX_DEPTH { "0,4HPart,0".into() } else { format!("0,4HPart,1,{}", 2 * k + 3) }));
}
let error = iges_import(&iges_file(&chain)).unwrap_err();
assert!(matches!(&error, crate::KernelError::Invalid(text) if text.contains("nesting is too deep")), "{error}");
let members = "1,".repeat(100_000);
let many = [(308, 0, "0,4HPart,0".into()), (308, 0, format!("1,5HFrame,100001,{members}1"))];
let error = iges_import(&iges_file(&many)).unwrap_err();
assert!(matches!(&error, crate::KernelError::Invalid(text) if text.contains("too many IGES assembly placements")), "{error}");
}
/// Six trimmed bilinear patches with line boundaries, forming a 10 × 20 × 30 box.
fn trimmed_box(ents: &mut Vec<(i64, i64, String)>, x: f64) -> Vec<usize> {
let c = |i: usize| -> [f64; 3] {
[x + if i & 1 != 0 { 10.0 } else { 0.0 }, if i & 2 != 0 { 20.0 } else { 0.0 }, if i & 4 != 0 { 30.0 } else { 0.0 }]
};
// Faces as corner quads (counter-clockwise seen from outside).
let quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]];
let mut ents: Vec<(i64, i64, String)> = Vec::new();
let mut faces = Vec::new();
let fmt = |p: [f64; 3]| format!("{:?},{:?},{:?}", p[0], p[1], p[2]);
for q in quads {
let (a, b, cc, d) = (c(q[0]), c(q[1]), c(q[2]), c(q[3]));
@@ -182,7 +283,15 @@ fn trimmed_surfaces_sew_into_a_solid() {
ents.push((142, 0, format!("0,{s_de},0,{comp},2")));
let cos = 2 * ents.len() - 1;
ents.push((144, 0, format!("{s_de},1,0,{cos}")));
faces.push(2 * ents.len() - 1);
}
faces
}
#[test]
fn trimmed_surfaces_sew_into_a_solid() {
let mut ents = Vec::new();
trimmed_box(&mut ents, 0.0);
let imp = iges_import(&iges_file(&ents)).unwrap();
assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);
assert!(imp.bodies[0].closed);
@@ -190,6 +299,25 @@ fn trimmed_surfaces_sew_into_a_solid() {
assert!(rel(m.volume, 6000.0) < 1e-6 && rel(m.area, 2200.0) < 1e-6, "{} {}", m.volume, m.area);
}
#[test]
fn surfaces_in_separate_groups_remain_separate_parts() {
let mut ents = Vec::new();
for (name, x) in [("Left", 0.0), ("Right", 100.0)] {
let faces = trimmed_box(&mut ents, x);
let members = faces.iter().map(|s| s.to_string()).collect::<Vec<_>>().join(",");
ents.push((308, 0, format!("0,{}H{name},{},{members}", name.len(), faces.len())));
}
let imp = iges_import(&iges_file(&ents)).unwrap();
assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);
assert_eq!(imp.bodies.len(), 2);
assert_eq!(imp.tree[0].children.iter().map(|n| n.name.as_str()).collect::<Vec<_>>(), ["Left", "Right"]);
for (body, x) in imp.bodies.iter().zip([0.0, 100.0]) {
let m = measure(&body.body).unwrap();
assert!(body.closed && rel(m.volume, 6000.0) < 1e-6 && rel(m.area, 2200.0) < 1e-6);
assert!(m.bbox.min.dist(Vec3::new(x, 0.0, 0.0)) < 1e-6 && m.bbox.max.dist(Vec3::new(x + 10.0, 20.0, 30.0)) < 1e-6);
}
}
#[test]
fn a_drill_point_round_trips_through_iges() {
// A blind hole with a cone tip: the tip's face closes at its apex (its seam runs out to the
+1 -1
View File
@@ -101,7 +101,7 @@ pub(crate) fn point(cx: &Ctx, id: u64) -> R<mt::Point3> {
Ok(mt::Point3::new(g(0)?, g(1)?, g(2)?) * cx.len)
}
fn direction(cx: &Ctx, id: u64) -> R<mt::Vector3> {
pub(super) fn direction(cx: &Ctx, id: u64) -> R<mt::Vector3> {
let e = entity(cx, id)?;
if e.name() != "DIRECTION" {
return Err(format!("#{id}: expected DIRECTION, found {}", e.name()));
+31 -2
View File
@@ -562,10 +562,39 @@ impl Reader {
fn placement_matrix(&mut self, item: u64, u: Units) -> R<mt::Matrix4> {
let cx = Ctx { ex: &self.ex, len: u.len, ang: u.ang, tol: u.tol };
let e = geom::entity(&cx, item)?;
if e.name() == "CARTESIAN_TRANSFORMATION_OPERATOR_3D" {
if matches!(e.name(), "CARTESIAN_TRANSFORMATION_OPERATOR_3D" | "CARTESIAN_TRANSFORMATION_OPERATOR_3D_NON_UNIFORM") {
let p = e.params();
let o = geom::point(&cx, p.get(4).and_then(Param::as_ref_id).ok_or("transformation without origin")?)?;
return Ok(mt::Matrix4::from_translation(o.to_homogeneous().truncate()));
let direction = |i: usize, fallback: mt::Vector3| -> R<mt::Vector3> {
match p.get(i) {
None | Some(Param::Null) => Ok(fallback),
Some(Param::Ref(id)) => geom::direction(&cx, *id),
_ => Err("invalid transformation direction".into()),
}
};
let scale = |i: usize, fallback: f64| -> R<f64> {
match p.get(i) {
None | Some(Param::Null) => Ok(fallback),
Some(v) => v.as_f64().filter(|x| x.is_finite() && *x != 0.0).ok_or_else(|| "invalid transformation scale".into()),
}
};
let sx = scale(5, 1.0)?;
let (sy, sz) = (scale(7, sx)?, scale(8, sx)?);
let m = mt::Matrix4::from_cols(
(direction(2, mt::Vector3::unit_x())? * sx).extend(0.0),
(direction(3, mt::Vector3::unit_y())? * sy).extend(0.0),
(direction(6, mt::Vector3::unit_z())? * sz).extend(0.0),
o.to_homogeneous(),
);
if !to_array(&m).iter().flatten().all(|x| x.is_finite()) {
return Err("invalid transformation scale".into());
}
use mt::SquareMatrix as _;
let det = m.determinant();
if !det.is_finite() || det == 0.0 {
return Err("singular transformation".into());
}
return Ok(m);
}
Ok(geom::frame(&cx, item)?.matrix())
}
+1 -1
View File
@@ -278,7 +278,7 @@ pub fn tool_definitions() -> Vec<Value> {
json!({
"path": string("Path to a .solidcraft, .step/.stp, .3mf, .stl, .obj, .glb or .gltf file"),
"up": {"type": "string", "enum": ["z", "y"], "description": "STEP and glTF only. z keeps the file's axes; y: the file has Y up, so its bodies are turned to stand Z up. Default: z for STEP, y for glTF"},
"names": {"type": "string", "enum": ["solid", "product", "instance"], "description": "STEP only. What the bodies are named after: solid (default: the solid's own name, else the product's), product (the part's name) or instance (the assembly occurrence's name, else the product's)"},
"names": {"type": "string", "enum": ["auto", "solid", "product", "instance"], "description": "STEP, IGES, FreeCAD and Rhino. auto (default): keep meaningful solid names, replace placeholders with the nearest named product, else instance; solid: the solid's own name; product: the part's name; instance: the occurrence's name, else the product's"},
}),
&["path"],
),
+4 -4
View File
@@ -10,7 +10,7 @@ SolidCraft reads STEP (ISO 10303-21; AP203, AP214 and AP242 geometry) with its o
Every import (STEP, IGES, 3MF, STL, OBJ; inserted, dropped, opened as a new design, or run as `file.insert_step`, `file.insert_mesh` or `doc.open` from a script, the CLI or MCP) becomes a **new component named after the file** (`bracket.step` → component `bracket`), placed in the active component at the file's origin. The Import feature belongs to it, so the file's bodies never land loose next to your own. Opening a file as a design makes the component too, so the browser shows the file's name. The command's reply reports it: `component` (id), `component_name` and `occurrence`.
A STEP **assembly** keeps its structure: each product under the file's root becomes a component nested under the import's, named after the product, at the place the file gives it. A part (or sub-assembly) the file places more than once becomes **one component with an occurrence per placement**: the Import feature builds the part once and skips the file's later copies (`skip` in the feature, format 22), and the occurrences show it everywhere else. The reply adds `subcomponents` (how many components were made below the import's) and `rigid_joints`.
A STEP **assembly** keeps its structure: each product under the file's root becomes a component nested under the import's, named after the product, at the place the file gives it. IGES groups and subfigures become nested components the same way. A part (or sub-assembly) the file places more than once becomes **one component with an occurrence per placement**: the Import feature builds the part once and skips the file's later copies (`skip` in the feature, format 22), and the occurrences show it everywhere else. Placements that are scaled, mirrored or otherwise non-rigid keep their geometry in place in the parent component. The reply adds `subcomponents` (how many components were made below the import's) and `rigid_joints`.
The Browser reuses body, sketch and construction-plane membership, child lists and resolved placements while the
camera moves. Large assemblies keep their tree open without resolving every part and
@@ -34,7 +34,7 @@ The contents of an imported assembly are **rigid by default**: rigid joints (a r
Designs saved before imports made components keep their Import where it is (no component is made for it) and rebuild as they did.
Read: manifold solid breps (with voids), faceted breps, shell-based surface models; planes, cylinders, cones, spheres, tori, B-spline and rational B-spline surfaces (with knots, Bézier, uniform, quasi-uniform), surfaces of revolution and linear extrusion, trimmed surfaces; lines, circles, ellipses, hyperbolas and parabolas (as exact rational curves, which export writes back as exact rational B-splines), B-spline curves, polylines, trimmed/surface/seam curves; length and angle units (SI prefixes, conversion-based units such as inches); product names (body names come from the solid's name, else the product's; `names` below chooses); surface colours; assemblies (next-assembly-usage occurrences placed by item-defined transformations, and mapped items) — the product tree is kept in the feature and becomes the import's components (above). Files are untrusted: sizes, entity counts and nesting are capped and every kernel call is guarded. What cannot be read becomes a warning on the feature (a face left out gives an open body); not read yet: offset surfaces, pcurve-only edges.
Read: manifold solid breps (with voids), faceted breps, shell-based surface models; planes, cylinders, cones, spheres, tori, B-spline and rational B-spline surfaces (with knots, Bézier, uniform, quasi-uniform), surfaces of revolution and linear extrusion, trimmed surfaces; lines, circles, ellipses, hyperbolas and parabolas (as exact rational curves, which export writes back as exact rational B-splines), B-spline curves, polylines, trimmed/surface/seam curves; length and angle units (SI prefixes, conversion-based units such as inches); product names (meaningful solid names are kept, placeholders use part names; `names` below chooses); surface colours; assemblies (next-assembly-usage occurrences placed by item-defined transformations, and mapped items) — the product tree is kept in the feature and becomes the import's components (above). Files are untrusted: sizes, entity counts and nesting are capped and every kernel call is guarded. What cannot be read becomes a warning on the feature (a face left out gives an open body); not read yet: offset surfaces, pcurve-only edges.
Extruded circular and elliptical faces keep their profile's parameter seam outside
the face trim, or on an explicit seam edge. Narrow faces such as rounded gear tooth
@@ -46,7 +46,7 @@ the supporting ellipse in the middle.
Files from different systems differ in which way is up and in what they call their solids. `doc.open`, `file.insert_step` and the MCP `open` tool take two options for STEP and IGES files; without them a file comes in as written.
- **`up`**: `"z"` (the default) keeps the file's axes. Many systems write Y up, so such a part lies on its back in SolidCraft's Z-up space. `"up": "y"` turns the import's component a quarter turn about X (+90°: Y becomes Z), as the window's "Stand it up" offer does, so an assembly's parts and instances turn together. The import and the turn are one undo step, the reply names the turned occurrence as `stand_up`, and only the file's component turns, not what is already in the design. The window offers to stand a part up after a STEP file opens unless the call said which way is up (`up: "z"` as well as `"y"`).
- **`names`**: what the bodies are called. `"solid"` (the default) is the name of the solid in the file, and the product's name where the solid has none. Some systems fill a solid's name with the last feature that made it (`Cut-Extrude3`), so every body of an assembly has a name that says nothing about its part. `"product"` names each body after the product (the part) that holds it, and `"instance"` after the assembly occurrence (`Post-2`), or the product where the body is not in an occurrence. A name the file leaves out, or fills with a placeholder, falls back to the next one (instance, product, solid). Repeated names are numbered as any body names are (`Post`, `Post (2)`). The names are stored with the Import feature, so the design reopens with them. The default stays the solid's name because SolidCraft's own STEP export writes a body's name there.
- **`names`**: `"auto"` (the default) keeps meaningful solid names and replaces placeholders such as `Body1` or `Body 2 (3)` with the nearest named product, then the occurrence name if no product is named. `"solid"` keeps the solid's name; `"product"` chooses the part's name; `"instance"` chooses the assembly occurrence (`Post-2`), falling back to the product. If the chosen name is missing, the solid's name remains. Repeated names are numbered (`Post`, `Post (2)`). Names are stored with the Import feature and survive reopening the design. Files without names or assembly metadata retain generated body names and a flat structure.
```json
{"command": "file.insert_step", "params": {"path": "frame.step", "up": "y", "names": "instance"}}
@@ -61,7 +61,7 @@ display on the resulting body.
## IGES
IGES 5.3 files (`.igs`/`.iges`) open, insert and drop the same way: `crates/kernel/src/iges_in.rs` (written from the published specification) restates the file as STEP and the STEP reader reads it, so the feature holds STEP text. Read: manifold solid B-reps (186) with their shells, faces, loops, edge and vertex lists; trimmed (144) and bounded (143) surfaces, and bare B-spline patches, sewn into a solid by their shared edges (an open body when they do not close); lines, circular arcs, ellipses, composite curves, rational B-spline curves; planes (108, 190), cylinders, cones, spheres, tori, rational B-spline surfaces, surfaces of revolution and tabulated cylinders; transformation matrices; units; colours (314 and the predefined numbers); body names (name properties, else labels). Not read yet: ruled and offset surfaces, curves on surfaces given only in parameter space. Export (`file.export` to `.igs`) writes each body as a manifold solid B-rep on the same surfaces a STEP export uses, with its name and colour.
IGES 5.3 files (`.igs`/`.iges`) open, insert and drop the same way: `crates/kernel/src/iges_in.rs` (written from the published specification) restates the file as STEP and the STEP reader reads it, so the feature holds STEP text. Read: manifold solid B-reps (186) with their shells, faces, loops, edge and vertex lists; trimmed (144) and bounded (143) surfaces, and bare B-spline patches, sewn within their owning group into a solid by their shared edges (an open body when they do not close); groups (402 forms 1, 7, 14 and 15), subfigure definitions (308) and instances (408), retaining names, nesting and placements; lines, circular arcs, ellipses, composite curves, rational B-spline curves; planes (108, 190), cylinders, cones, spheres, tori, rational B-spline surfaces, surfaces of revolution and tabulated cylinders; transformation matrices; units; colours (314 and the predefined numbers); body names (name properties, else labels). Not read yet: ruled and offset surfaces, curves on surfaces given only in parameter space. Export (`file.export` to `.igs`) writes each body as a manifold solid B-rep on the same surfaces a STEP export uses, with its name and colour.
## FreeCAD and Rhino