Skip to content

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

solid.mirror: copies join their source's component; follow the saved placement (#1938)

NOWN-DEV50313d147f8b
diff --git a/crates/doc/src/assembly.rs b/crates/doc/src/assembly.rs
index c09a77258b..93a557ca5e 100644
--- a/crates/doc/src/assembly.rs
+++ b/crates/doc/src/assembly.rs
@@ -244,9 +244,9 @@ impl Document {
m
}
- /// World transform of one placement of `component`: the occurrence `path` from the root
- /// (empty for the root itself). `None` when the path no longer leads to that component.
- pub fn path_transform(&self, component: u64, path: &[u64]) -> Option<Mat> {
+ /// One placement: the component the occurrence `path` from the root leads to (the root for
+ /// an empty path) and its world transform. `None` when the path no longer exists.
+ pub fn path_placement(&self, path: &[u64]) -> Option<(u64, Mat)> {
if path.len() > MAX_PLACEMENT_DEPTH + 1 {
return None;
}
@@ -256,7 +256,7 @@ impl Document {
m = mat_mul(&m, &o.transform);
c = o.component;
}
- (c == component).then_some(m)
+ Some((c, m))
}
/// Every placement of each component: (component, occurrence path ids, world transform).
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index 742b0bf6f9..ef77f1f524 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -685,8 +685,10 @@ pub enum FeatureKind {
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
combine: bool,
/// Where each of `bodies` is mirrored from: the occurrence path of the placement it was
- /// picked at. The body is mirrored where that placement shows it, as the feature's own
- /// component sees it. Empty in older designs, which mirror the bodies' own geometry.
+ /// picked at. The body is mirrored where that placement shows it, in the plane of the
+ /// feature's own component, and its copy joins the body's component (or, when that is
+ /// placed more than once, the innermost component around it placed once). Empty in older
+ /// designs, which mirror the bodies' own geometry.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
placements: Vec<Vec<u64>>,
},
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index f673c785f4..4927c55204 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -1284,14 +1284,31 @@ fn placement_digest(doc: &Document, f: &Feature) -> u64 {
FeatureKind::Revolve { to, .. } => to.is_some(),
_ => false,
};
- // A mirror of placed bodies follows where they are placed.
- let placed_mirror = matches!(&f.kind, FeatureKind::Mirror { placements, .. } if !placements.is_empty());
+ // A mirror of placed bodies follows the placements it was picked at and its own component's
+ // frame, not every occurrence: moving an unrelated one leaves it (and its cache) alone.
+ if let FeatureKind::Mirror { placements, bodies, .. } = &f.kind
+ && !placements.is_empty()
+ {
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ doc.component_transform(f.component).iter().flatten().for_each(|x| x.to_bits().hash(&mut h));
+ for placed in placements.iter().map(|path| mirror_copy_frame(doc, path)) {
+ placed.is_some().hash(&mut h);
+ if let Some((component, frame, picked)) = placed {
+ component.hash(&mut h);
+ frame.iter().chain(&picked).flatten().for_each(|x| x.to_bits().hash(&mut h));
+ }
+ }
+ for b in bodies {
+ serde_json::to_string(&doc.body_offsets.get(&b.0)).unwrap_or_default().hash(&mut h);
+ }
+ return h.finish();
+ }
// A combine moves tools placed differently from its target into the target's frame (#3383).
let combine = matches!(&f.kind, FeatureKind::Combine { .. });
if !to_object && !combine && drawn_tools_change_bodies(&f.kind) {
return drawn_tools_digest(doc, f);
}
- if to_object || placed_mirror || combine {
+ if to_object || combine {
return if doc.occurrences.is_empty() && doc.body_offsets.is_empty() { 0 } else { placements_hash(doc) };
}
let FeatureKind::Sketch { plane, sketch } = &f.kind else { return 0 };
@@ -4745,18 +4762,69 @@ fn mirror_matrix(pl: &Plane) -> Mat {
const MAX_INSTANCES: usize = 1000;
-/// Where a mirrored body is, in the frame of the mirror's component: through the placement it
-/// was picked at and the feature's component frame. `None` when that is the body's own frame
-/// (and in older designs, which saved no placement).
-fn mirrored_placement(doc: &Document, f: &Feature, mb: &ModelBody, path: Option<&[u64]>) -> Result<Option<Mat>> {
+/// Where a mirrored body was picked and where its copy goes: the component the copy joins and
+/// that component's world frame, and the frame the body's own geometry is in where it was picked
+/// (its placement `path`, with its offset). `None` in older designs, which saved no placement and
+/// mirror the body's own geometry.
+fn mirrored_placement(doc: &Document, mb: &ModelBody, path: Option<&[u64]>) -> Result<Option<(u64, Mat, Mat)>> {
let Some(path) = path else { return Ok(None) };
- let owner = doc.model_body_component(mb);
let lost = || DocError::Invalid(format!("the placement `{}` was mirrored at no longer exists", mb.name));
- let world = doc.path_transform(owner, path).ok_or_else(lost)?;
- let world = doc.model_body_offset(mb).map(|offset| crate::mat_mul(&world, offset)).unwrap_or(world);
- let inverse = crate::mat_inverse(&doc.component_transform(f.component)).ok_or_else(lost)?;
- let rel = crate::mat_mul(&inverse, &world);
- Ok((!crate::is_identity(&rel)).then_some(rel))
+ // A stale or edited path that leads to another component no longer shows the body.
+ let (at, _) = doc.path_placement(path).ok_or_else(lost)?;
+ if !placement_shows(doc, mb, at) {
+ return Err(lost());
+ }
+ let (component, frame, picked) = mirror_copy_frame(doc, path).ok_or_else(lost)?;
+ let source = doc.model_body_offset(mb).map(|offset| crate::mat_mul(&picked, offset)).unwrap_or(picked);
+ Ok(Some((component, frame, source)))
+}
+
+/// Whether a placement of component `at` shows body `mb`: `at` is the body's component. That is
+/// the evaluated body's own where a transfer recorded it, else the component its name is recorded
+/// in (an import's bodies) or its feature's. Inserting the same file again reuses the body names
+/// and points them at the new insert's components: when the recorded component lies outside the
+/// components the body's own feature made, the name is another body's, and the placement only has
+/// to lie inside the components the body's feature made.
+fn placement_shows(doc: &Document, mb: &ModelBody, at: u64) -> bool {
+ let owner = doc.model_body_component(mb);
+ if owner == at {
+ return true;
+ }
+ if mb.transferred || mb.source_name.is_some() {
+ return false;
+ }
+ let made_in = doc.feature(mb.feature).map(|f| f.component).unwrap_or(0);
+ !component_within(doc, owner, made_in) && component_within(doc, at, made_in)
+}
+
+/// Whether component `c` is `ancestor` or lies inside it (every component lies in the root).
+fn component_within(doc: &Document, mut c: u64, ancestor: u64) -> bool {
+ for _ in 0..=doc.components.len() {
+ if c == ancestor || ancestor == 0 {
+ return true;
+ }
+ match doc.components.iter().find(|x| x.id == c) {
+ Some(x) if c != 0 => c = x.parent,
+ _ => return false,
+ }
+ }
+ false
+}
+
+/// For a body mirrored at placement `path` (which, not the body's name, says where it is: a later
+/// insert can reuse the name): the component its copy joins, that component's world frame, and
+/// the placement's world frame. The copy joins the body's component, or, when that component is
+/// placed more than once (a copy there would show at every placement), the innermost component
+/// around it that is placed once.
+fn mirror_copy_frame(doc: &Document, path: &[u64]) -> Option<(u64, Mat, Mat)> {
+ let (_, picked) = doc.path_placement(path)?;
+ let placed_once = |id: &u64| {
+ let component = doc.occurrences.iter().find(|o| o.id == *id).map(|o| o.component);
+ doc.occurrences.iter().filter(|o| Some(o.component) == component).count() == 1
+ };
+ let once = path.iter().take_while(|id| placed_once(id)).count();
+ let (component, frame) = doc.path_placement(path.get(..once)?)?;
+ Some((component, frame, picked))
}
/// The placements (column-major matrices) of a pattern's copies, the original excluded.
@@ -5790,16 +5858,18 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
for (k, n) in bodies.iter().enumerate() {
let i = st.bodies.iter().position(|b| &b.name == n).ok_or_else(|| DocError::Unknown(format!("body `{n}`")))?;
let Some(mb) = st.bodies.get(i).cloned() else { continue };
- // A body of a component placed elsewhere is mirrored where it is shown: the copy
- // (in this feature's component) from its placement, a joined body in its own frame.
- let placed = mirrored_placement(doc, f, &mb, placements.get(k).map(Vec::as_slice))?;
- let (copy, own) = match placed {
- Some(rel) => {
- let inverse = crate::mat_inverse(&rel).ok_or_else(|| DocError::Invalid(format!("the placement of `{n}` is singular")))?;
- let copy = crate::mat_mul(&m, &rel);
- (copy, crate::mat_mul(&inverse, &copy))
+ // A body picked where a placement shows it is mirrored there: the copy goes beside
+ // it into the component that placement shows, a joined body stays in its own frame.
+ let (component, copy, own) = match mirrored_placement(doc, &mb, placements.get(k).map(Vec::as_slice))? {
+ Some((component, frame, source)) => {
+ let singular = || DocError::Invalid(format!("the placement `{n}` was mirrored at is singular"));
+ let inverse = |m: &Mat| crate::mat_inverse(m).ok_or_else(singular);
+ // The plane is in this feature's component: the body mirrored in the world.
+ let here = doc.component_transform(f.component);
+ let world = crate::mat_mul(&crate::mat_mul(&here, &m), &crate::mat_mul(&inverse(&here)?, &source));
+ (Some(component), crate::mat_mul(&inverse(&frame)?, &world), crate::mat_mul(&inverse(&source)?, &world))
}
- None => (m, m),
+ None => (None, m, m),
};
let mirrored = moved_copy(&mb, kernel::transform_matrix(&mb.body, if *combine { own } else { copy })?, 1);
if *combine {
@@ -5822,7 +5892,13 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
} else {
let name = copy_body_name(st, f, output, &mb.name);
copy_sheet(st, &mb.name, &name, &copy);
- st.bodies.push(ModelBody::traced_new(name, mirrored, f.id));
+ let mut body = ModelBody::traced_new(name, mirrored, f.id);
+ if let Some(c) = component.filter(|c| *c != f.component) {
+ // Kept in that component as a moved body is (and through later features).
+ body.component = c;
+ body.transferred = true;
+ }
+ st.bodies.push(body);
output += 1;
}
}
diff --git a/crates/doc/src/format/pending/mirror-copies-join-component.rs b/crates/doc/src/format/pending/mirror-copies-join-component.rs
new file mode 100644
index 0000000000..76c092535b
--- /dev/null
+++ b/crates/doc/src/format/pending/mirror-copies-join-component.rs
@@ -0,0 +1,7 @@
+//! A Mirror of bodies with `placements` puts each copy in the component of the body it mirrors
+//! (or, when that component is placed more than once, the innermost component around it placed
+//! once) instead of the Mirror's own component; the copy is mirrored at the same placement as
+//! before. Nothing new is saved and older designs need no transformation: a Mirror without
+//! `placements` mirrors the bodies' own geometry into its own component as before, and one saved
+//! with `placements` by 0.15 puts its copies beside their bodies when it is opened. The last
+//! release asks for an update instead of opening a design in this format.
diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs
index 6664de7892..d441131b67 100644
--- a/crates/engine/src/cmd/features.rs
+++ b/crates/engine/src/cmd/features.rs
@@ -1481,22 +1481,26 @@ fn mirror(s: &mut Session, p: &Value) -> Result<Value> {
/// Bodies picked where the viewport shows them: each world name ("Body1", or "Body1 (Occ:2)"
/// for a further instance) becomes its component's body name, with the occurrence path of the
-/// placement it was picked at. Names stay as they are (and no placement is kept) while every
-/// component is in place, or when one of them is not a body.
+/// placement it was picked at (where the copy goes). Names stay as they are, and no placement is
+/// kept, while every body is in the active component and every component in place, or when one
+/// of them is not a body.
fn placed_bodies(s: &Session, names: Vec<String>, cmd: &str) -> Result<(Vec<String>, Vec<Vec<u64>>)> {
- if names.is_empty() || !crate::frames::placed(s) {
+ if names.is_empty() || s.doc.occurrences.is_empty() {
return Ok((names, Vec::new()));
}
let frames = s.doc.body_frames_with_source(&s.model.state());
let mut picked = Vec::with_capacity(names.len());
for name in &names {
- let Some((_, own, _, path, _)) = frames.iter().find(|(world, ..)| world == name) else { return Ok((names, Vec::new())) };
- if path.iter().any(|id| s.pending_moves.contains_key(id)) {
- return Err(bad(cmd, format!("`{name}` has a position that is not captured yet: Capture Position (component.capture_position) first")));
- }
- picked.push((own.clone(), path.clone()));
+ let Some((_, own, component, path, _)) = frames.iter().find(|(world, ..)| world == name) else { return Ok((names, Vec::new())) };
+ picked.push((own.clone(), *component, path.clone()));
+ }
+ if !crate::frames::placed(s) && picked.iter().all(|(_, component, _)| *component == s.active_component) {
+ return Ok((names, Vec::new()));
+ }
+ if let Some((name, ..)) = picked.iter().find(|(_, _, path)| path.iter().any(|id| s.pending_moves.contains_key(id))) {
+ return Err(bad(cmd, format!("`{name}` has a position that is not captured yet: Capture Position (component.capture_position) first")));
}
- Ok(picked.into_iter().unzip())
+ Ok(picked.into_iter().map(|(own, _, path)| (own, path)).unzip())
}
/// The other name of an origin plane (`Top` for `XY`, `XY` for `Top`...), if `name` is one.
diff --git a/crates/engine/src/tests/mirror_placed.rs b/crates/engine/src/tests/mirror_placed.rs
index 781fca3527..17bcebc5ab 100644
--- a/crates/engine/src/tests/mirror_placed.rs
+++ b/crates/engine/src/tests/mirror_placed.rs
@@ -63,6 +63,12 @@ fn a_further_instance_is_mirrored_at_its_own_placement() {
assert_eq!(copies.len(), 2, "{r}");
assert_box(world_box(&s, &copies[0]), mirrored_yz(&s, "ArmBody"));
assert_box(world_box(&s, &copies[1]), mirrored_yz(&s, &instance));
+ // A component placed twice would show a copy at both placements: the copies join the
+ // innermost component around it that is placed once, here the design itself.
+ let st = s.model.state();
+ for copy in &copies {
+ assert_eq!(s.doc.model_body_component(st.body(copy).unwrap()), 0, "{copy}");
+ }
}
#[test]
@@ -103,3 +109,123 @@ fn a_position_not_captured_yet_is_refused() {
let e = s.execute("solid.mirror", &json!({"bodies": ["ArmBody"], "plane": "YZ"})).unwrap_err().to_string();
assert!(e.contains("Capture Position"), "{e}");
}
+
+#[test]
+fn a_copy_goes_beside_its_source_in_that_component() {
+ // Moved or in place, a component's mirrored body is a body of that component.
+ for moved in [true, false] {
+ let mut s = Session::default();
+ let (component, occurrence) = moved_arm(&mut s);
+ if !moved {
+ run(&mut s, "occurrence.move", json!({"occurrence": occurrence, "base_transform": solidcraft_doc::IDENTITY}));
+ }
+ let copy = created(&run(&mut s, "solid.mirror", json!({"bodies": ["ArmBody"], "plane": "YZ"})));
+ let st = s.model.state();
+ assert_eq!(s.doc.model_body_component(st.body(&copy).unwrap()), component, "moved: {moved}");
+ assert_box(world_box(&s, &copy), mirrored_yz(&s, "ArmBody"));
+ // It stays there through a later feature on it.
+ run(&mut s, "solid.move", json!({"bodies": [copy.clone()], "translate": [0, 0, 5]}));
+ assert_eq!(s.doc.model_body_component(s.model.state().body(&copy).unwrap()), component, "moved: {moved}");
+ }
+}
+
+/// Inserting the same file again reuses its body names; a mirror of the first insert's bodies
+/// keeps mirroring them (their copies vanished: the names led to the second insert's components).
+#[test]
+fn inserting_the_same_file_again_keeps_the_mirrored_copies() {
+ let dir = std::env::temp_dir().join(format!("solidcraft-mirror-placed-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let file = dir.join("nested.step").to_string_lossy().replace('\\', "/");
+ let mut s = Session::default();
+ run(&mut s, "component.create", json!({"name": "Outer"}));
+ run(&mut s, "solid.box", json!({"length": 30, "width": 30, "height": 5, "body_name": "Plate"}));
+ let inner = run(&mut s, "component.create", json!({"name": "Inner"}))["occurrence"].as_u64().unwrap();
+ run(&mut s, "solid.box", json!({"length": 40, "width": 20, "height": 10, "body_name": "Block"}));
+ run(&mut s, "component.activate", json!({"component": 0}));
+ run(&mut s, "occurrence.move", json!({"occurrence": inner, "axis": [0, 0, 1], "angle": "90 deg", "translate": [100, 0, 0]}));
+ run(&mut s, "file.export", json!({"path": file}));
+
+ let mut s = Session::default();
+ run(&mut s, "file.insert_step", json!({"path": file, "name": "A"}));
+ let wanted: Vec<(Vec3, Vec3)> = ["Plate", "Block"].iter().map(|b| mirrored_yz(&s, b)).collect();
+ let r = run(&mut s, "solid.mirror", json!({"bodies": ["Plate", "Block"], "plane": "YZ"}));
+ let copies: Vec<String> = r["created_bodies"].as_array().unwrap().iter().map(|n| n.as_str().unwrap().to_string()).collect();
+ run(&mut s, "solid.remove", json!({"bodies": ["Plate", "Block"]}));
+ run(&mut s, "component.from_bodies", json!({"bodies": copies}));
+ run(&mut s, "file.insert_step", json!({"path": file, "name": "B"}));
+ let _ = std::fs::remove_dir_all(&dir);
+ for r in &s.model.results {
+ assert!(r.error.is_none(), "{}: {:?}", r.name, r.error);
+ }
+ for (copy, want) in copies.iter().zip(wanted) {
+ assert_box(world_box(&s, copy), want);
+ }
+}
+
+/// Moving an occurrence the mirror does not depend on leaves the mirror alone: before, any
+/// occurrence move evaluated it again, and every later command paid for one more mirror.
+#[test]
+fn moving_an_unrelated_occurrence_does_not_evaluate_the_mirror_again() {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 5, "corner": [10, 0, 0], "body_name": "A"}));
+ run(&mut s, "solid.box", json!({"length": 8, "width": 8, "height": 8, "corner": [30, 0, 0], "body_name": "B"}));
+ run(&mut s, "component.from_bodies", json!({"bodies": ["A", "B"]}));
+ let occurrences: Vec<u64> = s.doc.occurrences.iter().map(|o| o.id).collect();
+ assert_eq!(occurrences.len(), 2, "{:?}", s.doc.occurrences);
+ let a = s.doc.body_frames(&s.model.state()).into_iter().find(|(name, ..)| name == "A").map(|(_, _, path, _)| path).unwrap();
+ let (mine, other) = if a.contains(&occurrences[0]) { (occurrences[0], occurrences[1]) } else { (occurrences[1], occurrences[0]) };
+ run(&mut s, "occurrence.move", json!({"occurrence": mine, "translate": [0, 5, 0]}));
+ let copy = created(&run(&mut s, "solid.mirror", json!({"bodies": ["A"], "plane": "YZ"})));
+ for _ in 0..3 {
+ run(&mut s, "occurrence.move", json!({"occurrence": other, "translate": [0, 0.1, 0]}));
+ assert_eq!(s.model.last_recomputed, 0, "an unrelated move evaluated features again");
+ }
+ // Moving the mirrored body's own occurrence does evaluate it, and the copy follows.
+ run(&mut s, "occurrence.move", json!({"occurrence": mine, "translate": [0, 1, 0]}));
+ assert!(s.model.last_recomputed > 0);
+ assert_box(world_box(&s, &copy), mirrored_yz(&s, "A"));
+}
+
+/// Two mirrored copies of overlapping bodies of a placed component intersect as their sources do.
+#[test]
+fn mirrored_copies_of_a_placed_component_intersect() {
+ let mut s = Session::default();
+ let c = run(&mut s, "component.create", json!({"name": "Pair"}));
+ let occurrence = c["occurrence"].as_u64().unwrap();
+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [10, 0, 0], "body_name": "P"}));
+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [15, 5, 5], "body_name": "Q"}));
+ run(&mut s, "component.activate", json!({"component": 0}));
+ run(&mut s, "occurrence.move", json!({"occurrence": occurrence, "axis": [0, 0, 1], "angle": "30 deg", "translate": [5, 20, 0]}));
+ let r = run(&mut s, "solid.mirror", json!({"bodies": ["P", "Q"], "plane": "YZ"}));
+ let copies: Vec<String> = r["created_bodies"].as_array().unwrap().iter().map(|n| n.as_str().unwrap().to_string()).collect();
+ let i = run(&mut s, "inspect.interference", json!({}));
+ let pair = i["interferences"].as_array().unwrap().iter().find(|x| x["a"] == copies[0].as_str() || x["b"] == copies[0].as_str()).cloned();
+ let pair = pair.unwrap_or_else(|| panic!("{i}"));
+ assert!((pair["volume_mm3"].as_f64().unwrap() - 125.0).abs() < 1e-6, "{i}");
+ run(&mut s, "solid.combine", json!({"target": copies[0], "tools": [copies[1]], "operation": "intersect", "keep_tools": true}));
+ let v = run(&mut s, "inspect.measure", json!({"bodies": [copies[0]]}))["total"]["volume_mm3"].as_f64().unwrap();
+ assert!((v - 125.0).abs() < 1e-6, "{v}");
+}
+
+/// A saved placement that leads to another component (a stale or edited path) no longer shows the
+/// mirrored body: the mirror reports that, instead of mirroring it where the other one is placed.
+#[test]
+fn a_placement_leading_to_another_component_is_reported_lost() {
+ let mut s = Session::default();
+ moved_arm(&mut s);
+ let other = run(&mut s, "component.create", json!({"name": "Other"}))["occurrence"].as_u64().unwrap();
+ run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "body_name": "OtherBody"}));
+ run(&mut s, "component.activate", json!({"component": 0}));
+ run(&mut s, "occurrence.move", json!({"occurrence": other, "translate": [-500, 0, 0]}));
+ let copy = created(&run(&mut s, "solid.mirror", json!({"bodies": ["ArmBody"], "plane": "YZ"})));
+ let mirror = s.doc.features.last().unwrap().id;
+ if let Some(f) = std::sync::Arc::make_mut(&mut s.doc).feature_mut(mirror)
+ && let solidcraft_doc::FeatureKind::Mirror { placements, .. } = &mut f.kind
+ {
+ *placements = vec![vec![other]];
+ }
+ s.refresh();
+ let e = s.model.result(mirror).and_then(|r| r.error.clone()).unwrap_or_else(|| panic!("mirrored at the wrong placement"));
+ assert!(e.contains("no longer exists"), "{e}");
+ assert!(s.world_state().body(&copy).is_none());
+}