From e4d9015f68bddbdd9a0359ef8d8f83cfbb5b54de Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 19:05:28 +0200 Subject: [PATCH] sketch: points placed by expressions (#2864) * Sketch points placed by expressions over the design's parameters A point typed as an expression ("W", "H / 2") in sketch.point, sketch.line and the other point arguments is fixed where its expressions come to, and moves there again before each solve when the parameters change: an outline that follows its parameters needs no dimensions and no solve per change. The expressions are saved with the point (one pending design-format change), listed with the sketch's other expressions, and renamed with their parameters; one that cannot be worked out is refused. Co-Authored-By: Claude Opus 5.5 (1M context) * Sketch point expressions: accurate params doc, out-of-range regression test The sketch.line params said every point argument takes expressions; only those that also take a point id do (the rectangle corners, an arc's through point and the like are plain [x, y]). PointExprs' comment called its expressions mm. A test covers a parameter that puts a placed point out of range and a design file whose point expression overflows: both are errors, not crashes, and the sketch recovers. Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: bherbruck --- crates/doc/src/document.rs | 25 +++- .../pending/sketch-point-expressions.rs | 5 + crates/engine/src/cmd/sketch.rs | 76 +++++++--- crates/engine/src/cmd/sketch_create.rs | 28 ++-- .../engine/src/cmd/sketch_point_expr_tests.rs | 131 ++++++++++++++++++ crates/sketch/src/construct_tests.rs | 2 +- crates/sketch/src/decompose_tests.rs | 2 +- crates/sketch/src/lib.rs | 3 +- crates/sketch/src/link.rs | 5 +- crates/sketch/src/model.rs | 30 +++- 10 files changed, 267 insertions(+), 40 deletions(-) create mode 100644 crates/doc/src/format/pending/sketch-point-expressions.rs create mode 100644 crates/engine/src/cmd/sketch_point_expr_tests.rs diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 9b5a400ec..a661404b5 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -3195,8 +3195,10 @@ impl Document { } } - /// Apply parameter values to every dimension in a sketch (in place). + /// Apply parameter values to every dimension in a sketch, and to its points placed by + /// parameters (in place). pub fn apply_dimension_values(&self, vals: &std::collections::BTreeMap, sk: &mut Sketch) -> Result<()> { + self.apply_point_values(vals, sk)?; for c in &mut sk.constraints { if let Some(p) = &c.param { let kind = if c.kind.is_angle() { Kind::Angle } else { Kind::Length }; @@ -3210,6 +3212,27 @@ impl Document { Ok(()) } + /// Move the points placed by parameters to where their expressions come to (in place). Such + /// a point is fixed, so the solve keeps it there. + pub fn apply_point_values(&self, vals: &std::collections::BTreeMap, sk: &mut Sketch) -> Result<()> { + use crate::eval::val; + for p in &mut sk.points { + let Some(exprs) = p.exprs.as_deref() else { continue }; + let mut at = p.pos; + for (e, slot, what) in [(&exprs.x, &mut at.x, "X"), (&exprs.y, &mut at.y, "Y")] { + if let Some(e) = e { + *slot = val(vals, e, Kind::Length).map_err(|error| DocError::Expr(format!("point {} {what}: {error}", p.id)))?; + } + } + if !(at.is_finite() && at.x.abs() < solidcraft_sketch::MAX_COORD && at.y.abs() < solidcraft_sketch::MAX_COORD) { + return Err(DocError::Invalid(format!("point {} is placed out of range", p.id))); + } + p.pos = at; + p.fixed = true; + } + Ok(()) + } + /// Give the texts of a sketch the numbers their expressions come to (in place): a text's /// height, place and angle that were typed as expressions. A text's outlines are rebuilt from /// its numbers when the sketch's links are refreshed, so this comes before that. A number diff --git a/crates/doc/src/format/pending/sketch-point-expressions.rs b/crates/doc/src/format/pending/sketch-point-expressions.rs new file mode 100644 index 000000000..98570f851 --- /dev/null +++ b/crates/doc/src/format/pending/sketch-point-expressions.rs @@ -0,0 +1,5 @@ +//! A sketch point can be placed by parameters: `exprs` (`x` and/or `y`, expressions over the +//! design's parameters, in the design's units when a number in them has no unit) on a point that +//! is `fixed` where they come to, and moved there again before each solve when the parameters +//! change. Older designs need no transformation: their points have no `exprs`. The last release +//! asks for an update instead of opening a design with this format number. diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 34468fcd0..e2ca211ab 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use solidcraft_doc::{FeatureKind, PlaneRef, expr::Kind}; use solidcraft_geom::{Plane, Vec2, Vec3}; -use solidcraft_sketch::{Analysis, Budget, ConstraintKind, CurveKind, Hold, Sketch, SolveReport, solve, solve_with}; +use solidcraft_sketch::{Analysis, Budget, ConstraintKind, CurveKind, Hold, PointExprs, Sketch, SolveReport, solve, solve_with}; use super::{CommandSpec, in_sketch}; use crate::params::{bad, bool_, expr, num, req_vec2, str_, string_list, vec2, vec3}; @@ -37,7 +37,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("line") .key("L") .enabled(in_sketch) - .params(concat!("points: [[x,y] | \"l1.end\" | {at, ref}…], closed?: bool, construction?: bool, ids?: [..], infer?: bool (add horizontal/vertical)", connect_doc!(), created_doc!())), + .params(concat!("points: [[x,y] | \"l1.end\" | {at, ref}…] (x and y each a number or an expression over the design's parameters, \"W / 2\": such a point is fixed where it comes to and follows the parameters; likewise wherever a point argument also takes a point id), closed?: bool, construction?: bool, ids?: [..], infer?: bool (add horizontal/vertical)", connect_doc!(), created_doc!())), CommandSpec::new("sketch.draw.dimensioned", "Draw Dimensioned Sketch Geometry", draw_dimensioned).icon("dimension") .enabled(in_sketch) .params(concat!("command: sketch creation command, params: object, dimensions: object of role to numeric or expression value; creates geometry and all driving dimensions atomically in one undo step", created_doc!())), @@ -109,7 +109,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("slot_overall") .enabled(in_sketch) .params(concat!("p0, p1: overall ends, width", connect_doc!(), created_doc!())), - CommandSpec::new("sketch.point", "Point", draw_point).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y], id?", connect_doc!(), created_doc!())), + CommandSpec::new("sketch.point", "Point", draw_point).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them), id?", connect_doc!(), created_doc!())), CommandSpec::new("sketch.dimension", "Sketch Dimension", dimension).at("SKETCH", "CREATE").icon("dimension").key("D").enabled(in_sketch).params( "entities: [refs], type?: auto|distance|horizontal|vertical|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them is the distance between them, above or below them horizontal, beside them vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled", ), @@ -434,10 +434,16 @@ impl PArg { } } -pub(super) fn parg(sk: &Sketch, v: &Value, cmd: &str) -> Result { +pub(super) fn parg(sk: &mut Sketch, doc: &solidcraft_doc::Document, v: &Value, cmd: &str) -> Result { if let Some(p) = vec2(v) { return Ok(PArg::At(p)); } + if let Some((at, exprs)) = expr_point(doc, v, cmd)? { + return Ok(match exprs { + Some(exprs) => PArg::Ref(add_placed_point(sk, at, exprs, None)?, at), + None => PArg::At(at), + }); + } let r = match v { Value::String(r) => Some(r.as_str()), Value::Object(o) => o.get("ref").and_then(Value::as_str), @@ -453,8 +459,34 @@ pub(super) fn parg(sk: &Sketch, v: &Value, cmd: &str) -> Result { Err(bad(cmd, "a point must be [x, y], a point id like \"l1.end\", or {at, ref}")) } -pub(super) fn req_parg(sk: &Sketch, p: &Value, k: &str, cmd: &str) -> Result { - parg(sk, p.get(k).ok_or_else(|| bad(cmd, format!("missing `{k}`")))?, cmd) +pub(super) fn req_parg(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value, k: &str, cmd: &str) -> Result { + parg(sk, doc, p.get(k).ok_or_else(|| bad(cmd, format!("missing `{k}`")))?, cmd) +} + +const POINT_MUST: &str = "a point's coordinates must be numbers or expressions over the design's parameters"; + +/// A point given as `[x, y]` with a coordinate typed as text: where it is now and, when a +/// coordinate names a parameter, the expressions that place it (none: a plain point). +pub(super) fn expr_point(doc: &solidcraft_doc::Document, v: &Value, cmd: &str) -> Result)>> { + let Some([x, y]) = v.as_array().map(Vec::as_slice) else { return Ok(None) }; + if !x.is_string() && !y.is_string() { + return Ok(None); + } + let (px, ex) = super::sketch_create::text_number(doc, x, cmd, "point x", POINT_MUST, false)?; + let (py, ey) = super::sketch_create::text_number(doc, y, cmd, "point y", POINT_MUST, false)?; + let exprs = (ex.is_some() || ey.is_some()).then_some(PointExprs { x: ex, y: ey }); + Ok(Some((Vec2::new(px, py), exprs))) +} + +/// A new point placed by parameters: fixed where its expressions come to, and moved there +/// again whenever the parameters change. +pub(super) fn add_placed_point(sk: &mut Sketch, at: Vec2, exprs: PointExprs, id: Option<&str>) -> Result { + let i = sk.add_point(at, id)?; + if let Some(q) = sk.points.get_mut(i) { + q.fixed = true; + q.exprs = Some(Box::new(exprs)); + } + Ok(i) } pub(super) fn curve_ref(sk: &Sketch, v: Option<&Value>, cmd: &str, what: &str) -> Result { @@ -764,8 +796,8 @@ fn draw_line(s: &mut Session, p: &Value) -> Result { let closed = bool_(p, "closed").unwrap_or(false); let infer = bool_(p, "infer").unwrap_or(false); let ids = string_list(p, "ids"); - let ((curves, cons), info) = draw(s, p, cmd, |sk, _| { - let args: Vec = list.iter().map(|v| parg(sk, v, cmd)).collect::>()?; + let ((curves, cons), info) = draw(s, p, cmd, |sk, doc| { + let args: Vec = list.iter().map(|v| parg(sk, doc, v, cmd)).collect::>()?; let n = args.len(); let segs = if closed { n } else { n - 1 }; let mut pts: Vec> = args.iter().map(PArg::idx).collect(); @@ -1097,8 +1129,8 @@ fn circle_center(s: &mut Session, p: &Value) -> Result { let p = &super::sketch_project::snap_points(s, p, cmd)?; let r = radius_arg(p, cmd)?; let id = str_(p, "id").map(str::to_string); - let (out, info) = draw(s, p, cmd, |sk, _| { - let c = req_parg(sk, p, "center", cmd)?; + let (out, info) = draw(s, p, cmd, |sk, doc| { + let c = req_parg(sk, doc, p, "center", cmd)?; let ci = sk.add_circle(c.pos(), r, c.idx(), id.as_deref())?; mark_construction(sk, &[ci], p); Ok((ids_of(sk, &[ci]), Vec::new())) @@ -1149,8 +1181,8 @@ fn arc_three(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.arc.three_point"; let p = &super::sketch_project::snap_points(s, p, cmd)?; let id = str_(p, "id").map(str::to_string); - let (out, info) = draw(s, p, cmd, |sk, _| { - let (a, b) = (req_parg(sk, p, "start", cmd)?, req_parg(sk, p, "end", cmd)?); + let (out, info) = draw(s, p, cmd, |sk, doc| { + let (a, b) = (req_parg(sk, doc, p, "start", cmd)?, req_parg(sk, doc, p, "end", cmd)?); let t = req_vec2(cmd, p, "through")?; let (o, _) = circumcircle(a.pos(), t, b.pos()).ok_or_else(|| bad(cmd, "the points are collinear"))?; // Counter-clockwise from start to end must pass the through point; otherwise swap. @@ -1172,9 +1204,9 @@ fn arc_center(s: &mut Session, p: &Value) -> Result { let p = &super::sketch_project::snap_points(s, p, cmd)?; let id = str_(p, "id").map(str::to_string); let sweep = num(p, "sweep"); - let (out, info) = draw(s, p, cmd, |sk, _| { - let c = req_parg(sk, p, "center", cmd)?; - let a = req_parg(sk, p, "start", cmd)?; + let (out, info) = draw(s, p, cmd, |sk, doc| { + let c = req_parg(sk, doc, p, "center", cmd)?; + let a = req_parg(sk, doc, p, "start", cmd)?; if let Some(sw) = sweep { // Start point and signed sweep (degrees); clockwise arcs keep `.start` at the start. if !(sw.abs() > 1e-9 && sw.abs() < 360.0) { @@ -1201,7 +1233,7 @@ fn arc_center(s: &mut Session, p: &Value) -> Result { }; return Ok((ids_of(sk, &[ci]), Vec::new())); } - let b = req_parg(sk, p, "end", cmd)?; + let b = req_parg(sk, doc, p, "end", cmd)?; let ci = sk.add_arc(c.pos(), a.pos(), b.pos(), [c.idx(), a.idx(), b.idx()], id.as_deref())?; Ok((ids_of(sk, &[ci]), Vec::new())) })?; @@ -1327,10 +1359,13 @@ fn slot_overall(s: &mut Session, p: &Value) -> Result { fn draw_point(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.point"; - let at = req_vec2(cmd, p, "point")?; let id = str_(p, "id").map(str::to_string); - let ((pid, cons), info) = edit(s, p, cmd, false, |sk, _| { - let i = sk.add_point(at, id.as_deref())?; + let ((pid, cons), info) = edit(s, p, cmd, false, |sk, doc| { + let i = match expr_point(doc, p.get("point").unwrap_or(&Value::Null), cmd)? { + Some((at, Some(exprs))) => add_placed_point(sk, at, exprs, id.as_deref())?, + Some((at, None)) => sk.add_point(at, id.as_deref())?, + None => sk.add_point(req_vec2(cmd, p, "point")?, id.as_deref())?, + }; let cons = connect_points(sk, i, p)?; Ok((sk.points.get(i).map(|q| q.id.clone()).unwrap_or_default(), cons)) })?; @@ -2548,6 +2583,9 @@ mod ids_tests; #[path = "sketch_infinite_tests.rs"] mod infinite_tests; #[cfg(test)] +#[path = "sketch_point_expr_tests.rs"] +mod point_expr_tests; +#[cfg(test)] #[path = "sketch_redundant_tests.rs"] mod redundant_tests; #[cfg(test)] diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs index fbc538b1a..0fb17162b 100644 --- a/crates/engine/src/cmd/sketch_create.rs +++ b/crates/engine/src/cmd/sketch_create.rs @@ -165,7 +165,7 @@ const AT_MUST: &str = "`at` must be the baseline start [x, y], each a number or /// it names a parameter, so that the text follows it; one that names none is the number it comes /// to. Returns the value (mm or radians) and the expression kept. Anything else is refused with /// `must`. -fn text_number(doc: &solidcraft_doc::Document, v: &Value, cmd: &str, key: &str, must: &str, angle: bool) -> Result<(f64, Option)> { +pub(super) fn text_number(doc: &solidcraft_doc::Document, v: &Value, cmd: &str, key: &str, must: &str, angle: bool) -> Result<(f64, Option)> { use solidcraft_doc::expr::{self, Kind}; let kind = if angle { Kind::Angle } else { Kind::Length }; match v { @@ -464,9 +464,9 @@ fn joint_derivatives(sk: &Sketch, ci: usize, pi: usize, order: usize, leaving: b fn blend(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.blend_curve"; let order = blend_order(p, cmd)?; - let (out, info) = edit(s, p, cmd, false, |sk, _| { - let pa = req_parg(sk, p, "a", cmd)?.idx().ok_or_else(|| bad(cmd, "`a` must be the end point of a curve"))?; - let pb = req_parg(sk, p, "b", cmd)?.idx().ok_or_else(|| bad(cmd, "`b` must be the end point of a curve"))?; + let (out, info) = edit(s, p, cmd, false, |sk, doc| { + let pa = req_parg(sk, doc, p, "a", cmd)?.idx().ok_or_else(|| bad(cmd, "`a` must be the end point of a curve"))?; + let pb = req_parg(sk, doc, p, "b", cmd)?.idx().ok_or_else(|| bad(cmd, "`b` must be the end point of a curve"))?; let (ca, ta) = end_of(sk, pa).ok_or_else(|| bad(cmd, "no curve ends at `a`"))?; let (cb, tb) = end_of(sk, pb).ok_or_else(|| bad(cmd, "no curve ends at `b`"))?; let (qa, qb) = (sk.point(pa).unwrap_or_default(), sk.point(pb).unwrap_or_default()); @@ -590,14 +590,14 @@ fn ellipse(s: &mut Session, p: &Value) -> Result { Ok(result(out, info)) } -fn point_list(sk: &mut Sketch, p: &Value, cmd: &str) -> Result> { +fn point_list(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value, cmd: &str) -> Result> { let list = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`points` must be a list"))?; if list.len() < 2 || list.len() > solidcraft_sketch::MAX_SPLINE_POINTS { return Err(bad(cmd, "a spline needs 2 to 500 points")); } let mut out = Vec::new(); for v in list { - let a = super::sketch::parg(sk, v, cmd)?; + let a = super::sketch::parg(sk, doc, v, cmd)?; let i = match a.idx() { Some(i) => i, None => sk.add_point(a.pos(), None)?, @@ -620,8 +620,8 @@ fn spline(s: &mut Session, p: &Value, cmd: &str, control: bool, degree: u8) -> R return Err(bad(cmd, "periodic mode requires a cubic fit spline")); } let p = &super::sketch_project::snap_points(s, p, cmd)?; - let (out, info) = edit(s, p, cmd, false, |sk, _| { - let mut pts = point_list(sk, p, cmd)?; + let (out, info) = edit(s, p, cmd, false, |sk, doc| { + let mut pts = point_list(sk, doc, p, cmd)?; if periodic && sk.point(*pts.first().ok_or_else(|| bad(cmd, "missing first point"))?) != sk.point(*pts.last().ok_or_else(|| bad(cmd, "missing last point"))?) @@ -652,10 +652,10 @@ fn conic(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "`rho` must be between 0 and 1")); } let p = &super::sketch_project::snap_points(s, p, cmd)?; - let (out, info) = edit(s, p, cmd, false, |sk, _| { + let (out, info) = edit(s, p, cmd, false, |sk, doc| { let mut idx = Vec::new(); for k in ["start", "end", "apex"] { - let a = req_parg(sk, p, k, cmd)?; + let a = req_parg(sk, doc, p, k, cmd)?; idx.push(match a.idx() { Some(i) => i, None => sk.add_point(a.pos(), None)?, @@ -675,8 +675,8 @@ fn conic(s: &mut Session, p: &Value) -> Result { fn midpoint_line(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.line.midpoint"; let end = req_vec2(cmd, p, "end")?; - let (out, info) = edit(s, p, cmd, false, |sk, _| { - let m = req_parg(sk, p, "mid", cmd)?; + let (out, info) = edit(s, p, cmd, false, |sk, doc| { + let m = req_parg(sk, doc, p, "mid", cmd)?; let start = m.pos() * 2.0 - end; if start.dist(end) < 1e-9 { return Err(bad(cmd, "the end must differ from the midpoint")); @@ -744,8 +744,8 @@ fn leaving_dir(sk: &Sketch, ci: usize, pi: usize) -> Option { fn arc_tangent(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.arc.tangent"; let end = req_vec2(cmd, p, "end")?; - let (out, info) = edit(s, p, cmd, false, |sk, _| { - let st = req_parg(sk, p, "start", cmd)?; + let (out, info) = edit(s, p, cmd, false, |sk, doc| { + let st = req_parg(sk, doc, p, "start", cmd)?; let picked = st.idx().ok_or_else(|| bad(cmd, "`start` must be the end point of a line or arc"))?; // The picked point, then any other point at the same place: a trimmed arc's end is its own // point, lying on the end of the curve that trimmed it, which is the one a click picks (#1485). diff --git a/crates/engine/src/cmd/sketch_point_expr_tests.rs b/crates/engine/src/cmd/sketch_point_expr_tests.rs new file mode 100644 index 000000000..2c5422014 --- /dev/null +++ b/crates/engine/src/cmd/sketch_point_expr_tests.rs @@ -0,0 +1,131 @@ +//! Sketch points placed by parameters: a coordinate typed as an expression fixes the point +//! where it comes to, and the point follows the parameters without a dimension or a solve. + +use serde_json::{Value, json}; +use solidcraft_geom::Vec2; + +use crate::Session; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn volume(s: &mut Session) -> f64 { + run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap_or(f64::NAN) +} + +fn no_trouble(s: &Session) { + for r in &s.model.results { + assert!(r.error.is_none() && r.warning.is_none(), "{}: {:?} {:?}", r.name, r.error, r.warning); + } +} + +/// Where point `id` of sketch `S` is in the evaluated model. +fn solved(s: &Session, id: &str) -> Vec2 { + let f = s.doc.find_feature("S").unwrap().id; + let st = s.model.state(); + let sk = &st.sketch(f).unwrap().sketch; + sk.points.iter().find(|q| q.id == id).unwrap().pos +} + +fn reopened(s: &Session) -> Session { + Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()) +} + +#[test] +fn an_outline_through_points_typed_as_expressions_follows_its_parameters() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "40 mm"})); + run(&mut s, "parameters.add", json!({"name": "H", "expression": "30 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], ["W", 0], ["W", "H / 2 + H / 2"], [0, "H"]], "closed": true})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": 10})); + no_trouble(&s); + assert!((volume(&mut s) - 40.0 * 30.0 * 10.0).abs() < 1e-6); + // One change of both: the outline follows without a dimension. + run(&mut s, "parameters.change", json!({"name": "W", "expression": "70 mm"})); + run(&mut s, "parameters.change", json!({"name": "H", "expression": "2 in"})); + no_trouble(&s); + assert!((volume(&mut s) - 70.0 * 50.8 * 10.0).abs() < 1e-6); + assert!(s.doc.to_json().contains("\"exprs\""), "the design file keeps the expressions"); + let mut r = reopened(&s); + no_trouble(&r); + assert!((volume(&mut r) - 70.0 * 50.8 * 10.0).abs() < 1e-6); + // Editing the sketch later keeps the points where the parameters put them. + run(&mut s, "sketch.edit", json!({"sketch": "S"})); + run(&mut s, "sketch.point", json!({"point": [200, 200]})); + run(&mut s, "sketch.finish", json!({})); + assert!((volume(&mut s) - 70.0 * 50.8 * 10.0).abs() < 1e-6); +} + +#[test] +fn a_placed_point_is_fixed_listed_with_its_parameters_and_renamed_with_them() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "60 mm"})); + run(&mut s, "parameters.add", json!({"name": "H", "expression": "30 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + run(&mut s, "sketch.point", json!({"point": ["W / 2", "H / 3"], "id": "c"})); + run(&mut s, "sketch.circle.center", json!({"center": ["W / 4", 5], "radius": 2, "id": "hole"})); + // A text without a parameter is just a number: a free point. + run(&mut s, "sketch.point", json!({"point": ["5", "6"], "id": "free"})); + run(&mut s, "sketch.finish", json!({})); + no_trouble(&s); + assert_eq!(solved(&s, "c"), Vec2::new(30.0, 10.0)); + let f = s.doc.find_feature("S").unwrap().id; + let sk = s.doc.sketch(f).unwrap(); + let c = sk.points.iter().find(|q| q.id == "c").unwrap(); + assert!(c.fixed && c.exprs.as_ref().is_some_and(|e| e.x.as_deref() == Some("W / 2")), "{c:?}"); + let free = sk.points.iter().find(|q| q.id == "free").unwrap(); + assert!(!free.fixed && free.exprs.is_none() && free.pos == Vec2::new(5.0, 6.0), "{free:?}"); + run(&mut s, "parameters.change", json!({"name": "W", "expression": "100 mm"})); + assert_eq!(solved(&s, "c"), Vec2::new(50.0, 10.0)); + let centre = s.doc.sketch(f).unwrap().curves.iter().find(|c| c.id == "hole").map(|c| c.kind.point_ids()).unwrap_or_default(); + let centre_id = s.doc.sketch(f).unwrap().points.get(centre[0]).unwrap().id.clone(); + assert_eq!(solved(&s, ¢re_id), Vec2::new(25.0, 5.0)); + // The parameter knows the point uses it; a rename reaches the expression. + let users = run(&mut s, "parameters.users", json!({"name": "H"})); + assert!(users.to_string().contains("Point Y"), "{users}"); + run(&mut s, "parameters.rename", json!({"name": "W", "new_name": "width"})); + let c = s.doc.sketch(f).unwrap().points.iter().find(|q| q.id == "c").unwrap().clone(); + assert_eq!(c.exprs.and_then(|e| e.x), Some("width / 2".to_string())); + run(&mut s, "parameters.change", json!({"name": "width", "expression": "80 mm"})); + no_trouble(&s); + assert_eq!(solved(&s, "c"), Vec2::new(40.0, 10.0)); +} + +#[test] +fn a_point_expression_that_cannot_be_worked_out_is_refused() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "turn", "expression": "30 deg"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + for bad in [json!(["nope", 0]), json!(["turn", 0]), json!([0, ""]), json!(["1 / 0", 0]), json!(["1e300 * 1e300", 0])] { + assert!(s.execute("sketch.point", &json!({"point": bad})).is_err(), "{bad}"); + assert!(s.execute("sketch.line", &json!({"points": [[0, 0], bad]})).is_err(), "{bad}"); + } + assert_eq!(s.doc.sketch(s.doc.find_feature("S").unwrap().id).unwrap().points.len(), 1, "only the origin"); +} + +#[test] +fn a_point_its_parameters_put_out_of_range_is_an_error_not_a_crash() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "40 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + run(&mut s, "sketch.point", json!({"point": ["W", 0], "id": "c"})); + run(&mut s, "sketch.finish", json!({})); + let changed = s.execute("parameters.change", &json!({"name": "W", "expression": "1e12 mm"})); + let failed = s.model.results.iter().any(|r| r.error.as_deref().is_some_and(|e| e.contains("out of range"))); + assert!(changed.is_err() || failed, "{changed:?}"); + run(&mut s, "parameters.change", json!({"name": "W", "expression": "50 mm"})); + no_trouble(&s); + assert_eq!(solved(&s, "c"), Vec2::new(50.0, 0.0)); + // A design file whose point expression cannot be worked out opens with that sketch in error. + let file = s.doc.to_json(); + let hostile = file.replace("\"x\": \"W\"", "\"x\": \"W * 1e300 * 1e300\"").replace("\"x\":\"W\"", "\"x\":\"W * 1e300 * 1e300\""); + assert_ne!(hostile, file, "the point's expression is in the file"); + let r = Session::new(solidcraft_doc::Document::from_json(&hostile).unwrap()); + assert!(r.model.results.iter().any(|r| r.error.is_some()), "the sketch reports the bad point"); +} diff --git a/crates/sketch/src/construct_tests.rs b/crates/sketch/src/construct_tests.rs index a69d9833e..503a1152b 100644 --- a/crates/sketch/src/construct_tests.rs +++ b/crates/sketch/src/construct_tests.rs @@ -890,7 +890,7 @@ fn given_points_are_never_placed() { sk.add_constraint(ConstraintKind::Fix { p }, None).unwrap(); } let g = sk.points.len(); - sk.points.push(SPoint { id: "far".into(), pos: v(2e9, 0.0), fixed: true, link: None }); + sk.points.push(SPoint { id: "far".into(), pos: v(2e9, 0.0), fixed: true, link: None, exprs: None }); let d = sk.add_point(v(20.0, 30.0), None).unwrap(); let push = |sk: &mut Sketch, kind: ConstraintKind| { sk.constraints.push(Constraint { id: format!("h{}", sk.constraints.len()), kind, param: None, driven: false, text: None }) diff --git a/crates/sketch/src/decompose_tests.rs b/crates/sketch/src/decompose_tests.rs index 9f4fd08ab..ad8d0cab7 100644 --- a/crates/sketch/src/decompose_tests.rs +++ b/crates/sketch/src/decompose_tests.rs @@ -45,7 +45,7 @@ fn raw(kind: ConstraintKind) -> Constraint { /// A point pushed past the sketch's own size cap. fn push_point(sk: &mut Sketch, pos: Vec2) { let id = format!("p{}", sk.points.len()); - sk.points.push(crate::model::SPoint { id, pos, fixed: false, link: None }); + sk.points.push(crate::model::SPoint { id, pos, fixed: false, link: None, exprs: None }); } /// Every point of `ids` placed at its `want` position. diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs index 60ba5da57..9ddf30210 100644 --- a/crates/sketch/src/lib.rs +++ b/crates/sketch/src/lib.rs @@ -50,7 +50,8 @@ pub use fonts::{DEFAULT_FONT_FAMILY, FontData, families_in, find_style_in, font_ pub use freeform_offset::{FreeformOffset, OFFSET_TOLERANCE}; pub use link::{Link, LinkGeom, LinkKind, LinkSource, MAX_LINK_ENTITIES, SKETCH_AXIS_HALF, TextExprs, sketch_axis_geom}; pub use model::{ - Constraint, ConstraintKind, Curve, CurveKind, MAX_CONSTRAINTS, MAX_COORD, MAX_CURVES, MAX_POINTS, SPoint, Sketch, SketchError, SketchView, + Constraint, ConstraintKind, Curve, CurveKind, MAX_CONSTRAINTS, MAX_COORD, MAX_CURVES, MAX_POINTS, PointExprs, SPoint, Sketch, SketchError, + SketchView, }; pub use offset::OffsetChain; pub use offset_topology::{OffsetCreated, OffsetRole, OffsetRoleFlags, OffsetRoleKind, OffsetTopology}; diff --git a/crates/sketch/src/link.rs b/crates/sketch/src/link.rs index 819a4d3a7..2490d74f1 100644 --- a/crates/sketch/src/link.rs +++ b/crates/sketch/src/link.rs @@ -520,7 +520,8 @@ impl Sketch { self.links.iter().find(|l| l.id == id) } - /// The expressions of the sketch's texts, each with what it sets (`Text height`…). + /// The expressions of the sketch's texts and of its points placed by parameters, each with + /// what it sets (`Text height`, `Point X`…). pub fn text_exprs(&self) -> Vec<(&'static str, &String)> { self.links .iter() @@ -529,6 +530,7 @@ impl Sketch { _ => None, }) .flatten() + .chain(self.points.iter().filter_map(|p| p.exprs.as_deref()).flat_map(crate::PointExprs::list)) .collect() } @@ -541,6 +543,7 @@ impl Sketch { _ => None, }) .flatten() + .chain(self.points.iter_mut().filter_map(|p| p.exprs.as_deref_mut()).flat_map(crate::PointExprs::list_mut)) .collect() } diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index 6e93064cd..82ce56d89 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -53,6 +53,32 @@ pub struct SPoint { /// Projected (linked) reference geometry: the id of the link that owns this point. #[serde(default, skip_serializing_if = "Option::is_none")] pub link: Option, + /// A point placed by expressions over the design's parameters: it is `fixed` where they + /// come to (`Document::apply_point_values` works them out before each solve). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exprs: Option>, +} + +/// The expressions of a point placed by parameters, over the design's parameters; a coordinate +/// without one keeps the number stored in the point (mm). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct PointExprs { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub x: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub y: Option, +} + +impl PointExprs { + /// The expressions set, each with what it sets. + pub fn list(&self) -> Vec<(&'static str, &String)> { + [("Point X", &self.x), ("Point Y", &self.y)].into_iter().filter_map(|(what, e)| e.as_ref().map(|e| (what, e))).collect() + } + + /// Mutable view of [`PointExprs::list`], for renaming the parameters they refer to. + pub fn list_mut(&mut self) -> Vec<&mut String> { + [&mut self.x, &mut self.y].into_iter().filter_map(Option::as_mut).collect() + } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -615,7 +641,7 @@ impl Default for Sketch { impl Sketch { pub fn new() -> Self { Sketch { - points: vec![SPoint { id: "origin".into(), pos: Vec2::ZERO, fixed: true, link: None }], + points: vec![SPoint { id: "origin".into(), pos: Vec2::ZERO, fixed: true, link: None, exprs: None }], curves: Vec::new(), constraints: Vec::new(), patterns: Vec::new(), @@ -712,7 +738,7 @@ impl Sketch { Some(i) => i.to_string(), None => self.fresh("p")?, }; - self.points.push(SPoint { id, pos: p, fixed: false, link: None }); + self.points.push(SPoint { id, pos: p, fixed: false, link: None, exprs: None }); Ok(self.points.len() - 1) }