From 157c0d68d08569f8936736fd3c80e6de70d088cd Mon Sep 17 00:00:00 2001 From: rbousigues88 Date: Sun, 25 Oct 2026 04:29:28 +0000 Subject: [PATCH] Sketch Dimension: point/circle to circle or arc edge (#4064) (#4065) * Sketch Dimension: point or circle to the edge of a circle or arc (#4064) Adds PointCircleDistance and CircleCircleDistance (edge-based, like #1863): solver, constructive seed, drawing, command wiring, tests, UI scenarios and docs. Saved designs gain two constraint kinds, in one pending format file. Fixes #4064. Co-Authored-By: Claude Sonnet 5.5 * Sketch Dimension scenario: pick the circle at its top edge (#4064) The bottom edge sits under the Dimension tool's status hint in the scenario window, so the second click never reached the tool. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- ROADMAP.md | 3 + .../format/pending/circle-edge-distances.rs | 7 + crates/engine/src/cmd/sketch.rs | 34 ++- .../src/cmd/sketch_circle_edge_tests.rs | 191 +++++++++++++ crates/engine/src/cmd/sketch_constraints.rs | 2 + crates/sketch/src/circle_edge_tests.rs | 256 ++++++++++++++++++ crates/sketch/src/dims.rs | 22 +- crates/sketch/src/lib.rs | 4 +- crates/sketch/src/loci.rs | 17 ++ crates/sketch/src/model.rs | 104 ++++++- crates/sketch/src/solver.rs | 21 +- crates/ui-egui/src/dim_view.rs | 7 +- ...ketch_dimension_circle_to_circle_edge.json | 21 ++ ...sketch_dimension_point_to_circle_edge.json | 20 ++ docs/book/src/guide/sketching.md | 11 +- docs/capabilities.md | 2 +- skills/solidcraft-modeling/reference.md | 3 +- 17 files changed, 712 insertions(+), 13 deletions(-) create mode 100644 crates/doc/src/format/pending/circle-edge-distances.rs create mode 100644 crates/engine/src/cmd/sketch_circle_edge_tests.rs create mode 100644 crates/sketch/src/circle_edge_tests.rs create mode 100644 crates/ui-egui/tests/scenarios/sketch_dimension_circle_to_circle_edge.json create mode 100644 crates/ui-egui/tests/scenarios/sketch_dimension_point_to_circle_edge.json diff --git a/ROADMAP.md b/ROADMAP.md index 497786f3b..98275b2de 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -247,6 +247,9 @@ completed drawings publish atomically. The browser still exports synchronously. - Sketch Dimension takes a line and a circle or arc (#1803): it measures from the line to the circle's edge (the gap, 0 when tangent, or how far the edge reaches past a line that cuts it), drives it like any other dimension and keeps the circle on its side of the line. +- Sketch Dimension takes a point and a circle or arc, or two circles or arcs (#4064): it + measures to the circle's edge (from the point, or between the two edges: the gap, 0 when + they touch, how far they overlap, or the narrowest gap between nested circles). - Sketch annotations, live drawing lengths and Measure use document units. Inches show three decimals and retain a meaningful fourth digit. Bare length dimension entry captures the current design unit; changing units leaves existing geometry and expressions intact. diff --git a/crates/doc/src/format/pending/circle-edge-distances.rs b/crates/doc/src/format/pending/circle-edge-distances.rs new file mode 100644 index 000000000..5e8d8aafa --- /dev/null +++ b/crates/doc/src/format/pending/circle-edge-distances.rs @@ -0,0 +1,7 @@ +//! A sketch can hold two more dimensions to the edge of a circle or arc (#4064): +//! `point_circle_distance`, from a point `p` to the edge of circle or arc `c` (saved with its +//! `value` and, for a point within the circle, `inside`), and `circle_circle_distance`, between +//! the edges of circles or arcs `a` and `b` (saved with its `value` and, unless they are apart, +//! `circles`: `crossing` for how far they overlap, `nested` for the narrowest gap between one +//! inside the other). Older designs need no transformation: they have no such dimensions; the +//! last release asks for an update instead of meeting a constraint type it doesn't know. diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 3c8401fc2..85cf36e27 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, PointExprs, Sketch, SolveReport, solve, solve_with}; +use solidcraft_sketch::{Analysis, Budget, ConstraintKind, CurveKind, Hold, PointExprs, Sketch, SolveReport, TwoCircles, solve, solve_with}; use super::{CommandSpec, in_sketch}; use crate::params::{bad, bool_, expr, num, req_expr, req_vec2, str_, string_list, vec2, vec3}; @@ -120,7 +120,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .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] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them) or a snap: \"mid:\" (held at the line's midpoint), \"on::x,y\" (on the curve near x,y), {vertex: [x,y,z]} or {on_edge: [x,y,z]} of the model; 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] (a line midpoint is \"mid:line_id\"), 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), or `name = expression` (e.g. \"width = 40\"; also `#name = expression`), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); 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 midpoints: placing text above or below their bounding box measures horizontally, beside it vertically. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. 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", + "entities: [refs] (a line midpoint is \"mid:line_id\"), 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), or `name = expression` (e.g. \"width = 40\"; also `#name = expression`), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); 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 midpoints: placing text above or below their bounding box measures horizontally, beside it vertically. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A point and a circle or arc: the distance from the point to its edge (or how far within it a point inside lies). Two circles or arcs: the gap between their edges (or how far they overlap when they cross, or the narrowest gap between them when one lies inside the other); dimension their centre points for the distance between centres. 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", ), CommandSpec::new("sketch.constraint.horizontal_vertical", "Horizontal/Vertical", c_horizontal_vertical) .at("SKETCH", "CONSTRAINTS") @@ -2496,6 +2496,33 @@ fn dimension(s: &mut Session, p: &Value) -> Result { let gap = (d - r).abs(); (ConstraintKind::LineCircleDistance { l, c, value: gap, inside }, gap) } + // A point and a circle or arc: the distance from the point to its edge, along the + // radius through the point (#4064). + ((Some(q), None), Some((None, Some(c)))) | ((None, Some(c)), Some((Some(q), None))) if is_round(c) => { + let own_centre = matches!(sk.curves.get(c).map(|x| &x.kind), Some(CurveKind::Circle { c: centre, .. } | CurveKind::Arc { c: centre, .. }) if *centre == q); + if own_centre { + return Err(bad(cmd, "that point is the circle's own centre: dimension its radius or diameter instead")); + } + let (centre, r) = sk.center(c).zip(sk.radius(c)).ok_or_else(|| bad(cmd, "cannot dimension that curve"))?; + let d = sk.point(q).unwrap_or_default().dist(centre); + // A point within the circle measures how far inside its edge it lies. + let inside = d < r; + let gap = (d - r).abs(); + (ConstraintKind::PointCircleDistance { p: q, c, value: gap, inside }, gap) + } + // Two circles or arcs: the gap between their edges, how far they overlap, or the + // narrowest gap between the inner one and the outer one, as they lie now (#4064). + ((None, Some(a)), Some((None, Some(b)))) if is_round(a) && is_round(b) => { + if a == b { + return Err(bad(cmd, "pick two different circles or arcs")); + } + let round = |c: usize| sk.center(c).zip(sk.radius(c)).ok_or_else(|| bad(cmd, "cannot dimension that curve")); + let ((ca, ra), (cb, rb)) = (round(a)?, round(b)?); + let d = ca.dist(cb); + let circles = TwoCircles::of(d, ra, rb); + let gap = circles.gap(d, ra, rb).max(0.0); + (ConstraintKind::CircleCircleDistance { a, b, value: gap, circles }, gap) + } _ => return Err(bad(cmd, "cannot dimension that combination of entities")), }; let is_angle = k.is_angle(); @@ -3074,6 +3101,9 @@ mod ux_tests; #[path = "sketch_axis_ref_tests.rs"] mod axis_ref_tests; #[cfg(test)] +#[path = "sketch_circle_edge_tests.rs"] +mod circle_edge_tests; +#[cfg(test)] #[path = "sketch_drag_live_tests.rs"] mod drag_live_tests; #[cfg(test)] diff --git a/crates/engine/src/cmd/sketch_circle_edge_tests.rs b/crates/engine/src/cmd/sketch_circle_edge_tests.rs new file mode 100644 index 000000000..fd4b5d150 --- /dev/null +++ b/crates/engine/src/cmd/sketch_circle_edge_tests.rs @@ -0,0 +1,191 @@ +//! Sketch Dimension to the edge of a circle or arc (#4064): `sketch.dimension` with a point and a +//! circle or arc measures the distance from the point to its edge, with two circles or arcs the +//! gap between their edges (how far they overlap when they cross, the narrowest gap when one is +//! inside the other); it drives that distance, follows its parameter, and survives undo and +//! reopening. + +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 sketch(s: &Session) -> solidcraft_sketch::Sketch { + s.model.state().sketch(s.active_sketch.unwrap()).unwrap().sketch.clone() +} + +fn point(s: &Session, id: &str) -> Vec2 { + let sk = sketch(s); + sk.resolve_point(id).and_then(|p| sk.point(p)).unwrap() +} + +/// A new sketch with a circle of radius `r` at `centre` (its diameter dimensioned), its centre +/// fixed when `fixed`. +fn add_circle(s: &mut Session, centre: [f64; 2], r: f64, fixed: bool) -> String { + let id = run(s, "sketch.circle.center", json!({"center": centre, "radius": r}))["created"]["curves"][0].as_str().unwrap().to_string(); + if fixed { + run(s, "sketch.constraint.fix", json!({"entities": [format!("{id}.center")]})); + } + run(s, "sketch.dimension", json!({"entities": [id], "type": "diameter", "value": 2.0 * r})); + id +} + +/// A circle of radius 5 with its centre fixed at (20, 15) (`c1`) and a point `pt` at `at`, kept +/// level with the centre. +fn circle_and_point(at: [f64; 2]) -> Session { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + add_circle(&mut s, [20.0, 15.0], 5.0, true); + run(&mut s, "sketch.point", json!({"point": at, "id": "pt"})); + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points": ["c1.center", "pt"], "mode": "horizontal"})); + s +} + +/// A circle of radius `ra` with its centre fixed at (10, 10) (`c1`) and a circle of radius `rb` +/// (`c2`) `x` to its right, kept level with it. +fn two_circles(ra: f64, x: f64, rb: f64) -> Session { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + add_circle(&mut s, [10.0, 10.0], ra, true); + add_circle(&mut s, [10.0 + x, 10.0], rb, false); + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points": ["c1.center", "c2.center"], "mode": "horizontal"})); + s +} + +fn near(s: &Session, id: &str, want: [f64; 2]) { + let at = point(s, id); + assert!(at.dist(Vec2::new(want[0], want[1])) < 1e-7, "{id} at {at:?}, want {want:?}"); +} + +#[test] +fn a_point_and_a_circle_dimension_to_its_edge() { + let mut s = circle_and_point([32.0, 15.0]); + // 12 from the centre, radius 5: 7 from the edge. + let r = run(&mut s, "sketch.dimension", json!({"entities": ["pt", "c1"]})); + assert_eq!(r["type"], "LinearDimension", "{r}"); + assert_eq!(r["measured"], 7.0, "{r}"); + assert_eq!(r["expression"], "7 mm", "{r}"); + let param = r["param"].as_str().unwrap().to_string(); + // The parameter drives the gap: 3 puts the point 5 + 3 from the centre. + run(&mut s, "parameters.change", json!({"name": param, "expression": "3 mm"})); + near(&s, "pt", [28.0, 15.0]); + // The circle and the point in the other order, with a value. + let mut s = circle_and_point([32.0, 15.0]); + let r = run(&mut s, "sketch.dimension", json!({"entities": ["c1", "pt"], "value": 4})); + assert_eq!(r["measured"], 4.0, "{r}"); + near(&s, "pt", [29.0, 15.0]); +} + +#[test] +fn a_point_inside_the_circle_dimensions_how_far_within_the_edge_it_lies() { + // 2 from the centre, radius 5: 3 within the edge. + let mut s = circle_and_point([22.0, 15.0]); + let r = run(&mut s, "sketch.dimension", json!({"entities": ["pt", "c1"]})); + assert_eq!(r["measured"], 3.0, "{r}"); + let param = r["param"].as_str().unwrap().to_string(); + run(&mut s, "parameters.change", json!({"name": param, "expression": "1"})); + // 1 within the edge is 4 from the centre: the point stays inside. + near(&s, "pt", [24.0, 15.0]); +} + +#[test] +fn the_circles_own_centre_is_refused() { + let mut s = circle_and_point([32.0, 15.0]); + for entities in [["c1.center", "c1"], ["c1", "c1.center"]] { + let err = s.execute("sketch.dimension", &json!({"entities": entities})).unwrap_err().to_string(); + assert!(err.contains("own centre"), "{err}"); + } +} + +#[test] +fn two_circles_dimension_the_gap_between_their_edges() { + // Centres 20 apart, radii 5 and 3: a gap of 12. + let mut s = two_circles(5.0, 20.0, 3.0); + let r = run(&mut s, "sketch.dimension", json!({"entities": ["c1", "c2"]})); + assert_eq!(r["type"], "LinearDimension", "{r}"); + assert_eq!(r["measured"], 12.0, "{r}"); + let param = r["param"].as_str().unwrap().to_string(); + run(&mut s, "parameters.change", json!({"name": param, "expression": "4 mm"})); + near(&s, "c2.center", [22.0, 10.0]); +} + +#[test] +fn crossing_and_nested_circles_dimension_their_overlap_and_their_narrowest_gap() { + // Centres 6 apart, radii 5 and 3: they overlap by 2; overlapping by 1 puts them 7 apart. + let mut s = two_circles(5.0, 6.0, 3.0); + let r = run(&mut s, "sketch.dimension", json!({"entities": ["c2", "c1"]})); + assert_eq!(r["measured"], 2.0, "{r}"); + run(&mut s, "parameters.change", json!({"name": r["param"].as_str().unwrap(), "expression": "1"})); + near(&s, "c2.center", [17.0, 10.0]); + // A radius 3 circle 4 off the centre of a radius 10 one: 3 at the narrowest; 1 there puts + // it 6 off. + let mut s = two_circles(10.0, 4.0, 3.0); + let r = run(&mut s, "sketch.dimension", json!({"entities": ["c1", "c2"]})); + assert_eq!(r["measured"], 3.0, "{r}"); + run(&mut s, "parameters.change", json!({"name": r["param"].as_str().unwrap(), "expression": "1"})); + near(&s, "c2.center", [16.0, 10.0]); +} + +#[test] +fn arcs_dimension_to_their_circles() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.arc.center_point", json!({"center": [20, 20], "start": [26, 20], "end": [14, 20]})); + run(&mut s, "sketch.circle.center", json!({"center": [40, 20], "radius": 4})); + run(&mut s, "sketch.point", json!({"point": [20, 0], "id": "pt"})); + // Centres 20 apart, radii 6 and 4. + let r = run(&mut s, "sketch.dimension", json!({"entities": ["a1", "c1"]})); + assert_eq!(r["measured"], 10.0, "{r}"); + // 20 below the arc's centre, radius 6. + let r = run(&mut s, "sketch.dimension", json!({"entities": ["pt", "a1"]})); + assert_eq!(r["measured"], 14.0, "{r}"); +} + +#[test] +fn the_dimensions_undo_and_reopen() { + let mut s = two_circles(5.0, 20.0, 3.0); + run(&mut s, "sketch.point", json!({"point": [10, 30], "id": "pt"})); + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points": ["c1.center", "pt"], "mode": "vertical"})); + let before = sketch(&s).constraints.len(); + run(&mut s, "sketch.dimension", json!({"entities": ["c1", "c2"], "value": 6})); + run(&mut s, "sketch.dimension", json!({"entities": ["pt", "c1"], "value": 9})); + let saved = s.doc.to_json(); + assert!(saved.contains("\"point_circle_distance\"") && saved.contains("\"circle_circle_distance\""), "not saved"); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap()); + run(&mut reopened, "sketch.edit", json!({"sketch": "Sketch1"})); + near(&reopened, "c2.center", [24.0, 10.0]); + near(&reopened, "pt", [10.0, 24.0]); + let kinds = |s: &Session| sketch(s).constraints.iter().map(|c| c.kind.clone()).collect::>(); + assert_eq!(kinds(&reopened), kinds(&s)); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(sketch(&s).constraints.len(), before); +} + +#[test] +fn a_gap_the_sketch_already_has_is_refused_or_driven() { + // Tangent circles already have a gap of zero. + let mut s = two_circles(5.0, 8.0, 3.0); + run(&mut s, "sketch.constraint.tangent", json!({"a": "c1", "b": "c2"})); + let err = s.execute("sketch.dimension", &json!({"entities": ["c1", "c2"]})).unwrap_err().to_string(); + assert!(err.contains("already determined"), "{err}"); + let r = run(&mut s, "sketch.dimension", json!({"entities": ["c1", "c2"], "if_redundant": "driven"})); + assert_eq!(r["driven"], true, "{r}"); + assert!(r["measured"].as_f64().unwrap().abs() < 1e-7, "{r}"); +} + +#[test] +fn the_same_circle_twice_and_an_ellipse_are_refused() { + let mut s = circle_and_point([32.0, 15.0]); + let err = s.execute("sketch.dimension", &json!({"entities": ["c1", "c1"]})).unwrap_err().to_string(); + assert!(err.contains("two different"), "{err}"); + run(&mut s, "sketch.ellipse", json!({"center": [60, 20], "major": [70, 20], "minor_radius": 4})); + let err = s.execute("sketch.dimension", &json!({"entities": ["pt", "e1"]})).unwrap_err().to_string(); + assert!(err.contains("cannot dimension that combination"), "{err}"); +} diff --git a/crates/engine/src/cmd/sketch_constraints.rs b/crates/engine/src/cmd/sketch_constraints.rs index 59068dd95..efddb171e 100644 --- a/crates/engine/src/cmd/sketch_constraints.rs +++ b/crates/engine/src/cmd/sketch_constraints.rs @@ -450,6 +450,8 @@ fn anchor(sk: &Sketch, k: &ConstraintKind) -> Option { Distance { p, q, .. } | DistanceX { p, q, .. } | DistanceY { p, q, .. } => Some((pt(p)? + pt(q)?) * 0.5), PointLineDistance { p, .. } | LinearDiameter { p, .. } => pt(p), LineCircleDistance { c, .. } => sk.center(c), + PointCircleDistance { p, .. } => pt(p), + CircleCircleDistance { a, b, .. } => Some((sk.center(a)? + sk.center(b)?) * 0.5), Length { l, .. } | LineAngle { l, .. } => mid(l), Radius { c, .. } | Diameter { c, .. } | ArcLength { c, .. } | ArcSweep { c, .. } => mid(c), SlotOverallLength { a, b, .. } => Some((sk.center(a)? + sk.center(b)?) * 0.5), diff --git a/crates/sketch/src/circle_edge_tests.rs b/crates/sketch/src/circle_edge_tests.rs new file mode 100644 index 000000000..885078579 --- /dev/null +++ b/crates/sketch/src/circle_edge_tests.rs @@ -0,0 +1,256 @@ +//! Distances to the edge of a circle or arc from a point, and between the edges of two circles or +//! arcs (#4064): solved numerically and by construction, measured, drawn between the edge points +//! that face each other, saved, and refused on other kinds of curve. + +use solidcraft_geom::Vec2; + +use crate::tests::v; +use crate::*; + +/// A circle of radius `r` at `centre`, its radius set by a dimension; its centre fixed when +/// `fixed`. The circle and its centre point. +fn circle(sk: &mut Sketch, centre: Vec2, r: f64, fixed: bool) -> (usize, usize) { + let c = sk.add_circle(centre, r, None, None).unwrap(); + let CurveKind::Circle { c: ci, .. } = sk.curves[c].kind else { panic!("not a circle") }; + sk.add_constraint(ConstraintKind::Radius { c, value: r }, None).unwrap(); + if fixed { + sk.add_constraint(ConstraintKind::Fix { p: ci }, None).unwrap(); + } + (c, ci) +} + +/// A fixed circle of radius 5 at (20, 15) and a point at `at`, kept level with the centre (so +/// a distance from the centre places it). The circle, its centre and the point. +fn circle_and_point(at: Vec2) -> (Sketch, usize, usize, usize) { + let mut sk = Sketch::new(); + let (c, ci) = circle(&mut sk, v(20.0, 15.0), 5.0, true); + let p = sk.add_point(at, None).unwrap(); + sk.add_constraint(ConstraintKind::HorizontalPoints { p: ci, q: p }, None).unwrap(); + (sk, c, ci, p) +} + +/// A fixed circle of radius `ra` at the origin and a free circle of radius `rb` at (`x`, 0), +/// level with it. The sketch, both circles and the free circle's centre. +fn two_circles(ra: f64, x: f64, rb: f64) -> (Sketch, usize, usize, usize) { + let mut sk = Sketch::new(); + let (a, ca) = circle(&mut sk, v(0.0, 0.0), ra, true); + let (b, cb) = circle(&mut sk, v(x, 0.0), rb, false); + sk.add_constraint(ConstraintKind::HorizontalPoints { p: ca, q: cb }, None).unwrap(); + (sk, a, b, cb) +} + +fn measured(sk: &Sketch, k: usize) -> f64 { + solver::measure_dimension(sk, &sk.constraints[k].kind.clone()).unwrap() +} + +#[test] +fn a_point_to_circle_distance_places_the_point_its_gap_from_the_edge() { + let (mut sk, c, _, p) = circle_and_point(v(32.0, 15.0)); + let k = sk.constraints.len(); + sk.add_constraint(ConstraintKind::PointCircleDistance { p, c, value: 7.0, inside: false }, None).unwrap(); + // As drawn the point is 12 from the centre, 12 − 5 = 7 from the edge. + assert!((measured(&sk, k) - 7.0).abs() < 1e-9); + assert!(solve(&mut sk).ok()); + // A gap of 3 puts the point 5 + 3 from the centre, on the side it was drawn on. + sk.constraints[k].kind.set_value(3.0); + let rep = solve(&mut sk); + assert!(rep.ok() && rep.dof == 0, "{rep:?}"); + assert!(sk.points[p].pos.dist(v(28.0, 15.0)) < 1e-7, "{:?}", sk.points[p].pos); + assert!((measured(&sk, k) - 3.0).abs() < 1e-7); + // Zero puts it on the circle. + sk.constraints[k].kind.set_value(0.0); + assert!(solve(&mut sk).ok()); + assert!(sk.points[p].pos.dist(v(25.0, 15.0)) < 1e-7, "{:?}", sk.points[p].pos); +} + +#[test] +fn a_point_inside_the_circle_measures_how_far_within_the_edge_it_lies() { + // 2 from the centre, radius 5: 3 within the edge. + let (mut sk, c, _, p) = circle_and_point(v(22.0, 15.0)); + let k = sk.constraints.len(); + sk.add_constraint(ConstraintKind::PointCircleDistance { p, c, value: 3.0, inside: true }, None).unwrap(); + assert!((measured(&sk, k) - 3.0).abs() < 1e-9); + assert!(solve(&mut sk).ok()); + // 1 within the edge is 4 from the centre: the point stays inside. + sk.constraints[k].kind.set_value(1.0); + let rep = solve(&mut sk); + assert!(rep.ok(), "{rep:?}"); + assert!(sk.points[p].pos.dist(v(24.0, 15.0)) < 1e-7, "{:?}", sk.points[p].pos); +} + +#[test] +fn two_circles_apart_are_placed_their_gap_from_each_other() { + // Centres 20 apart, radii 5 and 3: a gap of 12. + let (mut sk, a, b, cb) = two_circles(5.0, 20.0, 3.0); + let k = sk.constraints.len(); + sk.add_constraint(ConstraintKind::CircleCircleDistance { a, b, value: 12.0, circles: TwoCircles::Apart }, None).unwrap(); + assert!((measured(&sk, k) - 12.0).abs() < 1e-9); + assert!(solve(&mut sk).ok()); + sk.constraints[k].kind.set_value(4.0); + let rep = solve(&mut sk); + assert!(rep.ok() && rep.dof == 0, "{rep:?}"); + assert!(sk.points[cb].pos.dist(v(12.0, 0.0)) < 1e-7, "{:?}", sk.points[cb].pos); + // Tangent: a gap of zero. + sk.constraints[k].kind.set_value(0.0); + assert!(solve(&mut sk).ok()); + assert!(sk.points[cb].pos.dist(v(8.0, 0.0)) < 1e-7, "{:?}", sk.points[cb].pos); +} + +#[test] +fn crossing_circles_measure_how_far_they_overlap() { + // Centres 6 apart, radii 5 and 3: they overlap by 5 + 3 − 6 = 2. + let (mut sk, a, b, cb) = two_circles(5.0, 6.0, 3.0); + let k = sk.constraints.len(); + sk.add_constraint(ConstraintKind::CircleCircleDistance { a, b, value: 2.0, circles: TwoCircles::Crossing }, None).unwrap(); + assert!((measured(&sk, k) - 2.0).abs() < 1e-9); + sk.constraints[k].kind.set_value(1.0); + let rep = solve(&mut sk); + assert!(rep.ok(), "{rep:?}"); + assert!(sk.points[cb].pos.dist(v(7.0, 0.0)) < 1e-7, "{:?}", sk.points[cb].pos); +} + +#[test] +fn nested_circles_measure_the_narrowest_gap_between_them() { + // A radius 3 circle 4 off the centre of a radius 10 one: the wall is 10 − 3 − 4 = 3 at its + // narrowest, whichever circle is named first. + for swap in [false, true] { + let (mut sk, a, b, cb) = two_circles(10.0, 4.0, 3.0); + let (a, b) = if swap { (b, a) } else { (a, b) }; + let k = sk.constraints.len(); + sk.add_constraint(ConstraintKind::CircleCircleDistance { a, b, value: 3.0, circles: TwoCircles::Nested }, None).unwrap(); + assert!((measured(&sk, k) - 3.0).abs() < 1e-9); + sk.constraints[k].kind.set_value(1.0); + let rep = solve(&mut sk); + assert!(rep.ok(), "{rep:?}"); + assert!(sk.points[cb].pos.dist(v(6.0, 0.0)) < 1e-7, "{swap}: {:?}", sk.points[cb].pos); + } +} + +#[test] +fn how_two_circles_lie_and_their_gap() { + use TwoCircles::*; + for (d, ra, rb, lie, gap) in [ + (20.0, 5.0, 3.0, Apart, 12.0), + (8.0, 5.0, 3.0, Apart, 0.0), + (6.0, 5.0, 3.0, Crossing, 2.0), + (4.0, 10.0, 3.0, Nested, 3.0), + (0.0, 3.0, 10.0, Nested, 7.0), + ] { + assert_eq!(TwoCircles::of(d, ra, rb), lie, "{d} {ra} {rb}"); + assert!((lie.gap(d, ra, rb) - gap).abs() < 1e-12, "{d} {ra} {rb}"); + assert!((lie.centres_apart(gap, ra, rb) - d).abs() < 1e-12, "{d} {ra} {rb}"); + } +} + +#[test] +fn arcs_are_measured_to_their_circles() { + let mut sk = Sketch::new(); + let p = sk.add_point(v(20.0, 0.0), None).unwrap(); + // Centre (20, 20), radius 6. + let arc = sk.add_arc(v(20.0, 20.0), v(26.0, 20.0), v(14.0, 20.0), [None; 3], None).unwrap(); + let c = sk.add_circle(v(40.0, 20.0), 4.0, None, None).unwrap(); + let k = sk.constraints.len(); + sk.add_constraint(ConstraintKind::PointCircleDistance { p, c: arc, value: 14.0, inside: false }, None).unwrap(); + sk.add_constraint(ConstraintKind::CircleCircleDistance { a: arc, b: c, value: 10.0, circles: TwoCircles::Apart }, None).unwrap(); + assert!((measured(&sk, k) - 14.0).abs() < 1e-9); + // Centres 20 apart, radii 6 and 4. + assert!((measured(&sk, k + 1) - 10.0).abs() < 1e-9); +} + +#[test] +fn the_dimensions_need_circles_or_arcs() { + let mut sk = Sketch::new(); + let l = sk.add_line(v(0.0, 0.0), v(40.0, 0.0), None, None, None).unwrap(); + let c = sk.add_circle(v(20.0, 20.0), 5.0, None, None).unwrap(); + let (ec, em) = (sk.add_point(v(60.0, 20.0), None).unwrap(), sk.add_point(v(70.0, 20.0), None).unwrap()); + let e = sk.add_curve(CurveKind::Ellipse { c: ec, m: em, r: 4.0 }, None).unwrap(); + let p = sk.add_point(v(0.0, 30.0), None).unwrap(); + for c in [l, e] { + assert!(sk.add_constraint(ConstraintKind::PointCircleDistance { p, c, value: 1.0, inside: false }, None).is_err(), "{c}"); + } + for (a, b) in [(c, c), (c, l), (l, c), (c, e)] { + let k = ConstraintKind::CircleCircleDistance { a, b, value: 1.0, circles: TwoCircles::Apart }; + assert!(sk.add_constraint(k, None).is_err(), "{a} {b}"); + } + for value in [-1.0, f64::NAN, f64::INFINITY] { + assert!(sk.add_constraint(ConstraintKind::PointCircleDistance { p, c, value, inside: false }, None).is_err(), "{value}"); + } +} + +#[test] +fn the_dimensions_survive_a_round_trip_and_a_renumbering() { + let (mut sk, a, b, _) = two_circles(10.0, 4.0, 3.0); + let p = sk.add_point(v(30.0, 0.0), None).unwrap(); + sk.add_constraint(ConstraintKind::PointCircleDistance { p, c: a, value: 1.0, inside: true }, None).unwrap(); + sk.add_constraint(ConstraintKind::CircleCircleDistance { a, b, value: 3.0, circles: TwoCircles::Nested }, None).unwrap(); + let json = serde_json::to_value(&sk).unwrap(); + let saved = json["constraints"].as_array().unwrap(); + let (point, circles) = (&saved[saved.len() - 2], &saved[saved.len() - 1]); + assert_eq!(point["type"], "point_circle_distance", "{point}"); + assert_eq!(point["inside"], true, "{point}"); + assert_eq!(circles["type"], "circle_circle_distance", "{circles}"); + assert_eq!(circles["circles"], "nested", "{circles}"); + let back: Sketch = serde_json::from_value(json).unwrap(); + assert_eq!(back.constraints, sk.constraints); + // The defaults (a point outside, circles apart) are left out. + let outside = ConstraintKind::PointCircleDistance { p, c: a, value: 1.0, inside: false }; + assert!(serde_json::to_value(&outside).unwrap().get("inside").is_none()); + let apart = ConstraintKind::CircleCircleDistance { a, b, value: 1.0, circles: TwoCircles::Apart }; + assert!(serde_json::to_value(&apart).unwrap().get("circles").is_none()); + let mut k = outside; + assert!(k.remap(&|q| Some(q + 1), &|i| Some(i + 10))); + assert_eq!(k.indices(), (vec![p + 1], vec![a + 10])); + assert!(!k.remap(&|_| None, &|i| Some(i))); + let mut k = apart; + assert!(k.remap(&|q| Some(q), &|i| Some(i + 10))); + assert_eq!(k.indices(), (vec![], vec![a + 10, b + 10])); + assert!(!k.remap(&|q| Some(q), &|_| None)); +} + +/// With a radius known and the other coordinate set, the seed places the point or the centre +/// exactly, before the numerical solver runs. +#[test] +fn the_seed_places_them_by_construction() { + // The point 5 right of the centre and 8 from the edge: 13 from the centre, so 12 above it. + let (mut sk, c, ci, p) = circle_and_point(v(24.0, 15.0)); + sk.constraints.retain(|k| !matches!(k.kind, ConstraintKind::HorizontalPoints { .. })); + sk.points[p].pos = v(24.0, 26.0); + sk.add_constraint(ConstraintKind::DistanceX { p: ci, q: p, value: 5.0 }, None).unwrap(); + sk.add_constraint(ConstraintKind::PointCircleDistance { p, c, value: 8.0, inside: false }, None).unwrap(); + let out = crate::tests::seed_of(&sk); + assert!(out.placed_by[p].is_some_and(crate::construct::Placement::anchors), "{out:?}"); + assert!(out.pos[p].unwrap().dist(v(25.0, 27.0)) < 1e-9, "{out:?}"); + let rep = solve(&mut sk); + assert!(rep.ok() && rep.dof == 0, "{rep:?}"); + assert!(sk.points[p].pos.dist(v(25.0, 27.0)) < 1e-9, "{:?}", sk.points[p].pos); + // Circles apart by 4, radii 5 and 3: the free centre 12 along the level line. + let (mut sk, a, b, cb) = two_circles(5.0, 20.0, 3.0); + sk.add_constraint(ConstraintKind::CircleCircleDistance { a, b, value: 4.0, circles: TwoCircles::Apart }, None).unwrap(); + let out = crate::tests::seed_of(&sk); + assert!(out.placed_by[cb].is_some_and(crate::construct::Placement::anchors), "{out:?}"); + assert!(out.pos[cb].unwrap().dist(v(12.0, 0.0)) < 1e-9, "{out:?}"); +} + +/// The dimension line runs between the edge points that face each other: from the edge to the +/// point along the radius, and along the line through two centres. +#[test] +fn the_dimensions_are_drawn_between_the_facing_edge_points() { + let linear = |sk: &Sketch, k: &ConstraintKind| match dim_frame(sk, k) { + Some(DimFrame::Linear { p0, p1, dir }) => (p0, p1, dir), + f => panic!("{f:?}"), + }; + let (sk, c, _, p) = circle_and_point(v(32.0, 15.0)); + let (p0, p1, dir) = linear(&sk, &ConstraintKind::PointCircleDistance { p, c, value: 7.0, inside: false }); + assert!(p0.dist(v(25.0, 15.0)) < 1e-12 && p1.dist(v(32.0, 15.0)) < 1e-12 && dir.dist(Vec2::X) < 1e-12, "{p0:?} {p1:?} {dir:?}"); + // Apart: from a's edge towards b to b's edge towards a. + let (sk, a, b, _) = two_circles(5.0, 20.0, 3.0); + let (p0, p1, _) = linear(&sk, &ConstraintKind::CircleCircleDistance { a, b, value: 12.0, circles: TwoCircles::Apart }); + assert!(p0.dist(v(5.0, 0.0)) < 1e-12 && p1.dist(v(17.0, 0.0)) < 1e-12, "{p0:?} {p1:?}"); + // Nested, either way round: across the narrowest part of the wall, from 7 to 10. + let (sk, a, b, _) = two_circles(10.0, 4.0, 3.0); + for (a, b) in [(a, b), (b, a)] { + let (p0, p1, _) = linear(&sk, &ConstraintKind::CircleCircleDistance { a, b, value: 3.0, circles: TwoCircles::Nested }); + let (lo, hi) = if p0.x < p1.x { (p0, p1) } else { (p1, p0) }; + assert!(lo.dist(v(7.0, 0.0)) < 1e-12 && hi.dist(v(10.0, 0.0)) < 1e-12, "{p0:?} {p1:?}"); + } +} diff --git a/crates/sketch/src/dims.rs b/crates/sketch/src/dims.rs index 403510d7e..165717411 100644 --- a/crates/sketch/src/dims.rs +++ b/crates/sketch/src/dims.rs @@ -10,7 +10,7 @@ use solidcraft_geom::Vec2; -use crate::model::{ConstraintKind, CurveKind, Sketch}; +use crate::model::{ConstraintKind, CurveKind, Sketch, TwoCircles}; use crate::union_find::{find, union}; /// What a dimension measures, in a form that can be drawn. @@ -104,6 +104,26 @@ pub fn dim_frame(sk: &Sketch, k: &ConstraintKind) -> Option { let p0 = a + d * (p1 - a).dot(d); DimFrame::Linear { p0, p1, dir: unit(p1 - p0, normal) } } + PointCircleDistance { p, c, .. } => { + // From the circle's edge, where the radius through the point crosses it, to the point. + let q = sk.point(p)?; + let (centre, r) = (sk.center(c)?, sk.radius(c)?); + let u = unit(q - centre, Vec2::X); + let edge = centre + u * r; + DimFrame::Linear { p0: edge, p1: q, dir: unit(q - edge, u) } + } + CircleCircleDistance { a, b, circles, .. } => { + // Along the line through the centres, between the edge points that face each other: + // for nested circles, where the inner one comes nearest the outer one. + let ((ca, ra), (cb, rb)) = ((sk.center(a)?, sk.radius(a)?), (sk.center(b)?, sk.radius(b)?)); + let u = unit(cb - ca, Vec2::X); + let (p0, p1) = match circles { + TwoCircles::Nested if ra >= rb => (cb + u * rb, ca + u * ra), + TwoCircles::Nested => (ca - u * ra, cb - u * rb), + TwoCircles::Apart | TwoCircles::Crossing => (ca + u * ra, cb - u * rb), + }; + DimFrame::Linear { p0, p1, dir: u } + } Radius { c, .. } | Diameter { c, .. } => { let (radius, arc) = match sk.curves.get(c)?.kind { CurveKind::Ellipse { r, .. } => (r, None), diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs index d95a7f102..2a72ee048 100644 --- a/crates/sketch/src/lib.rs +++ b/crates/sketch/src/lib.rs @@ -53,7 +53,7 @@ pub use freeform_offset::{FreeformOffset, FreeformOffsetOutput, 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, PointExprs, SPoint, Sketch, SketchError, - SketchView, + SketchView, TwoCircles, }; pub use offset::OffsetChain; pub use offset_topology::{OffsetCreated, OffsetRole, OffsetRoleFlags, OffsetRoleKind, OffsetTopology}; @@ -74,6 +74,8 @@ pub use text::{MAX_TEXT_CHARS, TextAlign, TextMetrics, TextStyle, text_geometry, pub use thin::{MAX_THIN_SEGMENTS, thin_wall_regions}; pub use wire::{MAX_FIT_POINTS, MAX_WIRE_POINTS, Wire, WireSpace, fit_polyline}; +#[cfg(test)] +mod circle_edge_tests; #[cfg(test)] mod construct_rounds_tests; #[cfg(test)] diff --git a/crates/sketch/src/loci.rs b/crates/sketch/src/loci.rs index 62a8edfee..2dbe5d758 100644 --- a/crates/sketch/src/loci.rs +++ b/crates/sketch/src/loci.rs @@ -895,6 +895,23 @@ pub(crate) fn read(sk: &Sketch, before: &dyn Fn(usize) -> Option, on_curve ties.push(Tie::Offset { p: rd.c, l, len: Len::Value(d) }); } } + // The point lies radius ± the gap from the centre. + PointCircleDistance { p, c, value, inside } => { + if let (Some(rd), Some(r)) = (round(c), r_of(c)) + && let Some(d) = dim(if inside { r - value } else { r + value }) + { + rel(rd.c, p, Rel::Dist(d)); + } + } + // The centres lie the radii and the gap apart, as the circles lie. + CircleCircleDistance { a, b, value, circles } => { + if let (Some(ra), Some(rb)) = (round(a), round(b)) + && let (Some(r_a), Some(r_b)) = (r_of(a), r_of(b)) + && let Some(d) = dim(circles.centres_apart(value, r_a, r_b)) + { + rel(ra.c, rb.c, Rel::Dist(d)); + } + } Tangent { a, b } => { let (l, curve) = if line(a).is_some() { (a, b) } else { (b, a) }; if line(l).is_some() diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index e9bac7b80..d426826c4 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -202,6 +202,55 @@ pub struct Curve { pub infinite: bool, } +/// How two circles lie, for a [`ConstraintKind::CircleCircleDistance`]: which gap between their +/// edges it measures, along the line through their centres. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TwoCircles { + /// Each outside the other: the gap between them, `distance − ra − rb`. + #[default] + Apart, + /// Crossing each other: how far they overlap, `ra + rb − distance`. + Crossing, + /// One inside the other: the narrowest gap between the inner one and the outer one, + /// `|ra − rb| − distance`. + Nested, +} + +impl TwoCircles { + /// Saved only when the circles are not apart. + pub fn is_apart(&self) -> bool { + *self == TwoCircles::Apart + } + /// How circles of radii `ra` and `rb` with centres `distance` apart lie (touching circles + /// count as apart, or as nested when one touches the other from inside). + pub fn of(distance: f64, ra: f64, rb: f64) -> TwoCircles { + if distance >= ra + rb { + TwoCircles::Apart + } else if distance <= (ra - rb).abs() { + TwoCircles::Nested + } else { + TwoCircles::Crossing + } + } + /// The gap between the edges of such circles (what the dimension measures). + pub fn gap(self, distance: f64, ra: f64, rb: f64) -> f64 { + match self { + TwoCircles::Apart => distance - ra - rb, + TwoCircles::Crossing => ra + rb - distance, + TwoCircles::Nested => (ra - rb).abs() - distance, + } + } + /// How far apart the centres are when the gap is `value` (the inverse of [`Self::gap`]). + pub fn centres_apart(self, value: f64, ra: f64, rb: f64) -> f64 { + match self { + TwoCircles::Apart => ra + rb + value, + TwoCircles::Crossing => ra + rb - value, + TwoCircles::Nested => (ra - rb).abs() - value, + } + } +} + /// Geometric constraints and dimensions. Indices refer to `Sketch::points` (`p`, `q`) or /// `Sketch::curves` (`l`, `c`, `a`, `b`). Dimension values are millimetres or radians. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -314,6 +363,28 @@ pub enum ConstraintKind { #[serde(default, skip_serializing_if = "std::ops::Not::not")] inside: bool, }, + /// Distance from point `p` to the edge of circle or arc `c`, along the radius through the + /// point: `|p − centre| − radius` while the point is outside the circle or, `inside`, how + /// far within the edge it lies, `radius − |p − centre|`. Zero puts the point on the circle. + /// An arc is measured to its whole circle. + PointCircleDistance { + p: usize, + c: usize, + value: f64, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + inside: bool, + }, + /// Distance between the edges of circles or arcs `a` and `b`, along the line through their + /// centres: the gap between them, how far they overlap, or the narrowest gap between the + /// inner one and the outer one, as `circles` says ([`TwoCircles`]). Zero is tangency in each + /// case. Arcs are measured to their whole circles. + CircleCircleDistance { + a: usize, + b: usize, + value: f64, + #[serde(default, skip_serializing_if = "TwoCircles::is_apart")] + circles: TwoCircles, + }, Length { l: usize, value: f64, @@ -392,6 +463,8 @@ impl ConstraintKind { | DistanceY { value, .. } | PointLineDistance { value, .. } | LineCircleDistance { value, .. } + | PointCircleDistance { value, .. } + | CircleCircleDistance { value, .. } | Length { value, .. } | LineAngle { value, .. } | ArcSweep { value, .. } @@ -413,6 +486,8 @@ impl ConstraintKind { | DistanceY { value, .. } | PointLineDistance { value, .. } | LineCircleDistance { value, .. } + | PointCircleDistance { value, .. } + | CircleCircleDistance { value, .. } | Length { value, .. } | LineAngle { value, .. } | ArcSweep { value, .. } @@ -446,9 +521,14 @@ impl ConstraintKind { Midpoint { .. } => "MidPoint", Symmetric { .. } => "Symmetry", Fix { .. } => "Fix", - Distance { .. } | DistanceX { .. } | DistanceY { .. } | PointLineDistance { .. } | LineCircleDistance { .. } | Length { .. } => { - "LinearDimension" - } + Distance { .. } + | DistanceX { .. } + | DistanceY { .. } + | PointLineDistance { .. } + | LineCircleDistance { .. } + | PointCircleDistance { .. } + | CircleCircleDistance { .. } + | Length { .. } => "LinearDimension", Radius { .. } => "RadialDimension", Diameter { .. } => "DiameterDimension", Angle { .. } | LineAngle { .. } | ArcSweep { .. } => "AngularDimension", @@ -482,6 +562,8 @@ impl ConstraintKind { Angle { a, b, .. } | SlotOverallLength { a, b, .. } => (vec![], vec![a, b]), Midpoint { p, l } | PointLineDistance { p, l, .. } => (vec![p], vec![l]), LineCircleDistance { l, c, .. } => (vec![], vec![l, c]), + PointCircleDistance { p, c, .. } => (vec![p], vec![c]), + CircleCircleDistance { a, b, .. } => (vec![], vec![a, b]), Symmetric { p, q, l } => (vec![p, q], vec![l]), Fix { p } => (vec![p], vec![]), Smooth { a, b } => (vec![], vec![a, b]), @@ -549,6 +631,14 @@ impl ConstraintKind { fc(l); fc(c); } + PointCircleDistance { p, c, .. } => { + fp(p); + fc(c); + } + CircleCircleDistance { a, b, .. } => { + fc(a); + fc(b); + } Symmetric { p, q, l } => { fp(p); fp(q); @@ -993,6 +1083,14 @@ impl Sketch { need_line(l)?; need_round(c)?; } + PointCircleDistance { c, .. } => need_round(c)?, + CircleCircleDistance { a, b, .. } => { + if a == b { + return Err(SketchError::Invalid("a distance between circles needs two different circles or arcs".into())); + } + need_round(a)?; + need_round(b)?; + } Tangent { a, b } => { let free = |i: usize| self.curves.get(i).is_some_and(|c| c.kind.is_freeform()); if !(is_round(a) || is_round(b) || free(a) || free(b)) { diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs index 3df93dfbb..4872af3e9 100644 --- a/crates/sketch/src/solver.rs +++ b/crates/sketch/src/solver.rs @@ -18,7 +18,7 @@ use solidcraft_geom::{Seg2, Vec2}; use crate::decompose::Budget; use crate::linalg::{Mat, determined_vars, solve as lin_solve}; -use crate::model::{ConstraintKind, CurveKind, Sketch}; +use crate::model::{ConstraintKind, CurveKind, Sketch, TwoCircles}; #[cfg(feature = "solver-profiling")] use crate::profiling::{self, Decision, Phase, StopReason}; use crate::union_find::{find, union}; @@ -366,6 +366,19 @@ impl State<'_> { let d = line_dist(cc, a, b).abs(); if inside { r - d } else { d - r } } + /// What a point-to-circle distance measures: the gap from point `p` to the edge of circle + /// or arc `c`, or (`inside`) how far within the edge the point lies. + fn point_circle_gap(&self, p: usize, c: usize, inside: bool) -> f64 { + let (cc, r) = self.round(c); + let d = self.p(p).dist(cc); + if inside { r - d } else { d - r } + } + /// What a distance between two circles or arcs measures, as they lie (`circles`). + fn circle_circle_gap(&self, a: usize, b: usize, circles: TwoCircles) -> f64 { + let (ca, ra) = self.round(a); + let (cb, rb) = self.round(b); + circles.gap(ca.dist(cb), ra, rb) + } fn slot_length(&self, a: usize, b: usize) -> f64 { let (ca, ra) = self.round(a); let (cb, rb) = self.round(b); @@ -567,6 +580,8 @@ fn residuals(s: &State, k: &ConstraintKind, out: &mut Vec) { out.push(line_dist(s.p(p), a, b).abs() - value); } LineCircleDistance { l, c, value, inside } => out.push(s.line_circle_gap(l, c, inside) - value), + PointCircleDistance { p, c, value, inside } => out.push(s.point_circle_gap(p, c, inside) - value), + CircleCircleDistance { a, b, value, circles } => out.push(s.circle_circle_gap(a, b, circles) - value), Length { l, value } => { let (a, b) = s.line(l); out.push(a.dist(b) - value); @@ -630,6 +645,8 @@ fn measure(s: &State, k: &ConstraintKind) -> Option { line_dist(s.p(p), a, b).abs() } LineCircleDistance { l, c, inside, .. } => s.line_circle_gap(l, c, inside), + PointCircleDistance { p, c, inside, .. } => s.point_circle_gap(p, c, inside), + CircleCircleDistance { a, b, circles, .. } => s.circle_circle_gap(a, b, circles), Length { l, .. } => { let (a, b) = s.line(l); a.dist(b) @@ -838,6 +855,8 @@ fn block_refs(sk: &Sketch, b: &Block) -> Vec { PointOnCurve { p, c } => vec![P(p), C(c)], Midpoint { p, l } | PointLineDistance { p, l, .. } | LinearDiameter { p, l, .. } => vec![P(p), L(l)], LineCircleDistance { l, c, .. } => vec![L(l), R(c)], + PointCircleDistance { p, c, .. } => vec![P(p), R(c)], + CircleCircleDistance { a, b, .. } => vec![R(a), R(b)], Horizontal { l } | Vertical { l } | Length { l, .. } | LineAngle { l, .. } => vec![L(l)], // Another kind reads a constant value, whatever its points: as good as any. ArcSweep { c, .. } | Radius { c, .. } | Diameter { c, .. } | ArcLength { c, .. } => vec![C(c)], diff --git a/crates/ui-egui/src/dim_view.rs b/crates/ui-egui/src/dim_view.rs index 69111f584..a8e116614 100644 --- a/crates/ui-egui/src/dim_view.rs +++ b/crates/ui-egui/src/dim_view.rs @@ -614,7 +614,12 @@ fn first_point(sk: &solidcraft_engine::sketch::Sketch, k: &ConstraintKind) -> Op use ConstraintKind::*; match *k { Length { l, .. } => sk.curves.get(l).and_then(|c| c.kind.point_ids().first().copied()), - Distance { p, .. } | DistanceX { p, .. } | DistanceY { p, .. } | PointLineDistance { p, .. } | LinearDiameter { p, .. } => Some(p), + Distance { p, .. } + | DistanceX { p, .. } + | DistanceY { p, .. } + | PointLineDistance { p, .. } + | PointCircleDistance { p, .. } + | LinearDiameter { p, .. } => Some(p), _ => None, } } diff --git a/crates/ui-egui/tests/scenarios/sketch_dimension_circle_to_circle_edge.json b/crates/ui-egui/tests/scenarios/sketch_dimension_circle_to_circle_edge.json new file mode 100644 index 000000000..96a9e0611 --- /dev/null +++ b/crates/ui-egui/tests/scenarios/sketch_dimension_circle_to_circle_edge.json @@ -0,0 +1,21 @@ +[ + {"call": "engine.execute", "params": {"command": "sketch.create", "params": {"plane": "XY"}}}, + {"call": "engine.execute", "params": {"command": "sketch.circle.center", "params": {"center": [10, 10], "radius": 5}}}, + {"call": "engine.execute", "params": {"command": "sketch.constraint.fix", "params": {"entities": ["c1.center"]}}}, + {"call": "engine.execute", "params": {"command": "sketch.dimension", "params": {"entities": ["c1"], "type": "diameter", "value": 10, "text_at": [2, 20]}}}, + {"call": "engine.execute", "params": {"command": "sketch.circle.center", "params": {"center": [30, 10], "radius": 3}}}, + {"call": "engine.execute", "params": {"command": "sketch.dimension", "params": {"entities": ["c2"], "type": "diameter", "value": 6, "text_at": [36, 18]}}}, + {"call": "engine.execute", "params": {"command": "sketch.constraint.horizontal_vertical", "params": {"points": ["c1.center", "c2.center"], "mode": "horizontal"}}}, + {"call": "ui.view", "params": {"view": "top"}}, + {"call": "ui.view", "params": {"view": "fit"}}, + {"start": "sketch.dimension"}, + {"click": {"sketch": [10, 5]}}, + {"click": {"sketch": [30, 7]}}, + {"text": "4"}, + {"key": "Enter"}, + {"key": "Escape"}, + {"expect": {"errors": 0}}, + {"expect": {"param": {"d3": 4}}}, + {"expect": {"query": {"command": "sketch.inspect", "path": ["curves", 1, "center_at", 0], "value": 22}}}, + {"expect": {"query": {"command": "sketch.inspect", "path": ["curves", 1, "center_at", 1], "value": 10}}} +] diff --git a/crates/ui-egui/tests/scenarios/sketch_dimension_point_to_circle_edge.json b/crates/ui-egui/tests/scenarios/sketch_dimension_point_to_circle_edge.json new file mode 100644 index 000000000..c76612ca4 --- /dev/null +++ b/crates/ui-egui/tests/scenarios/sketch_dimension_point_to_circle_edge.json @@ -0,0 +1,20 @@ +[ + {"call": "engine.execute", "params": {"command": "sketch.create", "params": {"plane": "XY"}}}, + {"call": "engine.execute", "params": {"command": "sketch.circle.center", "params": {"center": [20, 15], "radius": 5}}}, + {"call": "engine.execute", "params": {"command": "sketch.constraint.fix", "params": {"entities": ["c1.center"]}}}, + {"call": "engine.execute", "params": {"command": "sketch.dimension", "params": {"entities": ["c1"], "type": "diameter", "value": 10, "text_at": [12, 24]}}}, + {"call": "engine.execute", "params": {"command": "sketch.line", "params": {"points": [[32, 15], [32, 25]]}}}, + {"call": "engine.execute", "params": {"command": "sketch.constraint.horizontal_vertical", "params": {"points": ["c1.center", "l1.start"], "mode": "horizontal"}}}, + {"call": "ui.view", "params": {"view": "top"}}, + {"call": "ui.view", "params": {"view": "fit"}}, + {"start": "sketch.dimension"}, + {"click": {"sketch": [32, 15]}}, + {"click": {"sketch": [20, 20]}}, + {"text": "3"}, + {"key": "Enter"}, + {"key": "Escape"}, + {"expect": {"errors": 0}}, + {"expect": {"param": {"d2": 3}}}, + {"expect": {"query": {"command": "sketch.inspect", "path": ["curves", 1, "start_at", 0], "value": 28}}}, + {"expect": {"query": {"command": "sketch.inspect", "path": ["curves", 1, "start_at", 1], "value": 15}}} +] diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md index d632cdd21..f5142fff2 100644 --- a/docs/book/src/guide/sketching.md +++ b/docs/book/src/guide/sketching.md @@ -196,8 +196,8 @@ Scripts use the same command, with a midpoint reference in the `points` array: The solver is SolidCraft's own (damped Gauss–Newton with degree-of-freedom analysis). Constraints: coincident, horizontal/vertical, parallel, perpendicular, tangent, equal, concentric, collinear, midpoint, symmetry, fix, curvature (G2) and polygon. **Sketch Dimension** (D) adds linear, -aligned, horizontal, vertical, point-to-line, line-to-circle, radius, diameter and angle -dimensions. Each is a parameter +aligned, horizontal, vertical, point-to-line, line-to-circle, point-to-circle, circle-to-circle, +radius, diameter and angle dimensions. Each is a parameter (`d1`, `d2`, …), so it can hold an expression. Press D, click what you want to measure and type the value: as soon as the click settles the @@ -230,6 +230,13 @@ far the edge reaches past the line instead. An arc is measured to the circle it the distance to the centre, click the centre point instead of the edge. In scripts: `{"command": "sketch.dimension", "params": {"entities": ["l1", "c1"], "value": 5}}`. +A point and a circle or arc measure from the point to the circle's edge, along the radius +through the point: 0 puts the point on the circle, and a point inside the circle measures how +far within the edge it lies. Two circles or arcs measure between their edges, along the line +through their centres: the gap between them (0 when they touch), how far they overlap when they +cross, or, when one lies inside the other, the narrowest gap between them (the thinnest part of +the wall). For the distance between the centres, click the two centre points instead. + A dimension the sketch can't take, because the geometry is already fixed by other constraints and dimensions, is added as a driven (reference) dimension instead: it is shown in parentheses, measures the sketch, and has no value to edit. diff --git a/docs/capabilities.md b/docs/capabilities.md index c35c052dc..a1d909e32 100644 --- a/docs/capabilities.md +++ b/docs/capabilities.md @@ -31,7 +31,7 @@ and help is welcome: see [CONTRIBUTING.md](../CONTRIBUTING.md). and the rank of its Jacobian gives the remaining degrees of freedom. Constraints: coincident, point on curve, horizontal/vertical, parallel, perpendicular, tangent, curvature (G2), equal, concentric, collinear, midpoint, symmetry, fix; linear, aligned, horizontal, vertical, - point-to-line, line-to-circle, radius, diameter, angle, arc sweep, arc length and slot length dimensions driven + point-to-line, line-to-circle, point-to-circle, circle-to-circle, radius, diameter, angle, arc sweep, arc length and slot length dimensions driven by parameters. Over-constraining edits are rejected; fully constrained geometry turns black. Dragging solves the sketch every frame and rebuilds the model once, when the drag ends. Select a line or its two endpoints, type its dimension and press Enter to commit one undo diff --git a/skills/solidcraft-modeling/reference.md b/skills/solidcraft-modeling/reference.md index 88a43fb47..a8a58452f 100644 --- a/skills/solidcraft-modeling/reference.md +++ b/skills/solidcraft-modeling/reference.md @@ -48,9 +48,10 @@ These are the shapes of the commands a part build needs, so an agent rarely has {"command":"sketch.dimension","params":{"entities":["c1"],"type":"diameter","value":"6"}} {"command":"sketch.dimension","params":{"entities":["l1"],"value":"w"}} {"command":"sketch.dimension","params":{"entities":["l1","c1"],"value":"2"}} +{"command":"sketch.dimension","params":{"entities":["c1","c2"],"value":"3"}} ``` -A line with a circle or arc measures from the line to its edge (0 is tangent); give the centre point (`c1.center`) for the distance to the centre. +A line, a point or another circle with a circle or arc measures to its edge (0 is tangent, or the point on the circle); two circles measure between their edges (the overlap when they cross, the thinnest wall when one is inside the other). Give the centre point (`c1.center`) for the distance to the centre. Distances are unsigned. Draw the geometry on the correct side first, and the dimension keeps it there.