From 84ec512d7a68ff04f29feefa3117ee6457cc5281 Mon Sep 17 00:00:00 2001 From: Mauznemo <90456457+Mauznemo@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:36:29 +0000 Subject: [PATCH] fix: midpoint tool rejects two lines (#3836) --- crates/engine/src/cmd/sketch.rs | 64 +++++++++-- .../src/cmd/sketch_constraints_tests.rs | 103 ++++++++++++++++++ crates/ui-egui/src/context_menu.rs | 3 +- crates/ui-egui/src/delete.rs | 17 ++- crates/ui-egui/src/sketch_tools.rs | 89 +++++++++++++-- crates/ui-egui/src/tools.rs | 5 +- .../tests/point_constraint_preselection.rs | 102 ++++++++++++++++- docs/book/src/guide/sketching.md | 4 +- 8 files changed, 359 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 198106807..6dbbc2218 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -156,7 +156,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SKETCH", "CONSTRAINTS") .icon("c_midpoint") .enabled(in_sketch) - .params("point, line"), + .params("point, line | a, b in pick order: a point and a line (either way round), or two lines whose midpoints meet (the first stays, the second moves)"), CommandSpec::new("sketch.constraint.concentric", "Concentric", c_concentric) .at("SKETCH", "CONSTRAINTS") .icon("c_concentric") @@ -1637,6 +1637,15 @@ pub(super) fn residual_of(sk: &Sketch, id: &str) -> Option { sk.constraints.iter().position(|c| c.id == id).and_then(|ci| solidcraft_sketch::constraint_residual(sk, ci)) } +/// The point already tied to the middle of line `l`, including one created by drawing. +/// Coincident coordinates alone are not enough: the Midpoint relationship must exist. +fn existing_midpoint(sk: &Sketch, l: usize) -> Option { + sk.constraints.iter().find_map(|c| match c.kind { + ConstraintKind::Midpoint { p, l: line } if line == l && !c.driven => Some(p), + _ => None, + }) +} + /// Temporary pick intent. Saved sketches use ordinary points and constraints only. #[derive(Clone, Copy, PartialEq, Eq)] enum AlignmentTarget { @@ -1645,19 +1654,13 @@ enum AlignmentTarget { } impl AlignmentTarget { - fn materialize(self, sk: &mut Sketch) -> Result { + fn materialize(self, sk: &mut Sketch, cmd: &str) -> Result { match self { Self::Point(p) => Ok(p), Self::Midpoint(l) => { - // Reuse an existing associative midpoint, including one created by drawing. - // Coincident coordinates alone are insufficient: its relationship must exist. - if let Some(p) = sk.constraints.iter().find_map(|c| match c.kind { - ConstraintKind::Midpoint { p, l: line } if line == l && !c.driven => Some(p), - _ => None, - }) { + if let Some(p) = existing_midpoint(sk, l) { return Ok(p); } - let cmd = "sketch.constraint.horizontal_vertical"; let (a, b) = line_pts(sk, l).ok_or_else(|| bad(cmd, "a midpoint reference needs a line"))?; let p = sk.add_point((a + b) * 0.5, None)?; add_c(sk, ConstraintKind::Midpoint { p, l })?; @@ -1693,8 +1696,8 @@ fn c_horizontal_vertical(s: &mut Session, p: &Value) -> Result { if a == b { return Err(bad(cmd, "alignment needs two distinct point references")); } - let a = a.materialize(sk)?; - let b = b.materialize(sk)?; + let a = a.materialize(sk, cmd)?; + let b = b.materialize(sk, cmd)?; if a == b { return Err(bad(cmd, "alignment needs two distinct points")); } @@ -1826,9 +1829,46 @@ fn c_collinear(s: &mut Session, p: &Value) -> Result { fn c_midpoint(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.constraint.midpoint"; constrain(s, p, cmd, |sk| { - Ok(ConstraintKind::Midpoint { p: point_ref(sk, p.get("point"), cmd, "point")?, l: curve_ref(sk, p.get("line"), cmd, "line")? }) + if p.get("a").is_none() && p.get("b").is_none() { + return Ok(ConstraintKind::Midpoint { p: point_ref(sk, p.get("point"), cmd, "point")?, l: curve_ref(sk, p.get("line"), cmd, "line")? }); + } + // `a` and `b` in pick order: a point and a line either way round, or two lines. + let entity = |k: &str| -> Result { + let r = p.get(k).and_then(Value::as_str).ok_or_else(|| bad(cmd, format!("`{k}` must be a point or line id")))?; + match sk.resolve_point(r) { + Some(i) => Ok(Ent::Point(i)), + None => sk.curve_index(r).map(Ent::Curve).ok_or_else(|| bad(cmd, format!("unknown sketch point or curve `{r}`"))), + } + }; + let is_line = |sk: &Sketch, c: usize| matches!(sk.curves.get(c).map(|c| &c.kind), Some(CurveKind::Line { .. })); + match (entity("a")?, entity("b")?) { + (Ent::Point(q), Ent::Curve(l)) | (Ent::Curve(l), Ent::Point(q)) if is_line(sk, l) => Ok(ConstraintKind::Midpoint { p: q, l }), + // Two lines: their midpoints meet. One point sits at the middle of both, reusing + // a midpoint either line already has, so nothing new is saved in the design. + (Ent::Curve(a), Ent::Curve(b)) if is_line(sk, a) && is_line(sk, b) => { + if a == b { + return Err(bad(cmd, "pick two different lines")); + } + let (q, l) = match (existing_midpoint(sk, a), existing_midpoint(sk, b)) { + (Some(q), _) => (q, b), + (None, Some(q)) => (q, a), + (None, None) => (AlignmentTarget::Midpoint(a).materialize(sk, cmd)?, b), + }; + if existing_midpoint_of(sk, q, l) { + return Err(bad(cmd, "these lines already share their midpoint")); + } + Ok(ConstraintKind::Midpoint { p: q, l }) + } + _ => Err(bad(cmd, "MidPoint needs a point and a line, or two lines")), + } }) } + +/// Point `q` is already tied to the middle of line `l`. +fn existing_midpoint_of(sk: &Sketch, q: usize, l: usize) -> bool { + sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Midpoint { p, l: line } if p == q && line == l) && !c.driven) +} + /// The centre of a symmetry about a point (#1075): `point`, or `line` naming a point rather than /// a curve or a sketch axis (the origin picked as the third entity). fn symmetry_center(sk: &Sketch, p: &Value, cmd: &str) -> Result> { diff --git a/crates/engine/src/cmd/sketch_constraints_tests.rs b/crates/engine/src/cmd/sketch_constraints_tests.rs index 795ce0fad..1e4c08746 100644 --- a/crates/engine/src/cmd/sketch_constraints_tests.rs +++ b/crates/engine/src/cmd/sketch_constraints_tests.rs @@ -632,3 +632,106 @@ fn midpoint_alignment_remaps_after_unrelated_geometry_is_deleted() { run(&mut s, "sketch.delete", json!({"entities":[result["created"]["points"][0]]})); assert!(sketch(&s).constraints.is_empty()); } + +fn line_ends(sk: &solidcraft_sketch::Sketch, id: &str) -> (Vec2, Vec2) { + let solidcraft_sketch::CurveKind::Line { a, b } = sk.curves[sk.curve_index(id).unwrap()].kind else { panic!("expected line") }; + (sk.point(a).unwrap(), sk.point(b).unwrap()) +} + +#[test] +fn midpoint_of_two_lines_centres_the_second_on_the_first() { + use solidcraft_sketch::ConstraintKind; + for reverse in [false, true] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[0,0],[60,0]],"infer":false,"connect":false})); + run(&mut s, "sketch.line", json!({"points":[[5,-10],[25,-10]],"infer":false,"connect":false})); + let (first, second) = if reverse { ("l2", "l1") } else { ("l1", "l2") }; + let stays = line_ends(&sketch(&s), first); + let length = { + let (a, b) = line_ends(&sketch(&s), second); + a.dist(b) + }; + let before = s.doc.to_json(); + let undo = s.undo.len(); + let result = run(&mut s, "sketch.constraint.midpoint", json!({"a":first,"b":second})); + assert_eq!(result["created"]["points"].as_array().unwrap().len(), 1); + assert_eq!(result["created"]["constraints"].as_array().unwrap().len(), 2); + assert_eq!(s.undo.len(), undo + 1); + let sk = sketch(&s); + assert_eq!(line_ends(&sk, first), stays, "the first pick stays put"); + let (a, b) = line_ends(&sk, second); + assert!((a.dist(b) - length).abs() < 1e-6, "the second keeps its length"); + assert!(line_midpoint(&sk, first).dist(line_midpoint(&sk, second)) < 1e-6); + assert_eq!(sk.constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).count(), 2); + + // Saved as ordinary points and constraints: it reopens and keeps holding. + let after = s.doc.to_json(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc.to_json(), after); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&after).unwrap()); + reopened.active_sketch = s.active_sketch; + run(&mut reopened, "sketch.move_point", json!({"point":"l1.end","to":[80,15]})); + let sk = sketch(&reopened); + assert!(line_midpoint(&sk, "l1").dist(line_midpoint(&sk, "l2")) < 1e-6); + } +} + +#[test] +fn midpoint_takes_a_point_and_a_line_in_either_pick_order() { + for (a, b) in [("p", "l1"), ("l1", "p")] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[0,0],[40,0]],"infer":false,"connect":false})); + run(&mut s, "sketch.point", json!({"point":[7,9],"id":"p"})); + run(&mut s, "sketch.constraint.midpoint", json!({"a":a,"b":b})); + let sk = sketch(&s); + let p = sk.point(sk.resolve_point("p").unwrap()).unwrap(); + assert!(p.dist(line_midpoint(&sk, "l1")) < 1e-6, "{a} then {b}"); + } +} + +#[test] +fn midpoint_of_two_lines_reuses_an_existing_midpoint() { + use solidcraft_sketch::ConstraintKind; + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[0,0],[60,0]],"infer":false,"connect":false})); + run(&mut s, "sketch.line", json!({"points":[[5,-10],[25,-10]],"infer":false,"connect":false})); + // l3 starts at the midpoint of l2: that point is reused, not duplicated. + run(&mut s, "sketch.line", json!({"points":["mid:l2",[15,-30]],"infer":false,"connect":false})); + let count = sketch(&s).points.len(); + let result = run(&mut s, "sketch.constraint.midpoint", json!({"a":"l1","b":"l2"})); + assert!(result["created"]["points"].as_array().unwrap().is_empty()); + let sk = sketch(&s); + assert_eq!(sk.points.len(), count); + assert_eq!(sk.constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).count(), 2); + assert!(line_midpoint(&sk, "l1").dist(line_midpoint(&sk, "l2")) < 1e-6); + // Applying it again finds nothing to add. + let before = s.doc.to_json(); + assert!(s.execute("sketch.constraint.midpoint", &json!({"a":"l2","b":"l1"})).is_err()); + assert_eq!(s.doc.to_json(), before); +} + +#[test] +fn midpoint_rejects_wrong_picks_without_changing_the_sketch() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[0,0],[60,0]],"infer":false,"connect":false})); + run(&mut s, "sketch.circle.center", json!({"center":[40,50],"radius":3})); + run(&mut s, "sketch.point", json!({"point":[7,9],"id":"p"})); + for params in [ + json!({"a":"l1","b":"l1"}), + json!({"a":"l1","b":"c1"}), + json!({"a":"c1","b":"l1"}), + json!({"a":"p","b":"origin"}), + json!({"a":"p","b":"c1"}), + json!({"a":"l1","b":"missing"}), + json!({"a":"l1"}), + json!({"a":12,"b":"l1"}), + ] { + let before = s.doc.to_json(); + let undo = s.undo.len(); + assert!(s.execute("sketch.constraint.midpoint", ¶ms).is_err(), "{params}"); + assert_eq!(s.doc.to_json(), before, "{params}"); + assert_eq!(s.undo.len(), undo, "{params}"); + } +} diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 67fb16df3..803a9daae 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -926,7 +926,8 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { c.push(cmd(app, "sketch.constraint.parallel", "Parallel").with(ab.clone())); c.push(cmd(app, "sketch.constraint.perpendicular", "Perpendicular").with(ab.clone())); c.push(cmd(app, "sketch.constraint.collinear", "Collinear").with(ab.clone())); - c.push(cmd(app, "sketch.constraint.equal", "Equal").with(ab)); + c.push(cmd(app, "sketch.constraint.equal", "Equal").with(ab.clone())); + c.push(cmd(app, "sketch.constraint.midpoint", "MidPoint").with(ab)); } if r == 2 && n == 2 { let ab = json!({ "a": rounds[0], "b": rounds[1] }); diff --git a/crates/ui-egui/src/delete.rs b/crates/ui-egui/src/delete.rs index 31e1ce404..0ad438a6f 100644 --- a/crates/ui-egui/src/delete.rs +++ b/crates/ui-egui/src/delete.rs @@ -20,8 +20,21 @@ pub struct Pending { /// What Delete acts on now: the selection (bodies not locked), plus the components picked in /// the browser (their occurrences). pub fn selection_params(app: &SolveApp) -> Value { - let items: Vec<&solidcraft_engine::Sel> = - app.session.selection.iter().filter(|s| !matches!(s, solidcraft_engine::Sel::Body { name } if app.ui.locked_bodies.contains(name))).collect(); + use solidcraft_engine::Sel; + let mut items: Vec = Vec::new(); + for s in app.session.selection.iter().filter(|s| !matches!(s, Sel::Body { name } if app.ui.locked_bodies.contains(name))) { + // A MidPoint glyph shared by lines whose midpoints meet removes every constraint it + // shows, and the point they shared when nothing else holds it. + let group = match s { + Sel::SketchConstraint { id } => crate::sketch_tools::active_glyph_deletion(app, id), + _ => vec![s.clone()], + }; + for g in group { + if !items.contains(&g) { + items.push(g); + } + } + } let occurrences: Vec = app.tree.picked_components.iter().filter_map(|c| app.session.doc.occurrence_of(*c).map(|o| o.id)).collect(); json!({ "items": items, "occurrences": occurrences, "canvases": app.tree.picked_canvases, "joints": app.tree.picked_joints }) } diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index a8e90d846..c3f162241 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -467,6 +467,50 @@ pub fn refine_snap( }) } +/// The constraints one glyph stands for. A point that is the midpoint of several lines (their +/// midpoints meet) shows a single MidPoint glyph, the first constraint's, for all of them; +/// any other constraint stands for itself. +pub fn glyph_group(sk: &solidcraft_engine::sketch::Sketch, id: &str) -> Vec { + use solidcraft_engine::sketch::ConstraintKind::Midpoint; + match sk.constraints.iter().find(|c| c.id == id).map(|c| (c.kind.clone(), c.driven)) { + Some((Midpoint { p, .. }, false)) => { + sk.constraints.iter().filter(|c| !c.driven && matches!(c.kind, Midpoint { p: q, .. } if q == p)).map(|c| c.id.clone()).collect() + } + _ => vec![id.to_string()], + } +} + +/// What deleting glyph `id` removes: the constraints it stands for, and, for one MidPoint glyph +/// shared by several lines, their common point once nothing else holds it (it only tied the +/// midpoints together, so it would be left floating). +pub fn glyph_deletion(sk: &solidcraft_engine::sketch::Sketch, id: &str) -> Vec { + use solidcraft_engine::{Sel, sketch::ConstraintKind::Midpoint}; + let group = glyph_group(sk, id); + let shared = match sk.constraints.iter().find(|c| c.id == id).map(|c| &c.kind) { + Some(Midpoint { p, .. }) if group.len() > 1 => Some(*p), + _ => None, + }; + let orphan = shared.filter(|&p| { + !sk.curves.iter().any(|c| c.kind.uses(p)) + && !sk.constraints.iter().any(|c| !group.contains(&c.id) && c.kind.indices().0.contains(&p)) + && sk.points.get(p).is_some_and(|q| !q.fixed && q.link.is_none() && q.exprs.is_none()) + }); + let mut out: Vec = group.into_iter().map(|id| Sel::SketchConstraint { id }).collect(); + if let Some(q) = orphan.and_then(|p| sk.points.get(p)) { + out.push(Sel::SketchPoint { id: q.id.clone() }); + } + out +} + +/// [`glyph_deletion`] in the active sketch. +pub fn active_glyph_deletion(app: &SolveApp, id: &str) -> Vec { + let st = app.session.world_state(); + match active_sketch(app).and_then(|s| st.sketch(s)) { + Some(ss) => glyph_deletion(&ss.sketch, id), + None => vec![solidcraft_engine::Sel::SketchConstraint { id: id.to_string() }], + } +} + /// The constraint glyph under a screen position (its constraint id). pub fn glyph_at(pos: Pos2) -> Option { GLYPHS.with(|g| g.borrow().iter().find(|(_, c)| c.distance(pos) <= GLYPH * 0.6).map(|(id, _)| id.clone())) @@ -494,7 +538,14 @@ pub fn click_glyph(app: &mut SolveApp, _proj: &Proj, pos: Pos2) -> bool { /// Delete the selected constraint glyph (true when one was selected). pub fn delete_glyph(app: &mut SolveApp) -> bool { let Some(id) = PICKED.with(|p| p.borrow_mut().take()) else { return false }; - let _ = app.run("sketch.delete", json!({"entities": [id]})); + let entities: Vec = active_glyph_deletion(app, &id) + .into_iter() + .filter_map(|s| match s { + solidcraft_engine::Sel::SketchConstraint { id } | solidcraft_engine::Sel::SketchPoint { id } => Some(id), + _ => None, + }) + .collect(); + let _ = app.run("sketch.delete", json!({ "entities": entities })); true } @@ -1170,10 +1221,20 @@ fn glyphs(app: &SolveApp, painter: &egui::Painter, proj: &Proj, hover: Option = Vec::new(); + // The point of each MidPoint glyph drawn so far: lines whose midpoints meet share one glyph. + let mut midpoints: Vec = Vec::new(); for c in &ss.sketch.constraints { if c.kind.is_dimension() { continue; } + if let solidcraft_engine::sketch::ConstraintKind::Midpoint { p, .. } = c.kind + && !c.driven + { + if midpoints.contains(&p) { + continue; + } + midpoints.push(p); + } if matches!( c.kind, solidcraft_engine::sketch::ConstraintKind::PatternPoint { .. } | solidcraft_engine::sketch::ConstraintKind::PatternRadius { .. } @@ -1213,10 +1274,16 @@ fn glyphs(app: &SolveApp, painter: &egui::Painter, proj: &Proj, hover: Option = Vec::new(); for (id, sp, base) in &placed { let Some(c) = ss.sketch.constraints.iter().find(|c| &c.id == id) else { continue }; - let failing = ss.report.failing.contains(id); + let group = glyph_group(&ss.sketch, id); + let failing = group.iter().any(|g| ss.report.failing.contains(g)); // Redundant (already implied by the others, but holding): dimmed, not an error. - let redundant = !failing && ss.report.redundant.contains(id); + let redundant = !failing && group.iter().all(|g| ss.report.redundant.contains(g)); let selected = picked.as_deref() == Some(id.as_str()) - || app.session.selection.iter().any(|s| matches!(s, solidcraft_engine::Sel::SketchConstraint { id: x } if x == id)); + || app.session.selection.iter().any(|s| matches!(s, solidcraft_engine::Sel::SketchConstraint { id: x } if group.contains(x))); let lit = selected || hovered.as_deref() == Some(id.as_str()); let col = if failing { tk.error @@ -1276,10 +1344,11 @@ fn glyphs(app: &SolveApp, painter: &egui::Painter, proj: &Proj, hover: Option String { "sketch.dimension" => "Dimension: pick one or two entities and type the value (or click to place it first); Enter applies".into(), "sketch.constraint.horizontal_vertical" => "Horizontal/Vertical: pick a line or two points; hold Shift to pick a line midpoint".into(), "sketch.slot.center_to_center" | "sketch.slot.overall" => "Slot: click both ends, then the width".into(), + "sketch.constraint.midpoint" => "MidPoint: pick a point and a line, or two lines to centre the second on the first".into(), _ if id.starts_with("sketch.constraint.") => "Constraint: pick the sketch entities".into(), _ => crate::sketch_tools::hint(id).unwrap_or_else(|| "Click in the sketch".into()), } @@ -494,6 +495,7 @@ pub(crate) fn constraint_preselection(command: &str, selection: &[solidcraft_eng "sketch.constraint.midpoint", [SketchPoint { id: point }, SketchCurve { id: line }] | [SketchCurve { id: line }, SketchPoint { id: point }], ) => Some(json!({"point":point,"line":line})), + ("sketch.constraint.midpoint", [SketchCurve { id: a }, SketchCurve { id: b }]) if a != b => Some(json!({"a":a,"b":b})), ("sketch.constraint.symmetry", [a, b, c]) => { let mut points = Vec::new(); let mut lines = Vec::new(); @@ -567,7 +569,8 @@ fn run_pick(app: &mut SolveApp, t: &Tool) { let params = match t.cmd { "sketch.constraint.fix" => json!({"entity": k[0]}), "sketch.constraint.coincident" => json!({"a": k[0], "b": k[1]}), - "sketch.constraint.midpoint" => json!({"point": k[0], "line": k[1]}), + // In pick order: a point and a line either way round, or two lines to centre. + "sketch.constraint.midpoint" => json!({"a": k[0], "b": k[1]}), "sketch.constraint.symmetry" => json!({"a": k[0], "b": k[1], "line": k[2]}), _ => json!({"a": k[0], "b": k[1]}), }; diff --git a/crates/ui-egui/tests/point_constraint_preselection.rs b/crates/ui-egui/tests/point_constraint_preselection.rs index 2d431cd2d..7c0765347 100644 --- a/crates/ui-egui/tests/point_constraint_preselection.rs +++ b/crates/ui-egui/tests/point_constraint_preselection.rs @@ -1,5 +1,5 @@ use serde_json::json; -use solidcraft_engine::{Sel, sketch::ConstraintKind}; +use solidcraft_engine::{Sel, geom::Vec2, sketch::ConstraintKind}; use solidcraft_ui_egui::scenario::Harness; fn setup() -> Harness { @@ -86,3 +86,103 @@ fn rejected_and_ambiguous_preselection_preserve_document_and_selection() { assert_eq!(h.app.session.doc.to_json(), before); } } + +// MidPoint centres one line on another when the tool picks two lines. +fn two_lines() -> Harness { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[0,0],[60,0]],"infer":false,"connect":false})).unwrap(); + h.app.run("sketch.line", json!({"points":[[5,-10],[25,-10]],"infer":false,"connect":false})).unwrap(); + h.call("ui.view", json!({"view":"top"})); + h +} + +fn line_ends(h: &Harness, id: &str) -> (Vec2, Vec2) { + let state = h.app.session.world_state(); + let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; + let p = |end: &str| sk.point(sk.resolve_point(&format!("{id}.{end}")).unwrap()).unwrap(); + (p("start"), p("end")) +} + +fn assert_centred(h: &Harness, undo: usize) { + assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", h.app.status); + assert_eq!(h.app.session.undo.len(), undo + 1); + let (a, b) = line_ends(h, "l1"); + assert_eq!((a, b), (Vec2::new(0.0, 0.0), Vec2::new(60.0, 0.0)), "the first line stays"); + let (c, d) = line_ends(h, "l2"); + assert!(((a + b) * 0.5).dist((c + d) * 0.5) < 1e-6); + assert!((c.dist(d) - 20.0).abs() < 1e-6); +} + +#[test] +fn midpoint_tool_clicking_two_lines_centres_them() { + let mut h = two_lines(); + let undo = h.app.session.undo.len(); + h.step(&json!({"start":"sketch.constraint.midpoint"})).unwrap(); + h.step(&json!({"click":{"sketch":[45,0]}})).unwrap(); + h.step(&json!({"click":{"sketch":[10,-10]}})).unwrap(); + assert_centred(&h, undo); +} + +#[test] +fn midpoint_tool_takes_two_preselected_lines() { + let mut h = two_lines(); + h.step(&json!({"click":{"sketch":[45,0]}})).unwrap(); + h.step(&json!({"click":{"sketch":[10,-10]},"shift":true})).unwrap(); + assert_eq!(h.app.session.selection.len(), 2); + let undo = h.app.session.undo.len(); + h.step(&json!({"start":"sketch.constraint.midpoint"})).unwrap(); + assert!(h.app.tool.is_none()); + assert_centred(&h, undo); +} + +fn midpoint_ids(h: &Harness) -> Vec { + let state = h.app.session.world_state(); + let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; + sk.constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).map(|c| c.id.clone()).collect() +} + +fn point_count(h: &Harness) -> usize { + let state = h.app.session.world_state(); + state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.points.len() +} + +/// Centre l2 on l1 with the MidPoint tool, then click its glyph and press Delete. +fn centre_then_delete_glyph(h: &mut Harness) { + h.step(&json!({"start":"sketch.constraint.midpoint"})).unwrap(); + h.step(&json!({"click":{"sketch":[45,0]}})).unwrap(); + h.step(&json!({"click":{"sketch":[10,-10]}})).unwrap(); + h.step(&json!({"key":"Escape"})).unwrap(); + let ids = midpoint_ids(h); + assert!(ids.len() >= 2, "one point at the middle of both lines"); + let glyphs: Vec<_> = solidcraft_ui_egui::sketch_tools::glyph_positions().into_iter().filter(|(id, _)| ids.contains(id)).collect(); + assert_eq!(glyphs.len(), 1, "one MidPoint glyph for both lines: {glyphs:?}"); + let at = glyphs[0].1; + h.step(&json!({"click":[at.x, at.y]})).unwrap(); + h.step(&json!({"key":"Delete"})).unwrap(); + for _ in 0..20 { + if midpoint_ids(h).is_empty() { + break; + } + h.frames(1); + } + assert!(midpoint_ids(h).is_empty(), "deleting the glyph removes both constraints: {:?}", midpoint_ids(h)); +} + +#[test] +fn centred_lines_show_one_midpoint_glyph_that_deletes_both_constraints_and_their_point() { + let mut h = two_lines(); + let points = point_count(&h); + centre_then_delete_glyph(&mut h); + assert_eq!(point_count(&h), points, "the point that only tied the midpoints goes too"); +} + +#[test] +fn deleting_the_shared_midpoint_glyph_keeps_a_point_another_line_uses() { + let mut h = two_lines(); + // l3 starts at the midpoint of l2: centring reuses that point, and deleting keeps it. + h.app.run("sketch.line", json!({"points":["mid:l2",[15,-30]],"infer":false,"connect":false})).unwrap(); + let points = point_count(&h); + centre_then_delete_glyph(&mut h); + assert_eq!(point_count(&h), points); +} diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md index 08752de01..090de552c 100644 --- a/docs/book/src/guide/sketching.md +++ b/docs/book/src/guide/sketching.md @@ -240,7 +240,9 @@ You can also start the constraint first and then pick its curves. An incomplete selection leaves the tool ready for ordinary picking. Coincident accepts an exact selection of two points or a point and a curve. Midpoint -accepts one point and one line, in either selection order. Symmetry accepts two distinct +accepts one point and one line, in either selection order, or two lines: the second line +moves (keeping its length) until its midpoint sits on the first line's midpoint, +and stays centred there as either line changes. Symmetry accepts two distinct points and one symmetry line, regardless of where the line occurs in the selection. Successful constraints clear the selection; rejected constraints preserve it.