Skip to content

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

Joints: origins on an edge of a face, at its middle or a corner (#2403) (#2404)

NOWN-DEV6d410c342cae
diff --git a/crates/doc/src/format/pending/joint-origin-edge.rs b/crates/doc/src/format/pending/joint-origin-edge.rs
new file mode 100644
index 0000000000..628d743a8e
--- /dev/null
+++ b/crates/doc/src/format/pending/joint-origin-edge.rs
@@ -0,0 +1,4 @@
+//! A joint origin can sit on an edge of a planar face (`Snap::Edge`, saved as `"type": "edge"`):
+//! at the edge's middle or at a corner where it meets another edge, all three found again by name.
+//! Older designs need no transformation: they have no such origins. The last release refuses a
+//! design saved with this (the newer format number).
diff --git a/crates/doc/src/format/pending/joint-origin-frame-x.rs b/crates/doc/src/format/pending/joint-origin-frame-x.rs
new file mode 100644
index 0000000000..c9a32ddf5a
--- /dev/null
+++ b/crates/doc/src/format/pending/joint-origin-frame-x.rs
@@ -0,0 +1,5 @@
+//! A face or circle joint origin given no `x` reference keeps the x its frame had when picked
+//! (`x` as a direction, component coordinates) and lays it onto the face as it is now, so a part
+//! on a face that tilts keeps its turn. Older designs need no transformation: an origin without
+//! `x` works its frame out from the normal alone, as before. The last release refuses a design
+//! saved with this (the newer format number).
diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rs
index b126301e2f..6aa54eeec2 100644
--- a/crates/doc/src/joints.rs
+++ b/crates/doc/src/joints.rs
@@ -62,6 +62,18 @@ pub enum Snap {
#[serde(default, skip_serializing_if = "Option::is_none")]
x: Option<XRef>,
},
+ /// A point on an edge of a planar face: the edge's middle, or the corner where it meets the
+ /// edge `corner` names (`joints_edge.rs`). `edge` and `face` are the persistent names of the
+ /// edge and the face (found first); `pick` is a point on the edge as it was picked.
+ Edge {
+ pick: Vec3,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ edge: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ face: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ corner: Option<String>,
+ },
/// A point, z along `z` (default +Z).
Point {
point: Vec3,
@@ -88,7 +100,8 @@ pub enum XRef {
}
impl Snap {
- /// The persistent face names the snap refers to (its face, its end's, its x reference's).
+ /// The persistent face and edge names the snap refers to (its face, its end's, its x reference's;
+ /// an edge origin's edge, face and corner edge).
pub fn face_names(&self) -> Vec<&String> {
let mut out = Vec::new();
if let Snap::FaceCenter { face, x, .. } | Snap::CircleCenter { face, x, .. } = self {
@@ -100,6 +113,9 @@ impl Snap {
if let Snap::CircleCenter { end: Some(end), .. } = self {
out.push(end);
}
+ if let Snap::Edge { edge, face, corner, .. } = self {
+ out.extend(edge.iter().chain(face.iter()).chain(corner.iter()));
+ }
out
}
@@ -120,11 +136,33 @@ impl Snap {
out.push(face);
}
}
+ Snap::Edge { edge, face, corner, .. } => out.extend(edge.iter_mut().chain(face.iter_mut()).chain(corner.iter_mut())),
_ => {}
}
out
}
+ /// The direction a face or circle snap keeps as its frame's x (`XRef::Dir`), in the
+ /// component's coordinates; `None` for a face reference or none.
+ pub fn frame_x(&self) -> Option<Vec3> {
+ match self {
+ Snap::FaceCenter { x: Some(XRef::Dir(d)), .. } | Snap::CircleCenter { x: Some(XRef::Dir(d)), .. } => Some(*d),
+ _ => None,
+ }
+ }
+
+ /// A face or circle snap given no x reference keeps `x` (the frame's x as it is now): each
+ /// solve lays it onto the face, or square to the hole's axis, as the geometry is then, so a
+ /// part on a face that tilts keeps its turn about z. Without it (designs made before) x
+ /// follows from z alone, and turns through a right angle where z crosses 0.9 along the
+ /// component's X. A snap with a reference keeps it.
+ pub fn with_frame_x(mut self, x: Vec3) -> Snap {
+ if let Snap::FaceCenter { x: slot @ None, .. } | Snap::CircleCenter { x: slot @ None, .. } = &mut self {
+ *slot = Some(XRef::Dir(x));
+ }
+ self
+ }
+
/// Whether every point and direction in the snap is finite.
pub fn is_finite(&self) -> bool {
let x_ok = |x: &Option<XRef>| match x {
@@ -136,6 +174,7 @@ impl Snap {
Snap::Frame { origin, z, x } => origin.is_finite() && z.is_finite() && x.is_none_or(|x| x.is_finite()),
Snap::FaceCenter { pick, x, .. } | Snap::CircleCenter { pick, x, .. } => pick.is_finite() && x_ok(x),
Snap::Point { point, z } => point.is_finite() && z.is_none_or(|z| z.is_finite()),
+ Snap::Edge { pick, .. } => pick.is_finite(),
}
}
}
@@ -519,6 +558,7 @@ pub fn resolve_origin(doc: &Document, st: &ModelState, o: &JointOrigin) -> Resul
};
frame(c, n, face::x_axis(doc, st, x.as_ref(), c)?).ok_or_else(bad)
}
+ Snap::Edge { .. } => edge::edge_frame(doc, st, component_of(doc, o.occurrence)?, &o.snap),
Snap::CircleCenter { x, .. } => {
let r = round_of(doc, st, o)?;
frame(r.centre, r.z, face::x_axis(doc, st, x.as_ref(), r.centre)?).ok_or_else(bad)
@@ -1548,6 +1588,10 @@ impl Document {
#[path = "joints_cam.rs"]
pub mod cam;
+#[path = "joints_edge.rs"]
+mod edge;
+pub use edge::edge_snap;
+
#[path = "joints_reach.rs"]
mod reach;
diff --git a/crates/doc/src/joints_edge.rs b/crates/doc/src/joints_edge.rs
new file mode 100644
index 0000000000..097d51bbce
--- /dev/null
+++ b/crates/doc/src/joints_edge.rs
@@ -0,0 +1,193 @@
+//! Joint origins on an edge of a planar face (`Snap::Edge`): the edge's middle, or a corner where
+//! it meets another edge of the face. The edge, the face and the corner's other edge are found
+//! again by name on every solve, so the origin follows the face as it grows, shrinks or moves:
+//! hardware set 40 mm in from a panel's corner stays 40 mm in from that corner at any size.
+//!
+//! The frame never depends on which way an edge's polyline runs: z is the face's outward normal;
+//! at the middle y points into the face, square to the edge, and x = y × z runs along it; at a
+//! corner x and y run along the two edges, away from the corner into the face, in the order that
+//! makes the frame right-handed.
+
+use solidcraft_geom::Vec3;
+
+use super::{Snap, component_bodies, frame};
+use crate::{DocError, Document, Mat, ModelBody, ModelState, Result};
+
+/// Points that close are one corner (as a share of the body's size, at least 1 µm).
+fn tol(b: &ModelBody) -> f64 {
+ (b.body.size() * 2e-3).max(1e-3)
+}
+
+/// The edge of `b` nearest `p`, and how far it is.
+fn nearest_edge(b: &ModelBody, p: Vec3) -> Option<(usize, f64)> {
+ b.mesh()
+ .edges
+ .iter()
+ .enumerate()
+ .map(|(i, e)| (i, e.windows(2).map(|w| p.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min)))
+ .filter(|(_, d)| d.is_finite())
+ .min_by(|a, b| a.1.total_cmp(&b.1))
+}
+
+/// Edge `i` of `b`: by its name (`None` when the body has no such edge), else the edge at `pick`.
+fn edge_index(b: &ModelBody, name: Option<&str>, pick: Vec3) -> Option<usize> {
+ match name {
+ Some(n) => crate::name_lookup::locate_edge(b, n, pick).ok().map(|h| h.edge),
+ None => nearest_edge(b, pick).filter(|(_, d)| *d <= tol(b)).map(|(i, _)| i),
+ }
+}
+
+/// The planar face beside edge `i` the origin sits on: the named one, else the larger planar face
+/// the edge bounds. Its index, outward normal and centroid.
+fn face_of(b: &ModelBody, i: usize, name: Option<&str>, pick: Vec3) -> Result<(usize, Vec3, Vec3)> {
+ let m = b.mesh();
+ let beside: Vec<usize> = m.edge_faces.get(i).map(|fs| fs.iter().map(|f| *f as usize).collect()).unwrap_or_default();
+ let infos = b.body.faces(tol(b))?;
+ let planar = |f: usize| infos.iter().find(|x| x.index == f).and_then(|x| x.plane_normal.map(|n| (x.index, n, x.centroid, x.area)));
+ let chosen = match name {
+ Some(n) => {
+ let (f, _, _) = crate::naming::face_on_body(b, n, pick)
+ .ok_or_else(|| DocError::Invalid(format!("joint origin: the face `{n}` no longer exists (edit the joint to pick again)")))?;
+ if !beside.contains(&f) {
+ return Err(DocError::Invalid(format!("joint origin: the face `{n}` no longer meets its edge (edit the joint to pick again)")));
+ }
+ planar(f)
+ }
+ None => beside.iter().filter_map(|f| planar(*f)).max_by(|a, b| a.3.total_cmp(&b.3)),
+ };
+ chosen.map(|(f, n, c, _)| (f, n, c)).ok_or_else(|| DocError::Invalid("joint origin: no planar face beside that edge".into()))
+}
+
+/// Edge `i`'s middle (along its polyline) and the direction it runs there.
+fn middle(e: &[Vec3]) -> Option<(Vec3, Vec3)> {
+ let total: f64 = e.windows(2).map(|w| w[0].dist(w[1])).sum();
+ let mut acc = 0.0;
+ for w in e.windows(2) {
+ let l = w[0].dist(w[1]);
+ if l > 0.0 && acc + l >= total / 2.0 {
+ let t = (total / 2.0 - acc) / l;
+ return Some((w[0] + (w[1] - w[0]) * t, (w[1] - w[0]) / l));
+ }
+ acc += l;
+ }
+ None
+}
+
+/// An edge's end at `p` (within `tol`) and the direction it leaves the end in.
+fn leaving(e: &[Vec3], p: Vec3, tol: f64) -> Option<Vec3> {
+ let (first, last) = (*e.first()?, *e.last()?);
+ let away = |q: Option<&Vec3>, from: Vec3| q.and_then(|q| (*q - from).normalized());
+ if first.dist(p) <= tol {
+ away(e.iter().find(|q| q.dist(first) > tol * 0.5), first)
+ } else if last.dist(p) <= tol {
+ away(e.iter().rev().find(|q| q.dist(last) > tol * 0.5), last)
+ } else {
+ None
+ }
+}
+
+/// The corner where edges `e` and `f` meet: the closest pair of their ends, when within `tol`.
+fn meeting(e: &[Vec3], f: &[Vec3], tol: f64) -> Option<Vec3> {
+ let ends = |x: &[Vec3]| [x.first().copied(), x.last().copied()];
+ ends(e)
+ .into_iter()
+ .flatten()
+ .flat_map(|a| ends(f).into_iter().flatten().map(move |b| (a, a.dist(b))))
+ .filter(|(_, d)| *d <= tol)
+ .min_by(|a, b| a.1.total_cmp(&b.1))
+ .map(|(a, _)| a)
+}
+
+/// The frame of an edge snap in its component's coordinates.
+pub(super) fn edge_frame(doc: &Document, st: &ModelState, comp: u64, snap: &Snap) -> Result<Mat> {
+ let Snap::Edge { pick, edge, face, corner } = snap else { return Err(DocError::Invalid("not an edge origin".into())) };
+ let bad = || DocError::Invalid("joint origin: degenerate frame".into());
+ let gone = |what: &str| DocError::Invalid(format!("joint origin: {what} no longer exists (edit the joint to pick again)"));
+ let found = component_bodies(doc, st, comp).into_iter().find_map(|b| edge_index(b, edge.as_deref(), *pick).map(|i| (b, i)));
+ let (b, i) = found.ok_or_else(|| match edge {
+ Some(n) => gone(&format!("the edge `{n}`")),
+ None => DocError::Invalid("joint origin: no edge there".into()),
+ })?;
+ let m = b.mesh();
+ let e = m.edges.get(i).ok_or_else(bad)?;
+ let (_, z, centroid) = face_of(b, i, face.as_deref(), *pick)?;
+ let flat = |v: Vec3| (v - z * v.dot(z)).normalized();
+ match corner {
+ None => {
+ let (mid, along) = middle(e).ok_or_else(bad)?;
+ // Into the face: toward its centroid, square to the edge; a face whose centroid lies on
+ // the edge's line (only a sliver) falls back to the side z × along gives.
+ let to_c = centroid - mid;
+ let y = flat(to_c - along * to_c.dot(along)).unwrap_or_else(|| z.cross(along));
+ frame(mid, z, Some(y.cross(z))).ok_or_else(bad)
+ }
+ Some(other) => {
+ let j = crate::name_lookup::locate_edge(b, other, *pick).map_err(|_| gone(&format!("the edge `{other}`")))?.edge;
+ let f = m.edges.get(j).ok_or_else(bad)?;
+ let t = tol(b);
+ let at = meeting(e, f, t).ok_or_else(|| DocError::Invalid(format!("joint origin: its edges no longer meet at a corner (`{other}`)")))?;
+ let (de, df) = (leaving(e, at, t).and_then(flat).ok_or_else(bad)?, leaving(f, at, t).and_then(flat).ok_or_else(bad)?);
+ let x = if z.dot(de.cross(df)) >= 0.0 { de } else { df };
+ frame(at, z, Some(x)).ok_or_else(bad)
+ }
+ }
+}
+
+/// An edge snap for an edge picked at `pick` on component `comp` (its own coordinates): on the
+/// planar face holding `on` (default: the larger planar face beside the edge), at the edge's
+/// middle or, with `corner`, at the end nearest it. The edge, the face and the corner's other
+/// edge are kept by name.
+pub fn edge_snap(doc: &Document, st: &ModelState, comp: u64, pick: Vec3, on: Option<Vec3>, corner: Option<Vec3>) -> Result<Snap> {
+ let (b, i) = component_bodies(doc, st, comp)
+ .into_iter()
+ .filter_map(|b| nearest_edge(b, pick).filter(|(_, d)| *d <= tol(b)).map(|(i, _)| (b, i)))
+ .next()
+ .ok_or_else(|| DocError::Invalid("joint origin: no edge there".into()))?;
+ let names = crate::naming::edge_names(b);
+ let face_names = crate::naming::face_names(b);
+ let m = b.mesh();
+ let beside: Vec<usize> = m.edge_faces.get(i).map(|fs| fs.iter().map(|f| *f as usize).collect()).unwrap_or_default();
+ let face_index = match on {
+ Some(p) => {
+ let f = crate::naming::face_name_at_body(b, p)
+ .and_then(|n| crate::naming::face_on_body(b, &n, p))
+ .map(|(f, _, _)| f)
+ .ok_or_else(|| DocError::Invalid("joint origin: `on` is not on a face of that body".into()))?;
+ if !beside.contains(&f) {
+ return Err(DocError::Invalid("joint origin: `on` picks a face the edge doesn't bound".into()));
+ }
+ f
+ }
+ None => face_of(b, i, None, pick)?.0,
+ };
+ let face = face_names.get(face_index).cloned().filter(|n| !n.is_empty());
+ let corner = match corner {
+ None => None,
+ Some(c) => {
+ let e = m.edges.get(i).cloned().unwrap_or_default();
+ let t = tol(b);
+ let end = [e.first().copied(), e.last().copied()]
+ .into_iter()
+ .flatten()
+ .min_by(|a, b| a.dist(c).total_cmp(&b.dist(c)))
+ .ok_or_else(|| DocError::Invalid("joint origin: that edge has no ends".into()))?;
+ // The other edge of the face that ends there.
+ let other = m
+ .edges
+ .iter()
+ .enumerate()
+ .filter(|(j, _)| *j != i && m.edge_faces.get(*j).is_some_and(|fs| fs.contains(&(face_index as u32))))
+ .find(|(_, f)| meeting(&[end], f, t).is_some())
+ .map(|(j, _)| j)
+ .ok_or_else(|| DocError::Invalid("joint origin: no other edge of the face meets that end (a round edge has no corner)".into()))?;
+ Some(
+ names
+ .get(other)
+ .cloned()
+ .filter(|n| !n.is_empty())
+ .ok_or_else(|| DocError::Invalid("joint origin: the corner's other edge has no name".into()))?,
+ )
+ }
+ };
+ Ok(Snap::Edge { pick, edge: names.get(i).cloned().filter(|n| !n.is_empty()), face, corner })
+}
diff --git a/crates/engine/src/cmd/component_clone_assembly_tests.rs b/crates/engine/src/cmd/component_clone_assembly_tests.rs
index 23defb3897..da1d309985 100644
--- a/crates/engine/src/cmd/component_clone_assembly_tests.rs
+++ b/crates/engine/src/cmd/component_clone_assembly_tests.rs
@@ -233,3 +233,27 @@ fn paste_new_internal_motion_study_drives_only_the_copied_assembly_and_reopens()
assert_eq!(reopened.assembly, s.doc.assembly);
assert!(reopened.assembly.studies.iter().any(|m| m.name == "Travel (copy)" && m.keys[0].joint == copied_joint));
}
+
+/// An edge origin's edge, face and corner edge are the copy's too.
+#[test]
+fn an_edge_origin_is_copied_onto_the_copys_edges() {
+ let (source, mut destination) = documents();
+ let edge = |e: &str| Some(e.to_string());
+ let mut source = source;
+ source.assembly.origins = vec![NamedOrigin {
+ name: "Corner".into(),
+ origin: JointOrigin {
+ occurrence: 1,
+ snap: Snap::Edge { pick: Vec3::new(1.0, 2.0, 3.0), edge: edge("F1:top|F1:side"), face: edge("F1:top"), corner: edge("F1:top|F10:end") },
+ },
+ }];
+ destination.assembly.origins.clear();
+ clone_assembly(&mut destination, &source, &BTreeMap::from([(1, 101), (2, 102)]), &BTreeMap::from([(1, 11), (10, 110)]), &BTreeMap::new())
+ .unwrap();
+ let copied = destination.assembly.origins.last().map(|o| &o.origin.snap);
+ assert!(
+ matches!(copied, Some(Snap::Edge { edge: Some(e), face: Some(f), corner: Some(c), .. })
+ if e == "F11:top|F11:side" && f == "F11:top" && c == "F11:top|F110:end"),
+ "{copied:?}"
+ );
+}
diff --git a/crates/engine/src/cmd/joint_edge_tests.rs b/crates/engine/src/cmd/joint_edge_tests.rs
new file mode 100644
index 0000000000..7b0fc9c2c1
--- /dev/null
+++ b/crates/engine/src/cmd/joint_edge_tests.rs
@@ -0,0 +1,108 @@
+//! Joint origins on an edge of a face (its middle, or a corner) follow the face as it changes size.
+
+use serde_json::json;
+use solidcraft_geom::Vec3;
+
+use super::tests::{place, run};
+use crate::Session;
+
+/// A 2 mm panel `W` x 300 (W = 400) in component Panel, and a 20 x 10 x 6 bracket in component
+/// Bracket, off to the side.
+fn panel() -> Session {
+ let mut s = Session::default();
+ run(&mut s, "parameters.add", json!({"name": "W", "expression": "400 mm"}));
+ run(&mut s, "component.create", json!({"name": "Panel"}));
+ run(&mut s, "solid.box", json!({"length": "W", "width": 300, "height": 2, "corner": [0, 0, 0]}));
+ run(&mut s, "component.activate", json!({"component": "root"}));
+ run(&mut s, "component.create", json!({"name": "Bracket"}));
+ run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 6, "corner": [0, 500, 0]}));
+ s
+}
+
+/// The middle of the bracket's bottom face, where it is now.
+fn bracket(s: &Session) -> Vec3 {
+ place(s, "Bracket", Vec3::new(10.0, 505.0, 0.0))
+}
+
+fn near(a: Vec3, b: Vec3) -> bool {
+ a.dist(b) < 1e-6
+}
+
+#[test]
+fn a_part_set_in_from_a_corner_stays_there_as_the_panel_grows() {
+ let mut s = panel();
+ // The front right corner of the top face; the bracket 40 mm in along both edges.
+ run(
+ &mut s,
+ "joint.create",
+ json!({"type": "planar", "a": {"occurrence": "Panel", "edge": [200, 0, 2], "corner": [400, 0, 2]},
+ "b": {"occurrence": "Bracket", "face": [10, 505, 0]}, "values": [40, 40, 0], "name": "Corner"}),
+ );
+ for w in [400.0, 600.0, 250.0, 1000.0] {
+ run(&mut s, "parameters.change", json!({"name": "W", "expression": format!("{w} mm")}));
+ assert!(near(bracket(&s), Vec3::new(w - 40.0, 40.0, 2.0)), "W {w}: {:?}", bracket(&s));
+ assert_eq!(run(&mut s, "joint.solve", json!({}))["errors"], json!([]));
+ }
+ let snap = s.doc.assembly.joints.first().map(|j| j.a.snap.clone());
+ assert!(
+ matches!(&snap, Some(solidcraft_doc::joints::Snap::Edge { edge: Some(_), face: Some(_), corner: Some(_), .. })),
+ "the edge, the face and the corner's other edge are kept by name: {snap:?}"
+ );
+}
+
+#[test]
+fn a_part_at_an_edges_middle_follows_it_and_the_face_can_be_chosen() {
+ let mut s = panel();
+ // The right edge of the top face: its middle is (W, 150, 2), y points into the face (−X).
+ run(
+ &mut s,
+ "joint.create",
+ json!({"type": "planar", "a": {"occurrence": "Panel", "edge": [400, 100, 2]},
+ "b": {"occurrence": "Bracket", "face": [10, 505, 0]}, "values": [0, 40, 0], "name": "Mid"}),
+ );
+ for w in [400.0, 700.0, 320.0] {
+ run(&mut s, "parameters.change", json!({"name": "W", "expression": format!("{w} mm")}));
+ assert!(near(bracket(&s), Vec3::new(w - 40.0, 150.0, 2.0)), "W {w}: {:?}", bracket(&s));
+ }
+ // The same edge on the end face: z points out of the end (+X), y into it (down).
+ run(&mut s, "joint.delete", json!({"joint": "Mid"}));
+ run(
+ &mut s,
+ "joint.create",
+ json!({"type": "rigid", "a": {"occurrence": "Panel", "edge": [320, 100, 2], "on": [320, 150, 1]},
+ "b": {"occurrence": "Bracket", "face": [10, 505, 0]}, "name": "End"}),
+ );
+ assert!(near(bracket(&s), Vec3::new(320.0, 150.0, 2.0)), "{:?}", bracket(&s));
+ // The bracket's bottom faces the end face: its top (6 mm up its own z) is out along +X.
+ assert!(
+ near(place(&s, "Bracket", Vec3::new(10.0, 505.0, 6.0)), Vec3::new(326.0, 150.0, 2.0)),
+ "{:?}",
+ place(&s, "Bracket", Vec3::new(10.0, 505.0, 6.0))
+ );
+}
+
+#[test]
+fn edge_origins_refuse_bad_picks_and_report_a_lost_edge() {
+ let mut s = panel();
+ let bad = |s: &mut Session, a: serde_json::Value| {
+ s.execute("joint.create", &json!({"type": "rigid", "a": a, "b": {"occurrence": "Bracket", "face": [10, 505, 0]}})).unwrap_err().to_string()
+ };
+ // Not on an edge; a face the edge doesn't bound.
+ assert!(bad(&mut s, json!({"occurrence": "Panel", "edge": [200, 150, 2]})).contains("no edge there"));
+ assert!(bad(&mut s, json!({"occurrence": "Panel", "edge": [200, 0, 2], "on": [200, 150, 0]})).contains("doesn't bound"));
+ // A design whose edge name no longer finds anything: the joint is left out with the reason.
+ run(
+ &mut s,
+ "joint.create",
+ json!({"type": "rigid", "a": {"occurrence": "Panel", "edge": [200, 0, 2]}, "b": {"occurrence": "Bracket", "face": [10, 505, 0]}, "name": "J"}),
+ );
+ let mut doc = (*s.doc).clone();
+ if let Some(j) = doc.assembly.joints.first_mut()
+ && let solidcraft_doc::joints::Snap::Edge { edge, .. } = &mut j.a.snap
+ {
+ *edge = Some("F999:nothing|F998:nowhere".into());
+ }
+ *s.doc_mut() = doc;
+ let r = run(&mut s, "joint.solve", json!({}));
+ assert!(r["errors"][0]["why"].as_str().is_some_and(|w| w.contains("no longer exists")), "{r}");
+}
diff --git a/crates/engine/src/cmd/joint_frames_tests.rs b/crates/engine/src/cmd/joint_frames_tests.rs
new file mode 100644
index 0000000000..c0d2cc06bc
--- /dev/null
+++ b/crates/engine/src/cmd/joint_frames_tests.rs
@@ -0,0 +1,96 @@
+//! A joint origin on a face or a hole keeps its turn about z as the geometry tilts.
+
+use serde_json::{Value, json};
+use solidcraft_geom::Vec3;
+
+use super::tests::{occ, run};
+use crate::Session;
+
+/// A 40 x 40 x 2 plate in component Panel, turned about Y by the `tilt` parameter (a Move feature),
+/// and a 10 x 4 x 4 bar in component Bar, long along its X.
+fn tilted(tilt: f64) -> Session {
+ let mut s = Session::default();
+ run(&mut s, "parameters.add", json!({"name": "tilt", "expression": format!("{tilt} deg")}));
+ run(&mut s, "component.create", json!({"name": "Panel"}));
+ run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 2, "corner": [-20, -20, 0]}));
+ let plate = s.model.state().bodies.last().map(|b| b.name.clone()).unwrap_or_default();
+ run(&mut s, "solid.move", json!({"bodies": [plate], "axis": [0, 1, 0], "angle": "tilt"}));
+ run(&mut s, "component.activate", json!({"component": "root"}));
+ run(&mut s, "component.create", json!({"name": "Bar"}));
+ run(&mut s, "solid.box", json!({"length": 10, "width": 4, "height": 4, "corner": [100, 0, 0]}));
+ s
+}
+
+/// A point on the plate's top face (the largest face facing up).
+fn top(s: &mut Session) -> Value {
+ let body = s.model.state().bodies.first().map(|b| b.name.clone()).unwrap_or_default();
+ let faces = run(s, "model.faces", json!({"body": body}));
+ let best = faces["faces"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter(|f| f["plane_normal"][2].as_f64().is_some_and(|z| z > 0.3))
+ .max_by(|a, b| a["area"].as_f64().unwrap_or(0.0).total_cmp(&b["area"].as_f64().unwrap_or(0.0)))
+ .cloned()
+ .unwrap_or_default();
+ best["point"].clone()
+}
+
+/// How far the bar's long axis is turned from Y, the plate's axis of tilt (degrees, 0…90).
+fn bar_from_tilt_axis(s: &Session) -> f64 {
+ let m = solidcraft_doc::joints::occurrence_world(&s.doc, occ(s, "Bar"));
+ let x = solidcraft_doc::apply_vector(&m, Vec3::X);
+ x.dot(Vec3::Y).abs().min(1.0).acos().to_degrees()
+}
+
+#[test]
+fn a_part_on_a_tilting_face_keeps_its_turn_where_the_face_normal_crosses_0_9_along_x() {
+ // The plate starts at 60°: its normal is 0.87 along X. Past 64.2° it is over 0.9, where a
+ // frame worked out from the normal alone picks its x another way and the bar turned a
+ // right angle on the face.
+ let mut s = tilted(60.0);
+ let a = top(&mut s);
+ run(
+ &mut s,
+ "joint.create",
+ json!({"type": "rigid", "a": {"occurrence": "Panel", "face": a}, "b": {"occurrence": "Bar", "face": [105, 2, 0]}, "name": "Seat"}),
+ );
+ let start = bar_from_tilt_axis(&s);
+ for tilt in [62.0, 64.0, 66.0, 70.0, 80.0, 50.0, 30.0] {
+ run(&mut s, "parameters.change", json!({"name": "tilt", "expression": format!("{tilt} deg")}));
+ let now = bar_from_tilt_axis(&s);
+ assert!((now - start).abs() < 1e-6, "at {tilt}°: the bar is {now:.3}° from the tilt axis, {start:.3}° at first");
+ let r = run(&mut s, "joint.solve", json!({}));
+ assert_eq!(r["errors"], json!([]), "{r}");
+ }
+ // The origin keeps that x in the design.
+ let snap = s.doc.assembly.joints.first().map(|j| j.a.snap.clone());
+ assert!(snap.as_ref().and_then(solidcraft_doc::joints::Snap::frame_x).is_some(), "{snap:?}");
+}
+
+#[test]
+fn an_origin_saved_without_a_kept_x_is_placed_as_before() {
+ let mut s = tilted(30.0);
+ let a = top(&mut s);
+ run(
+ &mut s,
+ "joint.create",
+ json!({"type": "rigid", "a": {"occurrence": "Panel", "face": a}, "b": {"occurrence": "Bar", "face": [105, 2, 0]}, "name": "Seat"}),
+ );
+ let kept = bar_from_tilt_axis(&s);
+ // The same joint as an older design has it: no x kept on either side. It is placed as
+ // a frame from the normal alone places it, which here is where the kept x placed it too.
+ let mut doc = (*s.doc).clone();
+ for j in &mut doc.assembly.joints {
+ for o in [&mut j.a, &mut j.b] {
+ if let solidcraft_doc::joints::Snap::FaceCenter { x, .. } | solidcraft_doc::joints::Snap::CircleCenter { x, .. } = &mut o.snap {
+ *x = None;
+ }
+ }
+ }
+ let text = serde_json::to_string(&doc.assembly).unwrap_or_default();
+ assert!(!text.contains("\"x\""), "{text}");
+ *s.doc_mut() = doc;
+ run(&mut s, "joint.solve", json!({}));
+ assert!((bar_from_tilt_axis(&s) - kept).abs() < 1e-6);
+}
diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs
index a6e3a56073..1654fd7652 100644
--- a/crates/engine/src/cmd/joints.rs
+++ b/crates/engine/src/cmd/joints.rs
@@ -17,10 +17,10 @@ use crate::{EngineError, Result, Session};
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("joint.origin", "Joint Origin", joint_origin).at("SOLID", "CREATE").icon("joint_origin").params(
- "name?, occurrence?: id|name (default: from the pick, or the named face's component), face: [x,y,z] | \"<name>\" (centre of a planar face) | circle: [x,y,z] | \"<name>\" (centre of a round end: a point on its wall or rim, the end's centre, or the round face's name as model.faces lists it) | point: [x,y,z], z?: [x,y,z]; body?: the named face's body; end?: \"<name>\" (a circle's end: the face across its rim there; default the end nearer the pick); x?: [x,y,z] (a direction, world) | \"<face name>\" | {face: [x,y,z]} (the frame's x: a direction, a plane's normal, or the way to another hole's axis; keeps a round origin's turn). Faces are kept by name: the origin follows its face, and a circle its end, when the design changes",
+ "name?, occurrence?: id|name (default: from the pick, or the named face's component), face: [x,y,z] | \"<name>\" (centre of a planar face) | circle: [x,y,z] | \"<name>\" (centre of a round end: a point on its wall or rim, the end's centre, or the round face's name as model.faces lists it) | edge: [x,y,z] (a point on an edge of a planar face: the edge's middle, z out of the face, y into it; on?: [x,y,z] a point on the face (default: the larger planar face beside the edge); corner?: [x,y,z] near one end: the corner there, x and y along its two edges into the face; found again by name, so it follows the face as it changes size) | point: [x,y,z], z?: [x,y,z]; body?: the named face's body; end?: \"<name>\" (a circle's end: the face across its rim there; default the end nearer the pick); x?: [x,y,z] (a direction, world) | \"<face name>\" | {face: [x,y,z]} (the frame's x: a direction, a plane's normal, or the way to another hole's axis; keeps a round origin's turn). Faces are kept by name: the origin follows its face, and a circle its end, when the design changes",
),
CommandSpec::new("joint.create", "Joint", joint).at("SOLID", "ASSEMBLE").icon("joint").key("J").params(
- "type: rigid|revolute|slider|cylindrical|pin_slot|planar|ball; a, b: joint origins ({occurrence, face|circle|point: [x,y,z] in world, or face|circle: \"<face name>\"; end?, x? as joint.origin} | origin name); \
+ "type: rigid|revolute|slider|cylindrical|pin_slot|planar|ball; a, b: joint origins ({occurrence, face|circle|edge|point: [x,y,z] in world, or face|circle: \"<face name>\"; end?, x? as joint.origin} | origin name); \
values?: [angles in deg or expressions, distances]; limits?: [[min, max] | null…]; flip?: bool (default false: the origins are mated, \
b's z against a's as two faces meet; true: b's z along a's, so two origins given at one point with the same z stay as they are); \
offset?; angle?; name?; quiet?: bool (leave out dof and fixed)",
@@ -279,11 +279,11 @@ fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result<JointOrigin
if let Some((what, name)) = ["face", "circle"].iter().find_map(|k| v.get(*k).and_then(Value::as_str).map(|n| (*k, n))) {
return origin_by_name(s, v, what, name, cmd);
}
- let pick = ["face", "circle", "point"].iter().find_map(|k| v.get(*k).and_then(vec3).map(|p| (*k, p)));
+ let pick = ["face", "circle", "edge", "point"].iter().find_map(|k| v.get(*k).and_then(vec3).map(|p| (*k, p)));
let (what, world) = match (pick, v.get("frame")) {
(Some(x), _) => x,
(None, Some(f)) => ("frame", f.get("origin").and_then(vec3).ok_or_else(|| bad(cmd, "`frame` needs origin and z"))?),
- _ => return Err(bad(cmd, "a joint origin needs face, circle, point or frame [x, y, z], or a face's name")),
+ _ => return Err(bad(cmd, "a joint origin needs face, circle, edge, point or frame [x, y, z], or a face's name")),
};
let occurrence = match v.get("occurrence") {
Some(o) => occurrence_id(s, Some(o), cmd)?,
@@ -304,6 +304,10 @@ fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result<JointOrigin
let x = x_param(s, v, component, &inv, cmd)?;
if what == "face" { Snap::FaceCenter { pick, face, x } } else { Snap::CircleCenter { pick, face, end: None, x } }
}
+ "edge" => {
+ let (on, corner) = (v.get("on").and_then(vec3).map(local), v.get("corner").and_then(vec3).map(local));
+ joints::edge_snap(&s.doc, &st, component, local(world), on, corner).map_err(|e| bad(cmd, e.to_string()))?
+ }
"point" => Snap::Point { point: local(world), z: v.get("z").and_then(vec3).map(local_dir) },
_ => {
let f = v.get("frame").cloned().unwrap_or_default();
@@ -373,8 +377,11 @@ fn settle(s: &Session, mut o: JointOrigin, v: &Value, cmd: &str) -> Result<Joint
return Err(bad(cmd, format!("the round face doesn't end on face `{want}` (its ends lie on: {})", names.join(", "))));
}
}
- joints::resolve_origin(&s.doc, &st, &o).map_err(|e| bad(cmd, e.to_string()))?;
+ let m = joints::resolve_origin(&s.doc, &st, &o).map_err(|e| bad(cmd, e.to_string()))?;
joints::pin_end(&s.doc, &st, &mut o.snap);
+ // A face or circle given no `x` keeps the x it has now, so its frame doesn't turn as the face
+ // tilts.
+ o.snap = o.snap.with_frame_x(Vec3::new(m[0][0], m[0][1], m[0][2]));
Ok(o)
}
@@ -1316,10 +1323,16 @@ pub(crate) fn overlapping_pairs(boxes: &[Aabb3], limit: usize) -> (Vec<(usize, u
(pairs, skipped)
}
+#[cfg(test)]
+#[path = "joint_edge_tests.rs"]
+mod edge_tests;
#[cfg(test)]
#[path = "joints_face_tests.rs"]
mod face_tests;
#[cfg(test)]
+#[path = "joint_frames_tests.rs"]
+mod frames_tests;
+#[cfg(test)]
#[path = "joints_reach_tests.rs"]
mod reach_tests;
#[cfg(test)]
diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md
index 6672bbf1a3..b261722a54 100644
--- a/docs/book/src/guide/assemblies.md
+++ b/docs/book/src/guide/assemblies.md
@@ -28,6 +28,16 @@ made. Contact sets stop motion where bodies would pass through each other,
**Motion Study** keys joint values along a timeline, and **Interference** shows overlapping
volumes in red, lists the pairs closer than its **Clearance** and each body's nearest neighbour.
+A joint origin on a face or a hole keeps the turn it had when it was picked: when the face tilts
+(a bend angle or a rotation changing with a parameter) the part on it tilts with the face but
+doesn't spin about it.
+
+A joint origin can also sit on an edge of a flat face (`"edge": [x, y, z]`): at the edge's middle,
+pointing out of the face with its y into it, or with `"corner": [x, y, z]` at the corner near that
+point, its x and y running along the two edges into the face. The edge, the face and the corner
+are found again by name, so a bracket set 40 mm in from a panel's corner (a planar joint with
+values `[40, 40, 0]`) stays 40 mm in from that corner when the panel changes size.
+
The check behind it, `inspect.clearance`, does all of that in one call for any number of bodies,
which suits scripts and agents checking a whole assembly: