SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Joints: offsets, angles and values typed as expressions follow their parameters (#2385) (#2386)
NOWN-DEVc66e33284beb
diff --git a/crates/doc/src/format/pending/joint-expressions.rs b/crates/doc/src/format/pending/joint-expressions.rsnew file mode 100644index 0000000000..882b872979--- /dev/null+++ b/crates/doc/src/format/pending/joint-expressions.rs@@ -0,0 +1,4 @@+//! A joint keeps the expressions its offset, angle and values were typed as (`exprs`) and works+//! them out again whenever the design changes, so it follows the parameters they name. Older+//! designs need no transformation: a joint without `exprs` keeps its numbers 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.rsindex 6aa54eeec2..ff84addcd9 100644--- a/crates/doc/src/joints.rs+++ b/crates/doc/src/joints.rs@@ -260,6 +260,92 @@ pub struct Joint {pub angle: f64,#[serde(default, skip_serializing_if = "std::ops::Not::not")]pub suppressed: bool,+ /// The expressions the offset, the angle and the values were typed as: they are worked out+ /// again whenever the design changes, so a joint follows the parameters it is defined by.+ #[serde(default, skip_serializing_if = "JointExprs::is_empty")]+ pub exprs: JointExprs,+}++/// Expressions a joint's numbers follow (over the design's parameters): the offset (a length),+/// the angle and each value (angles or lengths as the joint's values are). A number typed in+/// place of one drops it.+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+pub struct JointExprs {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub offset: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub angle: Option<String>,+ /// By value index, as in `Joint::values`.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub values: Vec<Option<String>>,+}++impl JointExprs {+ pub fn is_empty(&self) -> bool {+ self.offset.is_none() && self.angle.is_none() && self.values.iter().all(Option::is_none)+ }++ /// The expression value `i` follows.+ pub fn value(&self, i: usize) -> Option<&str> {+ self.values.get(i).and_then(Option::as_deref)+ }++ /// Value `i` follows `e` (or nothing).+ pub fn set_value(&mut self, i: usize, e: Option<String>) {+ if e.is_some() && self.values.len() <= i {+ self.values.resize(i + 1, None);+ }+ if let Some(slot) = self.values.get_mut(i) {+ *slot = e;+ }+ while self.values.last().is_some_and(Option::is_none) {+ self.values.pop();+ }+ }+}++/// Largest offset or value an expression may give a joint (mm, or radians for an angle).+const MAX_EXPR_VALUE: f64 = 1e9;++/// A joint's offset, angle and values worked out from its expressions (those without one keep+/// their numbers), or why one can't be: an unknown name, a wrong unit, or a number too large.+pub fn expressed(doc: &Document, j: &Joint) -> Result<(f64, f64, Vec<f64>)> {+ let eval = |e: &str, kind: crate::expr::Kind, what: &str| -> Result<f64> {+ let v = doc.eval(e, kind).map_err(|err| DocError::Invalid(format!("joint {}: {what} `{e}`: {err}", j.name)))?;+ if v.is_finite() && v.abs() < MAX_EXPR_VALUE { Ok(v) } else { Err(DocError::Invalid(format!("joint {}: {what} `{e}` gives {v}", j.name))) }+ };+ let x = &j.exprs;+ let offset = match &x.offset {+ Some(e) => eval(e, crate::expr::Kind::Length, "offset")?,+ None => j.offset,+ };+ let angle = match &x.angle {+ Some(e) => eval(e, crate::expr::Kind::Angle, "angle")?,+ None => j.angle,+ };+ let mut values = j.values.clone();+ for (i, e) in x.values.iter().enumerate().take(j.kind.dofs().len()) {+ let Some(e) = e else { continue };+ let kind = if j.kind.is_angle(i) { crate::expr::Kind::Angle } else { crate::expr::Kind::Length };+ let name = j.kind.dofs().get(i).copied().unwrap_or("value");+ let v = eval(e, kind, name)?;+ if values.len() <= i {+ values.resize(i + 1, 0.0);+ }+ if let Some(slot) = values.get_mut(i) {+ *slot = v;+ }+ }+ Ok((offset, angle, values))+}++/// Values the loop solver leaves alone: those a motion link sets and those an expression does.+fn set_values(asm: &Assembly) -> BTreeSet<(u64, usize)> {+ let mut set: BTreeSet<(u64, usize)> = asm.links.iter().map(|l| (l.b, l.ib)).collect();+ for j in &asm.joints {+ set.extend(j.exprs.values.iter().enumerate().filter(|(_, e)| e.is_some()).map(|(i, _)| (j.id, i)));+ }+ set}/// Value of joint `b` (index `ib`) = ratio · value of joint `a` (index `ia`) + offset, or for a@@ -446,6 +532,49 @@ pub struct Assembly {}impl Assembly {+ /// Every expression the joints and motion links keep, with the joint (or the driven joint of+ /// a link) and what it sets: `offset`, `angle`, a value's name, or a coupling's length.+ pub fn exprs(&self) -> Vec<(u64, String, &str)> {+ let mut out = Vec::new();+ for j in &self.joints {+ let x = &j.exprs;+ out.extend(x.offset.as_deref().map(|e| (j.id, "offset".to_string(), e)));+ out.extend(x.angle.as_deref().map(|e| (j.id, "angle".to_string(), e)));+ for (i, e) in x.values.iter().enumerate() {+ if let Some(e) = e {+ out.push((j.id, j.kind.dofs().get(i).copied().unwrap_or("value").to_string(), e.as_str()));+ }+ }+ }+ for l in &self.links {+ for s in l.coupling.as_ref().map(Coupling::sizes).unwrap_or_default() {+ if let Size::Expr(e) = s {+ out.push((l.b, "coupling".to_string(), e.as_str()));+ }+ }+ }+ out+ }++ /// The expressions of `exprs`, to rewrite (a renamed parameter).+ pub fn exprs_mut(&mut self) -> Vec<&mut String> {+ let mut out = Vec::new();+ for j in &mut self.joints {+ let x = &mut j.exprs;+ out.extend(x.offset.as_mut());+ out.extend(x.angle.as_mut());+ out.extend(x.values.iter_mut().flatten());+ }+ for l in &mut self.links {+ for s in l.coupling.as_mut().map(Coupling::sizes_mut).unwrap_or_default() {+ if let Size::Expr(e) = s {+ out.push(e);+ }+ }+ }+ out+ }+pub fn is_empty(&self) -> bool {self.joints.is_empty()&& self.origins.is_empty()@@ -858,7 +987,7 @@ fn close_loops(tree: &Tree, closing: &[u64], asm: &Assembly, held: &Held, vals:if closing.len() > MAX_LOOPS {return (Values::new(), stuck);}- let linked: BTreeSet<(u64, usize)> = asm.links.iter().map(|l| (l.b, l.ib)).collect();+ let linked = set_values(asm);let groups = loop_groups(tree, closing, asm, &linked);let spent = std::cell::Cell::new(0usize);for (group, around, touches) in &groups {@@ -1053,7 +1182,7 @@ fn loop_dof(tree: &Tree, closing: &[u64], asm: &Assembly, vals: &Values, dof: &mif closing.len() > MAX_LOOPS {return;}- let linked: BTreeSet<(u64, usize)> = asm.links.iter().map(|l| (l.b, l.ib)).collect();+ let linked = set_values(asm);let groups = loop_groups(tree, closing, asm, &linked);// The joints loops depend on: those around them, those whose values they read, and those a// motion link carries any of these values into.@@ -1466,6 +1595,14 @@ fn build<'a>(doc: &'a Document, st: &ModelState, vals: &Values, sol: &mut Soluti// Joint frames in component coordinates (errors leave the joint out).let mut frames: BTreeMap<u64, (Mat, Mat)> = BTreeMap::new();for j in &joints {+ // A joint whose expressions can't be worked out (a parameter gone) is left out rather+ // than placed by numbers that no longer say what it was defined by.+ if !j.exprs.is_empty()+ && let Err(e) = expressed(doc, j)+ {+ sol.errors.push((j.id, j.name.clone(), e.to_string()));+ continue;+ }match (resolve_origin(doc, st, &j.a), resolve_origin(doc, st, &j.b)) {(Ok(fa), Ok(fb)) => {frames.insert(j.id, (fa, fb));@@ -1631,6 +1768,7 @@ mod tests {offset: 0.0,angle: 0.0,suppressed: false,+ exprs: Default::default(),}).collect();let links =diff --git a/crates/doc/src/joints_cam.rs b/crates/doc/src/joints_cam.rsindex 6d8454ae5a..e0ad1095d2 100644--- a/crates/doc/src/joints_cam.rs+++ b/crates/doc/src/joints_cam.rs@@ -967,6 +967,7 @@ mod tests {offset: 0.0,angle: 0.0,suppressed: false,+ exprs: Default::default(),};let occ = |id: u64, grounded: bool| crate::Occurrence { id, component: id, parent: 0, name: format!("O{id}"), transform: IDENTITY, grounded };// 1 frame (grounded), 2 cam, 3-6 a rigid chain to the guide 7, 8 the piston, 9 crank, 10 rod.diff --git a/crates/doc/src/params.rs b/crates/doc/src/params.rsindex 76ab07461b..25e0fc2c4f 100644--- a/crates/doc/src/params.rs+++ b/crates/doc/src/params.rs@@ -486,6 +486,9 @@ pub enum ParamUser {Dimension { feature: u64, name: String, constraint: String },/// A configured column or an expression saved in a configuration row.Configuration { row: Option<String>, column: String },+ /// A joint's offset, angle or value, or a motion link's gear, rack or screw length (`input`+ /// says which; a link is named by the joint it drives).+ Joint { joint: u64, name: String, input: String },}impl ParamUser {@@ -498,6 +501,7 @@ impl ParamUser {Some(row) => format!("configuration `{row}` ({column})"),None => format!("configuration column {column}"),},+ ParamUser::Joint { name, input, .. } => format!("joint {name} ({input})"),}}}@@ -615,6 +619,12 @@ impl Document {}}}+ for (joint, input, e) in self.assembly.exprs() {+ if expr::references(e).iter().any(|r| r == name) {+ let jname = self.assembly.joints.iter().find(|j| j.id == joint).map(|j| j.name.clone()).unwrap_or_else(|| joint.to_string());+ out.push(ParamUser::Joint { joint, name: jname, input });+ }+ }out}@@ -719,6 +729,13 @@ impl Document {}}}+ for e in self.assembly.exprs_mut() {+ let r = expr::rename_reference(e, old, new);+ if r != *e {+ *e = r;+ n += 1;+ }+ }if let Some(c) = self.param_comments.remove(old) {self.param_comments.insert(new.to_string(), c);}diff --git a/crates/engine/src/cmd/component_clone_assembly_tests.rs b/crates/engine/src/cmd/component_clone_assembly_tests.rsindex da1d309985..cb0a2e08eb 100644--- a/crates/engine/src/cmd/component_clone_assembly_tests.rs+++ b/crates/engine/src/cmd/component_clone_assembly_tests.rs@@ -22,6 +22,7 @@ fn joint(id: u64, a: u64, b: u64) -> Joint {offset: 2.0,angle: 0.1,suppressed: false,+ exprs: Default::default(),}}diff --git a/crates/engine/src/cmd/file_import.rs b/crates/engine/src/cmd/file_import.rsindex 399b4f5df3..f1cd7fe353 100644--- a/crates/engine/src/cmd/file_import.rs+++ b/crates/engine/src/cmd/file_import.rs@@ -369,6 +369,7 @@ fn add_rigid_joints(s: &mut Session, pairs: &[(u64, u64, Mat)]) -> Result<Vec<u6offset: 0.0,angle: 0.0,suppressed: false,+ exprs: Default::default(),}}).collect();diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rsindex 1654fd7652..7fe68860ed 100644--- a/crates/engine/src/cmd/joints.rs+++ b/crates/engine/src/cmd/joints.rs@@ -8,7 +8,7 @@ use std::collections::{BTreeMap, BTreeSet};use serde_json::{Value, json};use solidcraft_doc::expr::Kind;use solidcraft_doc::joints::cam::{self, Cam, CamProfile, Follower};-use solidcraft_doc::joints::{self, Coupling, Joint, JointKind, JointOrigin, MotionLink, NamedOrigin, Size, Snap, XRef};+use solidcraft_doc::joints::{self, Coupling, Joint, JointExprs, JointKind, JointOrigin, MotionLink, NamedOrigin, Size, Snap, XRef};use solidcraft_geom::{Aabb3, Vec3};use super::CommandSpec;@@ -23,7 +23,9 @@ pub static COMMANDS: &[CommandSpec] = &["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)",+ offset?: mm or an expression; angle?: deg or an expression; name?; quiet?: bool (leave out dof and fixed). An expression (text) is \+ kept with the joint and worked out again whenever the design changes, so the joint follows the parameters it names; a joint whose \+ expression no longer works out (a parameter deleted) is left out of the solve with the reason in its errors",),CommandSpec::new("joint.as_built", "As-Built Joint", as_built).at("SOLID", "ASSEMBLE").icon("as_built").params("type, a: occurrence, b: occurrence (stay where they are); at?: joint origin (default: b's origin) — the joint's frame; \@@ -31,7 +33,7 @@ pub static COMMANDS: &[CommandSpec] = &[),CommandSpec::new("joint.rigid_group", "Rigid Group", rigid_group).at("SOLID", "ASSEMBLE").icon("rigid_group").params("occurrences: [ids or names] (move together, as they are)"),CommandSpec::new("joint.drive", "Drive Joints", drive).at("SOLID", "ASSEMBLE").icon("drive").params(- "joint: id|name; value | values: [angles in deg or expressions, distances] (values not given keep theirs; clamped to the limits; the other joints of a \+ "joint: id|name; value | values: [angles in deg or expressions, distances] (values not given keep theirs; a value driven drops the expression joint.create gave it; clamped to the limits; the other joints of a \closed loop follow, and the motion stops where the loop can no longer close → stopped_by_loop); quiet?: bool (leave out dof \and fixed) → values: [{name, value, unit: deg|mm, limits}] as joint.list gives them; moved: whether any occurrence moved; \reason: why the joint can move nothing (suppressed, its origins lost, or its chain joined to nothing grounded → unconnected: \@@ -65,10 +67,12 @@ pub static COMMANDS: &[CommandSpec] = &["a: the cam's joint (revolute); b: the follower's joint, a slider (a translating follower) or a revolute (an oscillating one), b driven by a; profile: {sketch: id|name, index?: the profile (default: the largest)} | {edges: [[x,y,z]…] (points on edges of the cam's bodies forming one closed loop, world), occurrence?}: the cam's outline, in a plane square to its axis, read again whenever the design changes; follower?: knife|roller|flat (default knife; flat: a face square to a slider's line); radius?: the roller's radius (mm, an expression or {circle: [x,y,z], occurrence?}: the roller's round face, which is its tip too); tip?: a joint origin where the follower touches: its knife's point or its roller's centre, such as {circle: [x,y,z]} on the roller (needed for an oscillating follower; a translating one's line runs through it, by default along its slider's axis); flip?: bool (ride the cam from the other side than the one the follower is on now); link?: index (replace that motion link) → link, lift: {min, max, rise, unit} (b's travel over a turn of the cam), reverse (the side it rides from), follower_offset (mm: how far a translating follower's line passes from the cam's axis); b keeps where it is",),CommandSpec::new("joint.limits", "Joint Limits", limits).icon("joint").params("joint; index?: value index (default 0); min?, max? (omit both to clear)"),- CommandSpec::new("joint.edit", "Edit Joint", edit).icon("edit").params("joint; type?, flip?, offset?, angle?, suppressed?, name?"),+ CommandSpec::new("joint.edit", "Edit Joint", edit)+ .icon("edit")+ .params("joint; type?, flip?, offset?, angle? (a number, or an expression the joint then follows), suppressed?, name?"),CommandSpec::new("joint.delete", "Delete Joint", delete).icon("delete").params("joint: id|name (or origin: name, link: index)"),CommandSpec::new("joint.list", "List Joints", list).icon("list").noundo().params(- "→ joints (type, occurrences, values, limits), origins, links, degrees of freedom, conflicts, floating: [{occurrences, joints}] \+ "→ joints (type, occurrences, values, limits; expressions: {offset?, angle?, values?} when they were typed as expressions), origins, links, degrees of freedom, conflicts, floating: [{occurrences, joints}] \(joint chains joined to nothing grounded: the solver places none of them, so driving them moves nothing)",),CommandSpec::new("joint.solve", "Solve Joints", solve_cmd).icon("compute").params("re-place the occurrences from the joints → conflicts, errors, dof"),@@ -80,10 +84,39 @@ pub static COMMANDS: &[CommandSpec] = &[/// Re-solve the joints and move the occurrences they place (after any edit). Gears, racks and/// screws first take their ratios from the radii and pitches they are defined by.pub fn resolve(s: &mut Session) -> joints::Solution {+ reexpress(s);recouple(s);resolve_holding(s, &BTreeMap::new())}+/// Work out the offsets, angles and values joints were given as expressions again (a parameter+/// may have changed). One that can't be worked out (its parameter gone) keeps its numbers; the+/// solve leaves that joint out and says why.+fn reexpress(s: &mut Session) {+ let changed: Vec<(usize, (f64, f64, Vec<f64>))> = s+ .doc+ .assembly+ .joints+ .iter()+ .enumerate()+ .filter(|(_, j)| !j.exprs.is_empty())+ .filter_map(|(i, j)| {+ let (o, a, mut q) = joints::expressed(&s.doc, j).ok()?;+ joints::clamp(j, &mut q);+ ((o, a) != (j.offset, j.angle) || q != j.values).then_some((i, (o, a, q)))+ })+ .collect();+ if changed.is_empty() {+ return;+ }+ let doc = s.doc_mut();+ for (i, (o, a, q)) in changed {+ if let Some(j) = doc.assembly.joints.get_mut(i) {+ (j.offset, j.angle, j.values) = (o, a, q);+ }+ }+}+/// Work out the ratios (and cam tables) of the coupled motion links again (a radius, a parameter/// or a cam's profile may have changed). A coupling that can't be worked out (its face gone)/// keeps its last ratio and table; `joint.list` says why.@@ -449,6 +482,28 @@ pub(crate) fn value(s: &Session, v: &Value, angle: bool, cmd: &str) -> Result<f6s.doc.eval(&e, kind).map_err(|e| bad(cmd, e.to_string()))}+/// The expression a number was typed as, kept so the joint follows the parameters it names+/// (`None` for a plain number, or for text that names no parameter, such as `"5 mm"`).+fn typed(v: Option<&Value>) -> Option<String> {+ match v {+ Some(Value::String(t)) if !solidcraft_doc::expr::references(t).is_empty() => Some(t.trim().to_string()),+ _ => None,+ }+}++/// The expressions among `values` (or `value`), by index.+fn value_exprs(p: &Value) -> Vec<Option<String>> {+ let mut out: Vec<Option<String>> = match (p.get("values"), p.get("value")) {+ (Some(Value::Array(a)), _) => a.iter().map(|v| typed(Some(v))).collect(),+ (_, Some(v)) => vec![typed(Some(v))],+ _ => Vec::new(),+ };+ while out.last().is_some_and(Option::is_none) {+ out.pop();+ }+ out+}+fn values_param(s: &Session, p: &Value, kind: JointKind, cmd: &str) -> Result<Vec<f64>> {let n = kind.dofs().len();let list: Vec<Value> = match (p.get("values"), p.get("value")) {@@ -589,6 +644,7 @@ fn joint(s: &mut Session, p: &Value) -> Result<Value> {offset,angle,suppressed: false,+ exprs: JointExprs { offset: typed(p.get("offset")), angle: typed(p.get("angle")), values: value_exprs(p) },};add_joint(s, j, p)}@@ -622,6 +678,7 @@ fn as_built(s: &mut Session, p: &Value) -> Result<Value> {offset: 0.0,angle: 0.0,suppressed: false,+ exprs: Default::default(),};add_joint(s, j, p)}@@ -666,6 +723,11 @@ fn drive(s: &mut Session, p: &Value) -> Result<Value> {joints::clamp(j, &mut q);// Moved as far toward `q` as contact sets and closed loops allow. Values left out of// `values` are not driven: in a closed loop they follow.+ // Driving moves the joint by hand: the values driven drop their expressions (an expression+ // given here is worked out once, as contact or a loop may stop the motion short of it).+ for i in 0..given.min(kind.dofs().len()) {+ j.exprs.set_value(i, None);+ }let before = super::motion::positions(s);let r = super::motion::drive_joint(s, id, q, given)?;let sol = joints::solve(&s.doc, &s.model.state());@@ -1126,15 +1188,26 @@ fn edit(s: &mut Session, p: &Value) -> Result<Value> {let doc = s.doc_mut();let Some(j) = doc.assembly.joints.iter_mut().find(|j| j.id == id) else { return Err(bad(cmd, "joint")) };if let Some(k) = kind {+ let was = j.kind;j.kind = k;j.values.resize(k.dofs().len(), 0.0);j.limits.resize(k.dofs().len(), None);+ j.exprs.values.truncate(k.dofs().len());+ // A value that changes unit with the type (a slide becoming a turn) drops its expression,+ // which would no longer work out and leave the joint out of the solve.+ for i in 0..j.exprs.values.len() {+ if was.is_angle(i) != k.is_angle(i) {+ j.exprs.set_value(i, None);+ }+ }}if let Some(o) = offset {j.offset = o;+ j.exprs.offset = typed(p.get("offset"));}if let Some(a) = angle {j.angle = a;+ j.exprs.angle = typed(p.get("angle"));}if let Some(f) = bool_(p, "flip") {j.flip = f;@@ -1192,8 +1265,12 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {.map(|j| {let named = named_values(j, vals.get(&j.id).map(Vec::as_slice).unwrap_or_default());let world = |o: &JointOrigin| s.doc.origin_world(&st, o).ok().map(|m| json!({"origin": [m[3][0], m[3][1], m[3][2]], "z": [m[2][0], m[2][1], m[2][2]]}));- json!({"id": j.id, "name": j.name, "type": j.kind, "a": j.a.occurrence, "b": j.b.occurrence, "values": named,- "flip": j.flip, "offset": j.offset, "suppressed": j.suppressed, "visible": s.joint_visible(j.id), "frame_a": world(&j.a), "frame_b": world(&j.b)})+ let mut out = json!({"id": j.id, "name": j.name, "type": j.kind, "a": j.a.occurrence, "b": j.b.occurrence, "values": named,+ "flip": j.flip, "offset": j.offset, "suppressed": j.suppressed, "visible": s.joint_visible(j.id), "frame_a": world(&j.a), "frame_b": world(&j.b)});+ if !j.exprs.is_empty() {+ out["expressions"] = json!(j.exprs);+ }+ out}).collect();let links: Vec<Value> = s@@ -1327,6 +1404,9 @@ pub(crate) fn overlapping_pairs(boxes: &[Aabb3], limit: usize) -> (Vec<(usize, u#[path = "joint_edge_tests.rs"]mod edge_tests;#[cfg(test)]+#[path = "joints_exprs_tests.rs"]+mod exprs_tests;+#[cfg(test)]#[path = "joints_face_tests.rs"]mod face_tests;#[cfg(test)]diff --git a/crates/engine/src/cmd/joints_exprs_tests.rs b/crates/engine/src/cmd/joints_exprs_tests.rsnew file mode 100644index 0000000000..d3cdfa05b4--- /dev/null+++ b/crates/engine/src/cmd/joints_exprs_tests.rs@@ -0,0 +1,146 @@+//! Joints whose offset, angle or values are typed as expressions follow the parameters they name.++use serde_json::json;+use solidcraft_geom::Vec3;++use super::tests::{occ, place, run};+use crate::Session;++/// Two 10 mm cubes in components A (grounded) and B, a `gap` and a `turn` parameter.+fn cubes() -> Session {+ let mut s = Session::default();+ for (name, x) in [("A", 0), ("B", 20)] {+ run(&mut s, "component.activate", json!({"component": "root"}));+ run(&mut s, "component.create", json!({"name": name}));+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]}));+ }+ let o = occ(&s, "A");+ run(&mut s, "occurrence.ground", json!({"occurrence": o, "grounded": true}));+ run(&mut s, "parameters.add", json!({"name": "gap", "expression": "5 mm"}));+ run(&mut s, "parameters.add", json!({"name": "turn", "expression": "0 deg"}));+ s+}++/// Where B's bottom corner (20, 0, 0 in B) is.+fn b_corner(s: &Session) -> Vec3 {+ place(s, "B", Vec3::new(20.0, 0.0, 0.0))+}++fn near(a: Vec3, b: Vec3) -> bool {+ a.dist(b) < 1e-6+}++#[test]+fn an_offset_and_an_angle_typed_as_expressions_follow_their_parameters() {+ let mut s = cubes();+ run(+ &mut s,+ "joint.create",+ json!({"type": "rigid", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "offset": "gap", "angle": "turn", "name": "Seat"}),+ );+ let z = |s: &Session| place(s, "B", Vec3::new(25.0, 5.0, 0.0)).z;+ assert!((z(&s) - 15.0).abs() < 1e-6, "{}", z(&s));+ // The gap changes: B rides up with it, without touching the joint.+ run(&mut s, "parameters.change", json!({"name": "gap", "expression": "12 mm"}));+ assert!((z(&s) - 22.0).abs() < 1e-6, "{}", z(&s));+ // A parameter the gap is worked out from changes too.+ run(&mut s, "parameters.add", json!({"name": "base", "expression": "2 mm"}));+ run(&mut s, "parameters.change", json!({"name": "gap", "expression": "base * 3"}));+ assert!((z(&s) - 16.0).abs() < 1e-6, "{}", z(&s));+ // The angle turns B about the seat's axis (its centre stays, its corner swings round).+ let centre = place(&s, "B", Vec3::new(25.0, 5.0, 0.0));+ let before = b_corner(&s);+ run(&mut s, "parameters.change", json!({"name": "turn", "expression": "90 deg"}));+ assert!(near(place(&s, "B", Vec3::new(25.0, 5.0, 0.0)), centre));+ let after = b_corner(&s);+ assert!((before - centre).dot(after - centre).abs() < 1e-6, "{before:?} {after:?}");+ // The design keeps the expressions, so they are there after saving and opening.+ let j = s.doc.assembly.joints.first().cloned().unwrap_or_else(|| panic!("no joint"));+ assert_eq!((j.exprs.offset.as_deref(), j.exprs.angle.as_deref()), (Some("gap"), Some("turn")));+ let saved = serde_json::to_value(&j).unwrap_or_default();+ assert_eq!((&saved["exprs"]["offset"], &saved["exprs"]["angle"]), (&json!("gap"), &json!("turn")), "{saved}");+ let listed = run(&mut s, "joint.list", json!({}));+ assert_eq!(listed["joints"][0]["expressions"]["offset"], json!("gap"), "{listed}");+ // A number typed over the expression drops it: B stays when the gap changes again.+ run(&mut s, "joint.edit", json!({"joint": "Seat", "offset": 4}));+ run(&mut s, "parameters.change", json!({"name": "gap", "expression": "30 mm"}));+ assert!((z(&s) - 14.0).abs() < 1e-6, "{}", z(&s));+ assert!(s.doc.assembly.joints.first().is_some_and(|j| j.exprs.offset.is_none() && j.exprs.angle.is_some()));+}++#[test]+fn a_joint_value_typed_as_an_expression_follows_it_until_it_is_driven() {+ let mut s = cubes();+ run(+ &mut s,+ "joint.create",+ json!({"type": "slider", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "values": ["gap"], "limits": [[0, 20]], "name": "Rail"}),+ );+ let z = |s: &Session| place(s, "B", Vec3::new(25.0, 5.0, 0.0)).z;+ assert!((z(&s) - 15.0).abs() < 1e-6, "{}", z(&s));+ run(&mut s, "parameters.change", json!({"name": "gap", "expression": "8 mm"}));+ assert!((z(&s) - 18.0).abs() < 1e-6, "{}", z(&s));+ // Past the limits it is held at them, like a typed value.+ run(&mut s, "parameters.change", json!({"name": "gap", "expression": "50 mm"}));+ assert!((z(&s) - 30.0).abs() < 1e-6, "{}", z(&s));+ // Driven by hand it drops the expression (contact or a loop may stop it short of any value).+ run(&mut s, "joint.drive", json!({"joint": "Rail", "value": 1}));+ run(&mut s, "parameters.change", json!({"name": "gap", "expression": "9 mm"}));+ assert!((z(&s) - 11.0).abs() < 1e-6, "{}", z(&s));+ assert!(s.doc.assembly.joints.first().is_some_and(|j| j.exprs.is_empty()));+}++#[test]+fn renaming_a_parameter_carries_into_joints_and_deleting_it_is_refused() {+ let mut s = cubes();+ run(&mut s, "joint.create", json!({"type": "rigid", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "offset": "gap + 1", "name": "Seat"}));+ run(&mut s, "parameters.rename", json!({"name": "gap", "new_name": "clearance"}));+ assert_eq!(s.doc.assembly.joints.first().and_then(|j| j.exprs.offset.clone()).as_deref(), Some("clearance + 1"));+ run(&mut s, "parameters.change", json!({"name": "clearance", "expression": "9 mm"}));+ assert!((place(&s, "B", Vec3::new(25.0, 5.0, 0.0)).z - 20.0).abs() < 1e-6);+ // The joint uses it, so it can't be deleted from under the joint.+ let e = s.execute("parameters.delete", &json!({"name": "clearance"})).unwrap_err().to_string();+ assert!(e.contains("joint Seat (offset)"), "{e}");+}++#[test]+fn a_joint_whose_expression_stops_working_out_is_left_out_with_the_reason() {+ let mut s = cubes();+ run(&mut s, "joint.create", json!({"type": "rigid", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "offset": "gap", "name": "Seat"}));+ let at = b_corner(&s);+ // The gap becomes an angle: the offset no longer works out as a length. B stays where it+ // was (not thrown to an old number) and the solve says why.+ run(&mut s, "parameters.change", json!({"name": "gap", "expression": "30 deg", "unit": "deg"}));+ assert!(near(b_corner(&s), at), "{:?}", b_corner(&s));+ let r = run(&mut s, "joint.solve", json!({}));+ let why = r["errors"][0]["why"].as_str().unwrap_or_default().to_string();+ assert!(why.contains("Seat") && why.contains("offset"), "{r}");+ // Fixed again, the joint places B again.+ run(&mut s, "parameters.change", json!({"name": "gap", "expression": "2 mm", "unit": "mm"}));+ assert!((place(&s, "B", Vec3::new(25.0, 5.0, 0.0)).z - 12.0).abs() < 1e-6);+ assert_eq!(run(&mut s, "joint.solve", json!({}))["errors"], json!([]));+}++#[test]+fn a_value_that_changes_unit_with_the_joint_type_drops_its_expression() {+ let mut s = cubes();+ run(&mut s, "joint.create", json!({"type": "slider", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "values": ["gap"], "name": "Rail"}));+ // The slide becomes a turn: `gap` (a length) can't be its angle, so the turn keeps a number+ // and the joint stays in the solve.+ let r = run(&mut s, "joint.edit", json!({"joint": "Rail", "type": "revolute"}));+ assert_eq!(r["errors"], json!([]), "{r}");+ assert!(s.doc.assembly.joints.first().is_some_and(|j| j.exprs.is_empty()));+}++#[test]+fn text_that_names_no_parameter_is_kept_as_a_number() {+ let mut s = cubes();+ run(+ &mut s,+ "joint.create",+ json!({"type": "slider", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "offset": "3 mm", "angle": "0 deg", "values": ["2 * 2 mm"]}),+ );+ let j = s.doc.assembly.joints.first().cloned().unwrap_or_else(|| panic!("no joint"));+ assert!(j.exprs.is_empty(), "{:?}", j.exprs);+ assert!((j.offset - 3.0).abs() < 1e-12 && j.values.first().is_some_and(|v| (v - 4.0).abs() < 1e-12), "{j:?}");+}diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rsindex 9cb2d1bd45..0b8fcf5f19 100644--- a/crates/ui-egui/src/dialogs_assembly.rs+++ b/crates/ui-egui/src/dialogs_assembly.rs@@ -281,8 +281,10 @@ pub fn edit_joint(app: &SolveApp, id: u64) -> Option<Dialog> {f.editing = Some(id);f.kind = TYPES.iter().position(|t| JointKind::parse(t) == Some(j.kind)).unwrap_or(0);f.flip = j.flip;- f.angle = num(j.angle.to_degrees(), "deg");- f.offset[2] = num(j.offset, "mm");+ // An offset or angle typed as an expression shows (and is sent back) as that expression, so+ // the joint keeps following its parameters.+ f.angle = j.exprs.angle.clone().unwrap_or_else(|| num(j.angle.to_degrees(), "deg"));+ f.offset[2] = j.exprs.offset.clone().unwrap_or_else(|| num(j.offset, "mm"));f.fit_limits();for (i, l) in f.limits.iter_mut().enumerate() {if let Some(Some((lo, hi))) = j.limits.get(i) {diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rsindex fa655b6863..d163db67e8 100644--- a/crates/ui-egui/src/dialogs_assembly_tests.rs+++ b/crates/ui-egui/src/dialogs_assembly_tests.rs@@ -138,6 +138,29 @@ fn edit_joint_runs_edit_and_limits() {assert!((j.offset - 2.0).abs() < 1e-12);}+/// Edit Joint shows an offset typed as an expression as that expression, and OK keeps it; the+/// dialog's plain numbers keep no expression.+#[test]+fn edit_joint_keeps_an_offset_typed_as_an_expression() {+ let mut app = two_boxes();+ let (a, b) = (occ(&app, "A"), occ(&app, "B"));+ app.run("parameters.add", json!({"name": "gap", "expression": "3 mm"})).unwrap();+ let (fa, fb) = (json!({"occurrence": a, "face": [10, 10, 10]}), json!({"occurrence": b, "face": [40, 10, 0]}));+ app.run("joint.create", json!({"type": "rigid", "a": fa, "b": fb, "offset": "gap", "angle": "0 deg"})).unwrap();+ let id = app.session.doc.assembly.joints[0].id;+ let mut d = edit_joint(&app, id).unwrap();+ if let Kind::Assembly(Asm::Joint(f)) = &mut d.kind {+ assert_eq!(f.offset[2], "gap");+ f.flip = true;+ }+ for (id, p) in apply_commands(&app, &d).unwrap() {+ app.run(&id, p).unwrap();+ }+ let j = &app.session.doc.assembly.joints[0];+ assert!(j.flip);+ assert_eq!((j.exprs.offset.as_deref(), j.exprs.angle.as_deref()), (Some("gap"), None));+}+/// As-built joints and rigid groups take components from body picks; New Component makes one/// from bodies when bodies are picked.#[test]diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.mdindex b261722a54..3280f83c8e 100644--- a/docs/book/src/guide/assemblies.md+++ b/docs/book/src/guide/assemblies.md@@ -38,6 +38,14 @@ point, its x and y running along the two edges into the face. The edge, the faceare found again by name, so a bracket set 40 mm in from a panel's corner (a planar joint withvalues `[40, 40, 0]`) stays 40 mm in from that corner when the panel changes size.+A joint's offset, angle and values can be typed as expressions over the design's parameters+(`"offset": "gap + 2"`, `"values": ["travel"]`). The joint keeps them and works them out again+whenever the design changes, so a part seated `gap` above a panel moves with `gap`. Renaming a+parameter carries into the joints that use it, and deleting one they use is refused. If an+expression stops working out (say a parameter becomes an angle), the joint is left out of the+solve and `joint.solve` gives the reason, instead of placing the part from old numbers. Typing a+plain number, or driving the value, drops that expression.+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: