Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Extract a component whose body was built in another component (#12153)

SS-EN0b32d3619de9
diff --git a/crates/engine/src/cmd/component_extract.rs b/crates/engine/src/cmd/component_extract.rs
index 2ac92d4c3d..8b63dbd924 100644
--- a/crates/engine/src/cmd/component_extract.rs
+++ b/crates/engine/src/cmd/component_extract.rs
@@ -7,8 +7,10 @@
//! come along, all keeping their ids and names, with the parameters they use. It is evaluated on
//! its own and has to build the bodies the component has here. Then the component's history is
//! replaced by an Import feature of those bodies, linked to the file, and this design has to look
-//! as it did before. Anything that crosses the component's boundary (a feature outside that uses
-//! its sketches, bodies moved in or out, a joint to one of its subcomponents) is refused.
+//! as it did before. A body of the component that a feature outside it built (a mirror or
+//! pattern into it, a body moved in) takes that history along when nothing else outside depends
+//! on it. Anything else that crosses the component's boundary (a feature outside that uses its
+//! sketches, bodies moved out, a joint to one of its subcomponents) is refused.
use solidcraft_geom::prelude::*;
use std::collections::{BTreeMap, BTreeSet};
@@ -205,8 +207,13 @@ struct Scope {
own: BTreeSet<u64>,
/// The placements of its subcomponents.
inner: BTreeSet<u64>,
- /// Its features and its subcomponents'.
+ /// Its features and its subcomponents', and the features outside that built its bodies: they
+ /// all leave this design.
inside: BTreeSet<u64>,
+ /// Sketches outside that those features use: copied to the new design, kept here.
+ carried: BTreeSet<u64>,
+ /// The features outside that built its bodies.
+ pulled: BTreeSet<u64>,
/// Its bodies and its subcomponents'.
bodies: BTreeSet<String>,
/// The component of every body of the design.
@@ -216,6 +223,74 @@ struct Scope {
occurrences: BTreeMap<u64, u64>,
}
+/// The bodies `after` has that `before` did not have the same, and those it lost: what a feature
+/// built, changed, moved to another component or used up.
+fn touched(doc: &Document, before: &ModelState, after: &ModelState) -> BTreeSet<String> {
+ let mut out: BTreeSet<String> = before.bodies.iter().filter(|b| after.body(&b.name).is_none()).map(|b| b.name.clone()).collect();
+ for b in &after.bodies {
+ let same = before.body(&b.name).is_some_and(|old| old.body.same(&b.body) && doc.model_body_component(old) == doc.model_body_component(b));
+ if !same {
+ out.insert(b.name.clone());
+ }
+ }
+ out
+}
+
+/// The features outside a component (`inside` are its own) that built, changed or moved in
+/// `wanted`, its bodies built outside it, back to where they started; or the feature that also
+/// builds or changes a body that stays outside, which keeps the history from going along.
+fn history_from_outside(
+ s: &Session,
+ inside: &BTreeSet<u64>,
+ mut wanted: BTreeSet<String>,
+ owned: &dyn Fn(&str) -> bool,
+ name: &str,
+ cmd: &str,
+) -> Result<BTreeSet<u64>> {
+ let empty = ModelState::default();
+ let mut steps: Vec<(&solidcraft_doc::Feature, BTreeSet<String>)> = Vec::new();
+ let mut before: &ModelState = &empty;
+ for f in &s.doc.features {
+ let Some(r) = s.model.result(f.id) else { continue };
+ steps.push((f, touched(&s.doc, before, &r.state)));
+ before = &r.state;
+ }
+ let state = s.model.state();
+ let mut pulled = BTreeSet::new();
+ for (f, t) in steps.iter().rev() {
+ if !t.iter().any(|b| wanted.contains(b)) {
+ continue;
+ }
+ if inside.contains(&f.id) {
+ // Already going; a body it used up from outside is checked where that was built
+ wanted.extend(t.iter().filter(|b| state.body(b).is_none()).cloned());
+ continue;
+ }
+ if let Some(other) = t.iter().find(|b| state.body(b).is_some() && !owned(b)) {
+ let mine = t.iter().find(|b| wanted.contains(*b)).cloned().unwrap_or_default();
+ return Err(bad(cmd, format!("{} builds body {mine} of {name} and also body {other} outside it, so it can't go with {name}", f.name)));
+ }
+ pulled.insert(f.id);
+ wanted.extend(t.iter().cloned());
+ }
+ Ok(pulled)
+}
+
+/// The last feature that put body `body` in another component.
+fn mover(s: &Session, body: &str) -> Option<String> {
+ let mut found = None;
+ let mut was = None;
+ for f in &s.doc.features {
+ let Some(r) = s.model.result(f.id) else { continue };
+ let now = r.state.body(body).map(|b| s.doc.model_body_component(b));
+ if was.is_some() && now.is_some() && now != was {
+ found = Some(f.name.clone());
+ }
+ was = now.or(was);
+ }
+ found
+}
+
/// What goes with component `comp`, or why it can't go on its own.
fn scope(s: &Session, comp: u64, cmd: &str) -> Result<Scope> {
let source = &s.doc;
@@ -239,7 +314,21 @@ fn scope(s: &Session, comp: u64, cmd: &str) -> Result<Scope> {
if let Some(o) = source.occurrences.iter().find(|o| children.contains(&o.component) && !subtree.contains(&o.parent)) {
return Err(bad(cmd, format!("{} is placed outside {name} too", o.name)));
}
- let inside: BTreeSet<u64> = source.features.iter().filter(|f| subtree.contains(&f.component)).map(|f| f.id).collect();
+ let mut inside: BTreeSet<u64> = source.features.iter().filter(|f| subtree.contains(&f.component)).map(|f| f.id).collect();
+ let state = s.model.state();
+ let owners: BTreeMap<String, u64> = state.bodies.iter().map(|b| (b.name.clone(), source.model_body_component(b))).collect();
+ let owned = |b: &str| owners.get(b).is_some_and(|c| subtree.contains(c));
+ let built_outside: BTreeSet<String> =
+ state.bodies.iter().filter(|b| owned(&b.name) && !inside.contains(&b.feature)).map(|b| b.name.clone()).collect();
+ let pulled = if built_outside.is_empty() { BTreeSet::new() } else { history_from_outside(s, &inside, built_outside, &owned, &name, cmd)? };
+ inside.extend(pulled.iter().copied());
+ let mut carried = BTreeSet::new();
+ let mut todo: Vec<u64> = pulled.iter().flat_map(|id| source.feature(*id).map(|f| f.kind.input_sketches()).unwrap_or_default()).collect();
+ while let Some(id) = todo.pop() {
+ if !inside.contains(&id) && carried.insert(id) {
+ todo.extend(source.feature(id).map(|f| f.kind.input_sketches()).unwrap_or_default());
+ }
+ }
if let Some(f) = source.features.iter().find(|f| inside.contains(&f.id) && s.model.result(f.id).is_some_and(|r| r.error.is_some())) {
return Err(bad(cmd, format!("{} fails; fix it first", f.name)));
}
@@ -249,9 +338,10 @@ fn scope(s: &Session, comp: u64, cmd: &str) -> Result<Scope> {
if let Some(f) = source
.features
.iter()
- .find(|f| matches!(&f.kind, FeatureKind::BodyTransfer { from, to, .. } if subtree.contains(from) != subtree.contains(to)))
+ // Bodies moved in are checked below: they go when what built them goes too
+ .find(|f| matches!(&f.kind, FeatureKind::BodyTransfer { from, to, .. } if subtree.contains(from) && !subtree.contains(to)))
{
- return Err(bad(cmd, format!("{} moves bodies into or out of {name}", f.name)));
+ return Err(bad(cmd, format!("{} moves bodies out of {name}", f.name)));
}
let mut occurrences: BTreeMap<u64, u64> = inner.iter().map(|o| (*o, *o)).collect();
if let [single] = own.iter().copied().collect::<Vec<_>>().as_slice() {
@@ -263,13 +353,17 @@ fn scope(s: &Session, comp: u64, cmd: &str) -> Result<Scope> {
}) {
return Err(bad(cmd, format!("joint {} connects a part of {name} to the rest of the design", j.name)));
}
- let state = s.model.state();
- let owners: BTreeMap<String, u64> = state.bodies.iter().map(|b| (b.name.clone(), source.model_body_component(b))).collect();
let mut bodies = BTreeSet::new();
for b in &state.bodies {
- let owned = owners.get(&b.name).is_some_and(|c| subtree.contains(c));
+ let owned = owned(&b.name);
if owned != inside.contains(&b.feature) {
- return Err(bad(cmd, format!("body {} was moved into or out of {name}", b.name)));
+ return Err(bad(
+ cmd,
+ match mover(s, &b.name) {
+ Some(f) => format!("{f} moves body {} out of {name}", b.name),
+ None => format!("body {} was moved into or out of {name}", b.name),
+ },
+ ));
}
if owned && b.body.is_mesh() {
return Err(bad(cmd, format!("mesh body {} can't be linked", b.name)));
@@ -278,7 +372,7 @@ fn scope(s: &Session, comp: u64, cmd: &str) -> Result<Scope> {
bodies.insert(b.name.clone());
}
}
- Ok(Scope { comp, name, subtree, children, own, inner, inside, bodies, owners, occurrences })
+ Ok(Scope { comp, name, subtree, children, own, inner, inside, carried, pulled, bodies, owners, occurrences })
}
/// The design `sc` makes on its own, called `stem`, evaluated and checked to build the bodies it
@@ -286,11 +380,12 @@ fn scope(s: &Session, comp: u64, cmd: &str) -> Result<Scope> {
fn part_design(s: &Session, sc: &Scope, stem: &str, cmd: &str) -> Result<(Session, Vec<String>)> {
let source = &s.doc;
let (comp, name, bodies) = (sc.comp, &sc.name, &sc.bodies);
- let to_root = |c: u64| if c == comp { 0 } else { c };
+ // Features from outside that built its bodies come along at the new design's root
+ let to_root = |c: u64| if c == comp || !sc.subtree.contains(&c) { 0 } else { c };
let mut part = (**source).clone();
part.name = stem.to_string();
part.marker = None;
- part.features.retain(|f| sc.inside.contains(&f.id));
+ part.features.retain(|f| sc.inside.contains(&f.id) || sc.carried.contains(&f.id));
for f in &mut part.features {
f.component = to_root(f.component);
// Bodies numbered or suffixed after the other bodies here (Body2, `X (2)`) keep those
@@ -306,6 +401,11 @@ fn part_design(s: &Session, sc: &Scope, stem: &str, cmd: &str) -> Result<(Sessio
*from = to_root(*from);
*to = to_root(*to);
}
+ FeatureKind::Mirror { placements, .. } => {
+ for path in placements {
+ local_path(path, &sc.own);
+ }
+ }
FeatureKind::Emboss { face: Some(face), .. } => {
local_path(&mut face.path, &sc.own);
local_path(&mut face.author_path, &sc.own);
@@ -320,6 +420,8 @@ fn part_design(s: &Session, sc: &Scope, stem: &str, cmd: &str) -> Result<(Sessio
_ => {}
}
}
+ // A body moved in from outside is already at the root
+ part.features.retain(|f| !matches!(f.kind, FeatureKind::BodyTransfer { from: 0, to: 0, .. }));
part.components.retain(|c| sc.children.contains(&c.id));
for c in &mut part.components {
c.parent = to_root(c.parent);
@@ -361,7 +463,7 @@ fn part_design(s: &Session, sc: &Scope, stem: &str, cmd: &str) -> Result<(Sessio
part.named_views.clear();
part.configs = Default::default();
part.assembly = Default::default();
- let features: BTreeMap<u64, u64> = sc.inside.iter().map(|f| (*f, *f)).collect();
+ let features: BTreeMap<u64, u64> = sc.inside.iter().chain(&sc.carried).map(|f| (*f, *f)).collect();
let body_map: BTreeMap<String, String> = bodies.iter().map(|b| (b.clone(), b.clone())).collect();
// Joints from the component to the rest of the design stay here, so they are not copied
let mut scope = Document { assembly: source.assembly.clone(), ..Document::default() };
@@ -397,6 +499,9 @@ fn part_design(s: &Session, sc: &Scope, stem: &str, cmd: &str) -> Result<(Sessio
return Err(bad(cmd, format!("{name} does not build body {b} on its own")));
};
if !same_shape(was, source.model_body_offset(was).unwrap_or(&identity), now, part.doc.model_body_offset(now).unwrap_or(&identity))? {
+ if let Some(f) = source.feature(was.feature).filter(|f| sc.pulled.contains(&f.id)) {
+ return Err(bad(cmd, format!("body {b} comes out differently on its own: {} builds it from outside {name}", f.name)));
+ }
return Err(bad(cmd, format!("body {b} comes out differently on its own: something outside {name} changes it")));
}
}
@@ -979,6 +1084,54 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
+ #[test]
+ fn a_body_built_outside_and_moved_in_goes_with_its_history() {
+ // #12142: a part modelled in context, then moved into its component
+ let dir = folder("moved-in");
+ let mut s = Session::default();
+ let plate = run(&mut s, "component.create", json!({"name": "Plate"}))["component"].as_u64().unwrap();
+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Own"}));
+ run(&mut s, "component.activate", json!({"component": 0}));
+ run(&mut s, "solid.box", json!({"length": 20, "width": 8, "height": 4, "corner": [30, 0, 0], "body_name": "Block"}));
+ run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [-30, 0, 0], "body_name": "Stays"}));
+ run(&mut s, "component.move_bodies", json!({"bodies": ["Block"], "component": plate}));
+ let vol = volumes(&s);
+ let file = dir.join("plate.solidcraft");
+ let out = run(&mut s, "component.extract", json!({"component": "Plate", "path": file}));
+ assert_eq!(out["bodies"], json!(["Block", "Own"]), "{out}");
+ assert_eq!(volumes(&s), vol);
+ assert!(s.model.results.iter().all(|r| r.error.is_none()));
+ let mut part = Session::default();
+ run(&mut part, "doc.open", json!({"path": file}));
+ assert!(part.model.results.iter().all(|r| r.error.is_none()));
+ assert_eq!(volumes(&part).keys().collect::<Vec<_>>(), ["Block", "Own"]);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn a_body_built_with_one_that_stays_outside_names_the_feature() {
+ let dir = folder("built-with");
+ let mut s = Session::default();
+ let plate = run(&mut s, "component.create", json!({"name": "Plate"}))["component"].as_u64().unwrap();
+ run(&mut s, "component.activate", json!({"component": 0}));
+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A"}));
+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [0, 0, 20], "body_name": "B"}));
+ // One cut changes both bodies, and only B goes into Plate
+ run(
+ &mut s,
+ "solid.cylinder",
+ json!({"radius": 2, "height": 50, "base": [5, 5, -5], "operation": "cut", "targets": ["A", "B"], "name": "BothCut"}),
+ );
+ run(&mut s, "component.move_bodies", json!({"bodies": ["B"], "component": plate}));
+ let before = serde_json::to_value(&*s.doc).unwrap();
+ let file = dir.join("plate.solidcraft");
+ let err = s.execute("component.extract", &json!({"component": "Plate", "path": file})).unwrap_err().to_string();
+ assert!(err.contains("BothCut"), "{err}");
+ assert_eq!(serde_json::to_value(&*s.doc).unwrap(), before);
+ assert!(!file.exists());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
#[test]
fn identical_copies_are_found_and_become_placements_of_the_link() {
let dir = folder("copies");
diff --git a/tests/kernel-cases/assemblies/cov-component-extract-moved-in-bodies-refused/expected.json b/tests/kernel-cases/assemblies/cov-component-extract-moved-in-bodies-refused/expected.json
index 053a6763ee..1ab8a39d22 100644
--- a/tests/kernel-cases/assemblies/cov-component-extract-moved-in-bodies-refused/expected.json
+++ b/tests/kernel-cases/assemblies/cov-component-extract-moved-in-bodies-refused/expected.json
@@ -2,7 +2,17 @@
"sources": [],
"what": "component.extract of a component whose body was moved in from the root",
"source": "analytic",
- "method": "Base: box 20x20x10 from (-10,-10,-10), grounded; Arm: box 40x10x10 from (0,-5,0), centre (20,0,5); Arm's body came in by component.move_bodies, a feature outside it: its history can't move to a design of its own, so extract is refused",
- "outcome": "refused",
- "refusal": "moves bodies into or out of Arm"
+ "method": "Base: box 20x20x10 from (-10,-10,-10), grounded: 4000 mm3; Arm: box 40x10x10 from (0,-5,0), centre (20,0,5): 4000 mm3; Arm's body came in by component.move_bodies, a feature outside it that touches nothing else outside: since #12142 that history goes with Arm to its own design (the folder name keeps the case's id from when it was refused), so extract succeeds with ArmBox and the design keeps both bodies where they were: 8000 mm3",
+ "body_count": 2,
+ "volume_mm3": 8000.0,
+ "results": [
+ {
+ "step": 8,
+ "json": {
+ "bodies": [
+ "ArmBox"
+ ]
+ }
+ }
+ ]
}