diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index b62e8aae1..66fd62490 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -2188,6 +2188,10 @@ mod offset_identity_tests; #[path = "offset_edit_guard_tests.rs"] mod offset_edit_guard_tests; +#[cfg(test)] +#[path = "offset_ends_tests.rs"] +mod offset_ends_tests; + #[cfg(test)] #[path = "offset_plane_face_tests.rs"] mod offset_plane_face_tests; diff --git a/crates/engine/src/cmd/offset_ends_tests.rs b/crates/engine/src/cmd/offset_ends_tests.rs new file mode 100644 index 000000000..9ebb58dcd --- /dev/null +++ b/crates/engine/src/cmd/offset_ends_tests.rs @@ -0,0 +1,88 @@ +#![allow(clippy::unwrap_used, clippy::panic)] +//! #2424: curves start at the ends of an associated offset spline, and follow them. +use serde_json::{Value, json}; +use solidcraft_doc::Document; +use solidcraft_sketch::{ConstraintKind, CurveKind, Sketch}; + +use crate::Session; + +fn run(s: &mut Session, command: &str, params: Value) -> Value { + s.execute(command, ¶ms).unwrap_or_else(|error| panic!("{command}: {error}")) +} +fn solved(s: &Session, id: u64) -> Sketch { + s.model.state().sketch(id).unwrap().sketch.clone() +} +/// An open fit-point spline `s1` and its associated offset; returns the offset's id. +fn offset_spline(s: &mut Session) -> (u64, String) { + run(s, "sketch.create", json!({"plane":"XY"})); + let sketch = s.active_sketch.unwrap(); + run(s, "sketch.spline.fit_point", json!({"points":[[0,0],[10,5],[20,0],[30,5]],"ids":["s1"]})); + let result = run(s, "sketch.offset", json!({"curves":["s1"],"distance":"2 mm","chain":true})); + (sketch, result["curves"][0].as_str().unwrap().into()) +} +fn coincident(sk: &Sketch, a: usize, b: usize) -> bool { + sk.constraints.iter().any(|k| matches!(k.kind, ConstraintKind::Coincident { p, q } if (p, q) == (a, b) || (p, q) == (b, a))) +} + +#[test] +fn lines_drawn_from_offset_spline_ends_get_their_own_coincident_points() { + let mut s = Session::default(); + let (id, output) = offset_spline(&mut s); + // Close the shape between the spline and its offset at both ends. + run(&mut s, "sketch.line", json!({"points":["s1.start", format!("{output}.start")],"ids":["l1"]})); + run(&mut s, "sketch.line", json!({"points":[format!("{output}.end"), "s1.end"],"ids":["l2"]})); + let sk = solved(&s, id); + sk.validate_freeform_offsets().unwrap(); + let o = sk.curve_index(&output).unwrap(); + let (start, end) = sk.curves[o].kind.ends().unwrap(); + let (l1, l2) = (sk.curve_index("l1").unwrap(), sk.curve_index("l2").unwrap()); + let (CurveKind::Line { b: l1_end, .. }, CurveKind::Line { a: l2_start, .. }) = (&sk.curves[l1].kind, &sk.curves[l2].kind) else { + panic!("lines") + }; + assert!(*l1_end != start && *l2_start != end, "the offset keeps sole ownership of its nodes"); + assert!(coincident(&sk, start, *l1_end) && coincident(&sk, end, *l2_start)); + assert!(sk.points[*l1_end].pos.dist(sk.points[start].pos) < 1e-9); + + // Moving the source moves the offset, and the lines follow its ends. + let from = sk.point(sk.resolve_point("s1.start").unwrap()).unwrap(); + run(&mut s, "sketch.drag", json!({"entity":"s1.start","from":[from.x, from.y],"to":[from.x - 3.0, from.y + 2.0]})); + let moved = solved(&s, id); + moved.validate_freeform_offsets().unwrap(); + assert!(moved.points[start].pos.dist(sk.points[start].pos) > 1.0, "the offset followed its source"); + assert!(moved.points[*l1_end].pos.dist(moved.points[start].pos) < 1e-6); + assert!(moved.points[*l2_start].pos.dist(moved.points[end].pos) < 1e-6); + + // The design saves and loads with the connection. + let doc = Document::from_json(&s.doc.to_json()).unwrap(); + let loaded = doc.sketch(id).unwrap(); + loaded.validate_freeform_offsets().unwrap(); + assert!(coincident(loaded, start, *l1_end)); +} + +#[test] +fn an_arc_from_an_offset_end_is_drawn_and_undone_atomically() { + let mut s = Session::default(); + let (id, output) = offset_spline(&mut s); + let before = s.doc.to_json(); + run(&mut s, "sketch.arc.three_point", json!({"start":format!("{output}.end"),"through":[33,3],"end":"s1.end"})); + let sk = solved(&s, id); + sk.validate_freeform_offsets().unwrap(); + let end = sk.curves[sk.curve_index(&output).unwrap()].kind.ends().unwrap().1; + assert_eq!(sk.curves.iter().filter(|c| c.kind.uses(end)).count(), 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); +} + +#[test] +fn an_open_offset_spline_shows_only_its_ends() { + let mut s = Session::default(); + let (id, output) = offset_spline(&mut s); + let sk = solved(&s, id); + let o = sk.curve_index(&output).unwrap(); + let (start, end) = sk.curves[o].kind.ends().unwrap(); + let nodes = sk.curves[o].kind.point_ids(); + assert!(nodes.len() > 2); + for i in nodes { + assert_eq!(crate::view::sketch_point_visible(&sk, i), i == start || i == end, "node {i}"); + } +} diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index a9b6ec59d..f97f4575f 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -275,6 +275,8 @@ pub(super) fn edit_solved( // The stored sketch is solved for its stored values. let stored = sk.driving_values(); let (out, left) = f(&mut sk, &mut doc)?; + // A curve that took an offset spline's generated node (drawn from its end) gets its own point there. + sk.detach_offset_points()?; let offsets = !sk.offsets.is_empty() || !sk.freeform_offsets.is_empty(); let rep = match left { // A drag step solved it (held, with the dimensions' values applied). diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 7a4e65845..a645e9fd6 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -301,7 +301,8 @@ pub fn sketch_curve_visible(sk: &Sketch, i: usize) -> bool { } /// Point roles shown and picked individually. Associated offsets keep their generated -/// fit nodes private until their association is broken. Build once per sketch/frame. +/// fit nodes private until their association is broken, except an open offset's two ends, +/// which other curves snap and constrain to. Build once per sketch/frame. pub struct SketchPointVisibility<'a> { hidden: std::collections::HashSet<&'a str>, } @@ -321,7 +322,9 @@ impl<'a> SketchPointVisibility<'a> { let mut hidden: std::collections::HashSet<&str> = sk.points.iter().filter(|p| p.link.as_deref().is_some_and(|l| text.contains(l))).map(|p| p.id.as_str()).collect(); for curve in sk.curves.iter().filter(|c| outputs.contains(c.id.as_str())) { - hidden.extend(curve.kind.point_ids().into_iter().filter_map(|i| sk.points.get(i).map(|p| p.id.as_str()))); + let ends = curve.kind.ends(); + let interior = curve.kind.point_ids().into_iter().filter(|i| ends.is_none_or(|(a, b)| *i != a && *i != b)); + hidden.extend(interior.filter_map(|i| sk.points.get(i).map(|p| p.id.as_str()))); } Self { hidden } } @@ -332,7 +335,7 @@ impl<'a> SketchPointVisibility<'a> { } /// Should sketch point `i` be drawn or picked individually? Text outlines and derived -/// offset fit nodes are private. Batch callers use [`SketchPointVisibility`]. +/// offset fit nodes (but an open offset's ends) are private. Batch callers use [`SketchPointVisibility`]. pub fn sketch_point_visible(sk: &Sketch, i: usize) -> bool { sk.points.get(i).is_some_and(|p| SketchPointVisibility::new(sk).takes(p)) } diff --git a/crates/sketch/src/freeform_offset.rs b/crates/sketch/src/freeform_offset.rs index 6529cd064..067686941 100644 --- a/crates/sketch/src/freeform_offset.rs +++ b/crates/sketch/src/freeform_offset.rs @@ -587,6 +587,35 @@ impl Sketch { *self = candidate; Ok(()) } + + /// Give every other curve that took a generated offset node (a line drawn from an open + /// offset's end) its own point there, coincident with the node: the output keeps sole + /// ownership of its nodes, and the curve follows the offset when its source moves. + /// Returns the ids of the constraints added. + pub fn detach_offset_points(&mut self) -> Result> { + if self.freeform_offsets.is_empty() { + return Ok(Vec::new()); + } + let outputs: std::collections::BTreeSet<&str> = self.freeform_offsets.iter().map(|o| o.output.as_str()).collect(); + let nodes: std::collections::BTreeSet = + self.curves.iter().filter(|c| outputs.contains(c.id.as_str())).flat_map(|c| c.kind.point_ids()).collect(); + let taken: Vec<(usize, usize)> = self + .curves + .iter() + .enumerate() + .filter(|(_, c)| !outputs.contains(c.id.as_str())) + .flat_map(|(ci, c)| c.kind.point_ids().into_iter().filter(|p| nodes.contains(p)).map(move |p| (ci, p))) + .collect(); + let mut added = Vec::new(); + for (ci, node) in taken { + let at = self.points.get(node).map(|p| p.pos).ok_or_else(|| bad("offset output point vanished"))?; + let own = self.add_point(at, None)?; + let curve = self.curves.get_mut(ci).ok_or_else(|| bad("offset neighbour curve vanished"))?; + curve.kind.map_points(&|p| if p == node { own } else { p }); + added.push(self.add_constraint(crate::ConstraintKind::Coincident { p: node, q: own }, None)?); + } + Ok(added) + } } #[cfg(test)] diff --git a/crates/ui-egui/tests/scenarios/sketch_offset_spline_ends.json b/crates/ui-egui/tests/scenarios/sketch_offset_spline_ends.json new file mode 100644 index 000000000..fb6b1e328 --- /dev/null +++ b/crates/ui-egui/tests/scenarios/sketch_offset_spline_ends.json @@ -0,0 +1,22 @@ +[ + {"note": "#2424: lines close the gap between an open spline and its associated offset. A click near the offset's end snaps to it; the line gets its own point there, coincident with the offset's end, and follows it when the source spline moves."}, + {"call": "engine.execute", "params": {"command": "sketch.create", "params": {"plane": "XY"}}}, + {"call": "engine.execute", "params": {"command": "sketch.spline.fit_point", "params": {"points": [[5,-5],[15,0],[25,-5],[35,0]], "ids": ["s1"]}}}, + {"call": "engine.execute", "params": {"command": "sketch.offset", "params": {"curves": ["s1"], "distance": "2 mm", "chain": true}}}, + {"call": "ui.view", "params": {"view": "top"}}, + {"call": "ui.view", "params": {"view": "fit"}}, + {"start": "sketch.line"}, + {"click": {"sketch": [5,-5]}}, + {"click": {"sketch": [3.85,-3.36]}}, + {"key": "Escape"}, + {"start": "sketch.line"}, + {"click": {"sketch": [33.85,1.64]}}, + {"click": {"sketch": [35,0]}}, + {"key": "Escape"}, + {"shot": "closed"}, + {"expect": {"errors": 0, "sketch_curves": {"own": 4}, "dof": 8}}, + {"call": "engine.execute", "params": {"command": "sketch.drag", "params": {"entity": "s1.start", "from": [5,-5], "to": [2,-2]}}}, + {"shot": "source-dragged"}, + {"expect": {"errors": 0, "dof": 8}}, + {"expect": {"query": {"command": "sketch.inspect", "path": ["curves", 2, "start_at", 0], "value": 2}}} +] diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md index 18f82b389..d01540dbb 100644 --- a/docs/book/src/guide/sketching.md +++ b/docs/book/src/guide/sketching.md @@ -129,6 +129,9 @@ error bound of 0.002 mm. Singular tangents, curvature cusps, possible self-inter excessive subdivisions are refused. Offset these curves individually: mixed chain junctions currently require separate geometry. `sketch.offset.break` releases an offset for independent editing, and undo restores its association. Older independently sampled offsets remain independent. +The fit points of such an offset stay hidden, except the two ends of an open one: lines and +arcs snap to them and stay coincident with them as the offset follows its source, so the gap +between a spline and its offset can be closed into a profile. Smooth open and newly created smooth closed offsets can be offset again, including bounded refinement after a source edit. New closed outputs use a periodic cubic fit with continuous tangent and curvature at the seam. Break Offset Association preserves that interpolation,