SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Assembly: let components extruded from reference faces move independently (#10289) (#10332)
Colin Faulkinghamdf04e7742fd2
diff --git a/crates/doc/src/face_anchor.rs b/crates/doc/src/face_anchor.rsindex 4f502b1ae7..0df02fe112 100644--- a/crates/doc/src/face_anchor.rs+++ b/crates/doc/src/face_anchor.rs@@ -13,12 +13,30 @@ pub struct FaceAnchor {pub component: u64,pub path: Vec<u64>,pub author_path: Vec<u64>,+ /// Source component to author component at capture, for an independently placed part.+ /// Body offsets and source geometry remain live; later assembly moves do not reshape it.+ /// Older attachments without this field retain their live placement relationship.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub placement: Option<crate::Mat>,/// Origin and x direction in the exact canonical face plane's coordinates.pub coordinates: [f64; 2],pub x_axis: [f64; 2],}impl FaceAnchor {+ /// Re-express a captured context when definitions (not their occurrences) change frames.+ pub fn reframe_placement(&mut self, author: &crate::Mat, source: &crate::Mat) -> Result<()> {+ if let Some(placement) = self.placement {+ let inverse = crate::mat_inverse(source).ok_or_else(|| DocError::Invalid("attached source frame is invalid".into()))?;+ let placement = crate::mat_mul(&crate::mat_mul(author, &placement), &inverse);+ if !crate::valid_transfer_matrix(&placement) {+ return Err(DocError::Invalid("invalid captured face placement".into()));+ }+ self.placement = Some(placement);+ }+ Ok(())+ }+pub fn remap_target(&mut self,features: &std::collections::BTreeMap<u64, u64>,@@ -47,6 +65,7 @@ impl FaceAnchor {|| self.path.iter().chain(&self.author_path).any(|id| *id == 0)|| (self.component == 0 && !self.path.is_empty())|| (self.component != 0 && self.path.is_empty())+ || self.placement.as_ref().is_some_and(|m| !crate::valid_transfer_matrix(m))|| self.coordinates.iter().any(|value| !value.is_finite() || value.abs() > 1e9)|| self.x_axis.iter().any(|value| !value.is_finite())|| (self.x_axis[0].hypot(self.x_axis[1]) - 1.).abs() > 1e-6@@ -70,13 +89,11 @@ impl FaceAnchor {}let inverse = crate::mat_inverse(&self.author_frame(doc, author)?).ok_or_else(|| DocError::Invalid("attached sketch author frame is invalid".into()))?;- let source = EmbossFace {- body: self.target.body.clone().into(),- at: crate::FacePick(self.target.point),- path: self.path.clone(),- author_path: self.author_path.clone(),- };- Ok(crate::mat_mul(&inverse, &source.body_frame(doc, body)?))+ // Resolve both paths even with a captured placement: a missing or reparented source+ // must still fail explicitly rather than silently reusing an unrelated definition.+ let source = EmbossFace::component_frame(doc, self.component, &self.path)?;+ let relative = self.placement.unwrap_or_else(|| crate::mat_mul(&inverse, &source));+ Ok(doc.model_body_offset(body).map_or(relative, |offset| crate::mat_mul(&relative, offset)))}}@@ -181,6 +198,7 @@ impl Document {component: self.model_body_component(body),path: target_path.to_vec(),author_path: author_path.to_vec(),+ placement: None,coordinates: [0., 0.],x_axis: [1., 0.],};@@ -191,6 +209,15 @@ impl Document {let delta = picked.origin - canonical.origin;anchor.coordinates = [delta.dot(canonical.x), delta.dot(canonical.y)];anchor.x_axis = [picked.x.dot(canonical.x), picked.x.dot(canonical.y)];+ // A part built against another component uses that assembly context to define its+ // own shape. Moving either occurrence later must not move the sketch inside the part.+ // Root sketches and references inside the same component keep their live placements.+ if author != 0 && author != anchor.component {+ let inverse = crate::mat_inverse(&anchor.author_frame(self, author)?)+ .ok_or_else(|| DocError::Invalid("attached sketch author frame is invalid".into()))?;+ let source = EmbossFace::component_frame(self, anchor.component, &anchor.path)?;+ anchor.placement = Some(crate::mat_mul(&inverse, &source));+ }anchor.validate()?;Ok(anchor)}@@ -389,7 +416,8 @@ impl Document {pub fn validate_face_anchor_json(value: &Value) -> Result<()> {let fields = value.as_object().ok_or_else(|| DocError::Invalid("face anchor must be an object".into()))?;- if fields.len() != 6 || fields.keys().any(|key| !["target", "component", "path", "author_path", "coordinates", "x_axis"].contains(&key.as_str()))+ if !(6..=7).contains(&fields.len())+ || fields.keys().any(|key| !["target", "component", "path", "author_path", "placement", "coordinates", "x_axis"].contains(&key.as_str())){return Err(DocError::Invalid("unknown or missing face anchor fields".into()));}@@ -423,6 +451,15 @@ pub fn validate_face_anchor_json(value: &Value) -> Result<()> {return Err(DocError::Invalid("face anchor basis must be normalized".into()));}}+ if let Some(placement) = fields.get("placement").filter(|v| !v.is_null()) {+ if placement.as_array().is_none_or(|rows| rows.len() != 4 || rows.iter().any(|row| row.as_array().is_none_or(|row| row.len() != 4))) {+ return Err(DocError::Invalid("face anchor placement requires a 4x4 matrix".into()));+ }+ let matrix: crate::Mat = serde_json::from_value(placement.clone()).map_err(|_| DocError::Invalid("invalid face anchor placement".into()))?;+ if !crate::valid_transfer_matrix(&matrix) {+ return Err(DocError::Invalid("face anchor placement must be a finite rigid transform".into()));+ }+ }Ok(())}@@ -531,6 +568,44 @@ mod tests {.unwrap();assert!(doc.resolve_face_anchor(&anchor, 0, &state).is_err(), "reused name cannot replace the producer");}+ #[test]+ fn captured_component_placement_is_rigid_and_legacy_anchors_stay_live() {+ let (mut doc, body, index, picked) = fixture();+ let author = doc.add_component(Some("Part"), 0).unwrap();+ let path = doc.first_path(author);+ let anchor = doc.capture_face_anchor(&body, index, &picked, &[], author, &path).unwrap();+ assert_eq!(anchor.placement, Some(crate::IDENTITY));+ let raw = serde_json::to_value(&anchor).unwrap();+ assert!(validate_face_anchor_json(&raw).is_ok());+ let restored: FaceAnchor = serde_json::from_value(raw.clone()).unwrap();+ assert_eq!(restored, anchor);+ for placement in [+ serde_json::json!([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]]),+ serde_json::json!([[2, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]),+ serde_json::json!([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]),+ serde_json::json!([[1, 0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]),+ serde_json::json!([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [1e10, 0, 0, 1]]),+ ] {+ let mut invalid = raw.clone();+ invalid["placement"] = placement;+ assert!(validate_face_anchor_json(&invalid).is_err(), "{invalid}");+ if let Ok(invalid) = serde_json::from_value::<FaceAnchor>(invalid) {+ assert!(invalid.validate().is_err());+ }+ }+ let mut legacy = raw;+ legacy.as_object_mut().unwrap().remove("placement");+ assert!(validate_face_anchor_json(&legacy).is_ok());+ let legacy: FaceAnchor = serde_json::from_value(legacy).unwrap();+ doc.occurrences.iter_mut().find(|o| o.component == author).unwrap().transform[3][0] = 40.;+ let mut state = ModelState::default();+ state.bodies.push(body);+ assert!(doc.resolve_face_anchor(&anchor, author, &state).unwrap().origin.dist(picked.origin) < 1e-9);+ assert!(doc.resolve_face_anchor(&legacy, author, &state).unwrap().origin.dist(picked.origin - Vec3::X * 40.) < 1e-9);+ doc.occurrences.clear();+ assert!(doc.resolve_face_anchor(&anchor, author, &state).is_err(), "a captured context still validates its paths");+ }+#[test]fn nested_anchor_offset_tracks_source_and_raw_budgets_precede_decode() {let (doc, body, index, picked) = fixture();diff --git a/crates/doc/src/format/pending/face-anchor-placement.rs b/crates/doc/src/format/pending/face-anchor-placement.rsnew file mode 100644index 0000000000..b39a55e3d5--- /dev/null+++ b/crates/doc/src/format/pending/face-anchor-placement.rs@@ -0,0 +1,5 @@+//! Cross-component face anchors in a part save the source-to-author component placement at+//! creation, so assembly moves do not reshape the part. Source geometry and body offsets stay+//! associative. Older anchors without `placement` retain their live placement relationship;+//! redefining their sketch plane captures a new context. The last release refuses this newer+//! format and asks for an update instead of dropping the captured placement.diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rsindex c8b1a29cd6..c63794469a 100644--- a/crates/engine/src/cmd/clipboard.rs+++ b/crates/engine/src/cmd/clipboard.rs@@ -150,6 +150,10 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {if !internal {notices.push(format!("pasted sketch retains external exact face attachment to {}", anchor.target.body));}+ if internal {+ let source = solidcraft_doc::mat_mul(&shift, frame_change.get(&anchor.component).unwrap_or(&solidcraft_doc::IDENTITY));+ anchor.reframe_placement(&m, &source)?;+ }anchor.remap_target(&sketches, &bodies)?;if internal {anchor.component = comp;diff --git a/crates/engine/src/cmd/component_move_features.rs b/crates/engine/src/cmd/component_move_features.rsindex 50bf4ef34e..3cddebc150 100644--- a/crates/engine/src/cmd/component_move_features.rs+++ b/crates/engine/src/cmd/component_move_features.rs@@ -93,6 +93,15 @@ pub(super) fn move_features(s: &mut Session, p: &Value) -> Result<Value> {FeatureKind::Sketch { plane, .. } => {if let Some(anchor) = crate::cmd::sketch::face::anchor_mut(plane) {let moved_body = moved_bodies.contains(&anchor.target.body);+ let author_delta = if authored_here {+ let old = s.doc.feature(f.id).ok_or_else(|| bad(cmd, "attached sketch no longer exists"))?;+ mat_mul(&to_dest, &s.doc.component_transform(old.component))+ } else {+ solidcraft_doc::IDENTITY+ };+ let source_delta =+ if moved_body { mat_mul(&to_dest, &s.doc.component_transform(anchor.component)) } else { solidcraft_doc::IDENTITY };+ anchor.reframe_placement(&author_delta, &source_delta)?;rewrite(&anchor.target.body, &mut anchor.path, &mut anchor.author_path);if moved_body {anchor.component = dest;diff --git a/crates/engine/src/cmd/face_tests.rs b/crates/engine/src/cmd/face_tests.rsindex c180e83e22..544353e470 100644--- a/crates/engine/src/cmd/face_tests.rs+++ b/crates/engine/src/cmd/face_tests.rs@@ -67,6 +67,108 @@ fn generated_face_profiles_keep_exact_links_live_after_edit_and_reopen() {}}}+#[test]+fn a_component_extruded_from_another_components_face_moves_independently() {+ let mut s = Session::default();+ let reference = run(&mut s, "component.create", json!({"name":"Reference","grounded":false}));+ run(&mut s, "solid.box", json!({"length":20,"width":20,"height":20,"name":"Base","body_name":"Stock"}));+ run(&mut s, "component.activate", json!({"component":0}));+ let part = run(&mut s, "component.create", json!({"name":"Part"}));+ run(&mut s, "solid.extrude", json!({"face":[10,10,20],"distance":10,"operation":"new","body_name":"Pad"}));+ run(&mut s, "component.activate", json!({"component":0}));+ let measure = |s: &mut Session, center: [f64; 3], volume: f64| {+ assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results);+ let got = run(s, "inspect.center_of_mass", json!({"bodies":["Pad"]}));+ for (i, want) in center.iter().enumerate() {+ assert!((got["center"][i].as_f64().unwrap() - want).abs() < 1e-6, "{got}; expected {center:?}");+ }+ assert!((got["volume"].as_f64().unwrap() - volume).abs() < 1e-6, "{got}");+ };+ measure(&mut s, [10., 10., 25.], 4000.);+ run(&mut s, "occurrence.move", json!({"occurrence":part["occurrence"],"translate":[40,0,0],"capture":true}));+ measure(&mut s, [50., 10., 25.], 4000.);+ run(&mut s, "edit.undo", json!({}));+ measure(&mut s, [10., 10., 25.], 4000.);+ run(&mut s, "edit.redo", json!({}));+ measure(&mut s, [50., 10., 25.], 4000.);+ // Moving the reference is an assembly placement, not an edit to its shape.+ run(&mut s, "occurrence.move", json!({"occurrence":reference["occurrence"],"translate":[0,50,0],"capture":true}));+ measure(&mut s, [50., 10., 25.], 4000.);+ // Both the attached plane and its projected outline still follow source dimensions.+ run(&mut s, "timeline.edit", json!({"feature":"Base","set":{"length":"30","height":"25"}}));+ measure(&mut s, [55., 10., 30.], 6000.);+ let mut reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap());+ measure(&mut reopened, [55., 10., 30.], 6000.);+ run(&mut reopened, "occurrence.move", json!({"occurrence":part["occurrence"],"translate":[0,0,10],"capture":true}));+ measure(&mut reopened, [55., 10., 40.], 6000.);+ run(&mut reopened, "timeline.copy", json!({"features":["Base","Sketch1","Extrude1"]}));+ run(&mut reopened, "timeline.paste", json!({"translate":[0,0,50]}));+ let copy = run(&mut reopened, "inspect.center_of_mass", json!({"bodies":["Pad (2)"]}));+ for (i, want) in [55., 10., 90.].iter().enumerate() {+ assert!((copy["center"][i].as_f64().unwrap() - want).abs() < 1e-6, "{copy}");+ }+ assert!((copy["volume"].as_f64().unwrap() - 6000.).abs() < 1e-6);+ // Reorganizing the feature definitions must preserve the captured context too.+ run(&mut reopened, "component.move_features", json!({"features":["Base","Sketch1","Extrude1"],"component":0}));+ measure(&mut reopened, [55., 10., 40.], 6000.);+}++#[test]+fn a_cross_component_face_profile_keeps_its_rotated_creation_context() {+ let mut s = Session::default();+ let source = run(&mut s, "component.create", json!({"name":"Reference","grounded":false}));+ run(&mut s, "solid.box", json!({"length":20,"width":20,"height":20,"body_name":"Stock"}));+ run(&mut s, "occurrence.move", json!({"occurrence":source["occurrence"],"translate":[30,20,0],"angle":"90 deg"}));+ let part = run(&mut s, "component.create", json!({"name":"Part","parent":0}));+ run(&mut s, "occurrence.move", json!({"occurrence":part["occurrence"],"translate":[-20,10,0],"angle":"-90 deg","capture":false}));+ run(&mut s, "solid.extrude", json!({"face":[20,30,20],"distance":10,"operation":"new","body_name":"Pad"}));+ assert!(s.pending_moves.is_empty(), "face capture records the author's pending placement");+ run(&mut s, "component.activate", json!({"component":0}));+ let center = |s: &mut Session, want: [f64; 3]| {+ let got = run(s, "inspect.center_of_mass", json!({"bodies":["Pad"]}));+ for (i, want) in want.iter().enumerate() {+ assert!((got["center"][i].as_f64().unwrap() - want).abs() < 1e-6, "{got}");+ }+ assert!((got["volume"].as_f64().unwrap() - 4000.).abs() < 1e-6);+ };+ center(&mut s, [20., 30., 25.]);+ run(&mut s, "occurrence.move", json!({"occurrence":part["occurrence"],"translate":[50,0,5],"angle":"90 deg","capture":false}));+ center(&mut s, [20., 20., 30.]);+ run(&mut s, "component.capture_position", json!({}));+ center(&mut s, [20., 20., 30.]);+ let mut reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap());+ center(&mut reopened, [20., 20., 30.]);+}++#[test]+fn moving_the_original_face_derived_component_does_not_move_its_copies_backwards() {+ let mut s = Session::default();+ run(&mut s, "component.create", json!({"name":"Reference"}));+ run(&mut s, "solid.box", json!({"length":20,"width":20,"height":20}));+ let part = run(&mut s, "component.create", json!({"name":"Part","parent":0}));+ run(&mut s, "solid.extrude", json!({"face":[10,10,20],"distance":10,"operation":"new","body_name":"Pad"}));+ run(&mut s, "component.activate", json!({"component":0}));+ let copy = run(&mut s, "occurrence.copy", json!({"component":part["component"],"translate":[0,40,0]}));+ run(&mut s, "occurrence.copy", json!({"component":part["component"],"translate":[0,80,0]}));+ run(&mut s, "occurrence.move", json!({"occurrence":copy["occurrence"],"translate":[10,0,0],"capture":true}));+ let centers = |s: &mut Session, original: [f64; 3]| {+ for (body, want) in [("Pad", original), ("Pad (Part:2)", [20., 50., 25.]), ("Pad (Part:3)", [10., 90., 25.])] {+ let got = run(s, "inspect.center_of_mass", json!({"bodies":[body]}));+ for (i, want) in want.iter().enumerate() {+ assert!((got["center"][i].as_f64().unwrap() - want).abs() < 1e-6, "{body}: {got}");+ }+ assert!((got["volume"].as_f64().unwrap() - 4000.).abs() < 1e-6, "{got}");+ }+ };+ centers(&mut s, [10., 10., 25.]);+ run(&mut s, "occurrence.move", json!({"occurrence":part["occurrence"],"translate":[40,0,0],"capture":true}));+ centers(&mut s, [50., 10., 25.]);+ let mut reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap());+ centers(&mut reopened, [50., 10., 25.]);+ run(&mut reopened, "occurrence.move", json!({"occurrence":part["occurrence"],"angle":"90 deg","capture":true}));+ centers(&mut reopened, [-10., 50., 25.]);+}+#[test]fn internal_capture_does_not_bypass_missing_ambiguous_or_invalid_path_picks() {let mut s = Session::default();