SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Sketch: persist Shift-picked midpoints with ordinary constraints (#2087) (#2378)
fkirillfb87cde6a1b9
diff --git a/ROADMAP.md b/ROADMAP.mdindex c7b5de2810..c269a33ec6 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -50,7 +50,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings.| # | Milestone | Status | Hours left ||---|---|---|---|| M0 | Vertical slice | done | — |-| M1 | Sketch depth: command coverage implemented — projection/intersect/include as linked geometry (auto-project on faces, lost-reference warnings, break link), full SKETCH create/modify set (slots, polygons, tangent arcs/circles, ellipse, fit/control splines, conic, text, trim/extend/break, fillet/chamfer, offset, mirror, patterns, move/scale, blend curve, centerline), constraints incl. curvature and polygon with over-constraint refusal, driven/arc-length/linear-diameter dimensions, AutoConstrain, DXF/SVG insert, 3D sketch curves (Project To Surface, Intersection Curve, Isoparametric Curve, Spun Profile), exact free-form profiles (B-spline/NURBS edges, any spline degree, curves cut by crossings), sweeps and pipes along 3D sketch curves, canvases and decals, curvature combs. Exact free-form Extend and certified associative offsets now preserve geometry and IDs through edits, deletion and reopen. Occurrence-frame 3D wires now store explicit coordinate spaces and retain points and analytic fits through moves, refresh, undo and reopen. Constructive sketch solving (Owen 1991, Fudos & Hoffmann 1997) ahead of the numerical solver: points and rigid clusters are placed on the branch the sketch had, so dimension edits and drags keep their solution; edits that would turn a sketch over are refused; drags re-solve only the sketch per frame. Remaining workflow repairs: mixed offset junctions, legacy natural-spline seams, and damaged legacy wire links lacking frame provenance | in progress | 4 |+| M1 | Sketch depth: command coverage implemented — projection/intersect/include as linked geometry (auto-project on faces, lost-reference warnings, break link), full SKETCH create/modify set (slots, polygons, tangent arcs/circles, ellipse, fit/control splines, conic, text, trim/extend/break, fillet/chamfer, offset, mirror, patterns, move/scale, blend curve, centerline), constraints incl. curvature and polygon with over-constraint refusal, Shift-picked line midpoints in Horizontal/Vertical using persisted points and ordinary constraints (#2087), driven/arc-length/linear-diameter dimensions, AutoConstrain, DXF/SVG insert, 3D sketch curves (Project To Surface, Intersection Curve, Isoparametric Curve, Spun Profile), exact free-form profiles (B-spline/NURBS edges, any spline degree, curves cut by crossings), sweeps and pipes along 3D sketch curves, canvases and decals, curvature combs. Exact free-form Extend and certified associative offsets now preserve geometry and IDs through edits, deletion and reopen. Occurrence-frame 3D wires now store explicit coordinate spaces and retain points and analytic fits through moves, refresh, undo and reopen. Constructive sketch solving (Owen 1991, Fudos & Hoffmann 1997) ahead of the numerical solver: points and rigid clusters are placed on the branch the sketch had, so dimension edits and drags keep their solution; edits that would turn a sketch over are refused; drags re-solve only the sketch per frame. Remaining workflow repairs: mixed offset junctions, legacy natural-spline seams, and damaged legacy wire links lacking frame provenance | in progress | 4 || M2 | Robust modelling: coplanar booleans in the kernel, holes (placed on faces and on sketch points), threads (cosmetic, then modelled), patterns, mirror, shell, draft, split, construction geometry | in progress | 16 || M3 | General fillets and chamfers (curved edges, chains, vertex blends); saddle rolling-ball surfaces now use continuous seam sections and arc-length fitting with shared contact boundaries and bounded accuracy checks; tiny rim edges remain selected instead of nearby wall seams when filleting (#2498) | in progress | 30 || M4 | Files: STEP import (done — [docs/step-import.md](docs/step-import.md)), FreeCAD/Rhino solids through cadmpeg (done, desktop and CLI), 3MF export and 3MF/STL import as mesh bodies (done), 3MF with B-rep face tags ([docs/formats/3mf-face-tags.md](docs/formats/3mf-face-tags.md), done), constant-section parametric mesh reconstruction, DXF sketches, OBJ import | in progress | 6 |diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rsindex 77c1b4f7fd..63f827732e 100644--- a/crates/engine/src/cmd/sketch.rs+++ b/crates/engine/src/cmd/sketch.rs@@ -117,7 +117,7 @@ pub static COMMANDS: &[CommandSpec] = &[.at("SKETCH", "CONSTRAINTS").icon("c_hv").enabled(in_sketch)- .params("line: id | points: [a, b]; mode?: horizontal|vertical"),+ .params("line: id | points: [a, b] (point ids or {midpoint: line_id}; accepted midpoints reuse or create a point with a Midpoint constraint); mode?: horizontal|vertical"),CommandSpec::new("sketch.constraint.coincident", "Coincident", c_coincident).at("SKETCH", "CONSTRAINTS").icon("c_coincident")@@ -1625,14 +1625,68 @@ pub(super) fn residual_of(sk: &Sketch, id: &str) -> Option<f64> {sk.constraints.iter().position(|c| c.id == id).and_then(|ci| solidcraft_sketch::constraint_residual(sk, ci))}+/// Temporary pick intent. Saved sketches use ordinary points and constraints only.+#[derive(Clone, Copy, PartialEq, Eq)]+enum AlignmentTarget {+ Point(usize),+ Midpoint(usize),+}++impl AlignmentTarget {+ fn materialize(self, sk: &mut Sketch) -> Result<usize> {+ 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,+ }) {+ 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 })?;+ Ok(p)+ }+ }+ }+}+fn c_horizontal_vertical(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "sketch.constraint.horizontal_vertical";let mode = str_(p, "mode").map(str::to_ascii_lowercase);constrain(s, p, cmd, |sk| {if let Some(pts) = p.get("points").and_then(Value::as_array) {- let a = point_ref(sk, pts.first(), cmd, "points[0]")?;- let b = point_ref(sk, pts.get(1), cmd, "points[1]")?;- let d = sk.point(b).unwrap_or_default() - sk.point(a).unwrap_or_default();+ if pts.len() != 2 {+ return Err(bad(cmd, "`points` needs exactly two point references"));+ }+ let target = |v: &Value| -> Result<AlignmentTarget> {+ if let Some(line) = v.get("midpoint") {+ let l = curve_ref(sk, Some(line), cmd, "midpoint")?;+ if !matches!(sk.curves.get(l).map(|c| &c.kind), Some(CurveKind::Line { .. })) {+ return Err(bad(cmd, "a midpoint reference needs a line"));+ }+ Ok(AlignmentTarget::Midpoint(l))+ } else {+ Ok(AlignmentTarget::Point(point_ref(sk, Some(v), cmd, "points")?))+ }+ };+ // Validate both intents before materializing either. Hover and a pending first+ // pick never change the sketch; this command accepts both in one undo step.+ let a = target(pts.first().ok_or_else(|| bad(cmd, "missing first point"))?)?;+ let b = target(pts.get(1).ok_or_else(|| bad(cmd, "missing second point"))?)?;+ if a == b {+ return Err(bad(cmd, "alignment needs two distinct point references"));+ }+ let a = a.materialize(sk)?;+ let b = b.materialize(sk)?;+ if a == b {+ return Err(bad(cmd, "alignment needs two distinct points"));+ }+ let d = sk.point(b).ok_or_else(|| bad(cmd, "invalid second point"))? - sk.point(a).ok_or_else(|| bad(cmd, "invalid first point"))?;let horiz = match mode.as_deref() {Some("horizontal") => true,Some("vertical") => false,diff --git a/crates/engine/src/cmd/sketch_constraints_tests.rs b/crates/engine/src/cmd/sketch_constraints_tests.rsindex de5e2e114b..f835ded7e2 100644--- a/crates/engine/src/cmd/sketch_constraints_tests.rs+++ b/crates/engine/src/cmd/sketch_constraints_tests.rs@@ -373,3 +373,202 @@ fn symmetry_moves_a_free_line_between_two_fixed_lines() {assert!((at(end).x - x).abs() < 1e-9, "{end} moved to {:?}", at(end));}}++#[test]+fn midpoint_alignment_persists_undoes_and_survives_endpoint_edits() {+ use solidcraft_sketch::ConstraintKind;+ for mode in ["horizontal", "vertical"] {+ for reverse in [false, true] {+ let mut s = new_sketch();+ run(&mut s, "sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false}));+ run(&mut s, "sketch.point", json!({"point":[24,40],"id":"target"}));+ let before = s.doc.to_json();+ let undo = s.undo.len();+ let refs = if reverse { json!(["target",{"midpoint":"l1"}]) } else { json!([{"midpoint":"l1"},"target"]) };+ let result = run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points":refs,"mode":mode}));+ assert_eq!(result["created"]["points"].as_array().unwrap().len(), 1);+ assert_eq!(result["created"]["constraints"].as_array().unwrap().len(), 2);+ assert_eq!(result["sketch"]["dof"], 5, "H/V removes one degree of freedom; the midpoint adds none");+ assert!(result["created"]["curves"].as_array().unwrap().is_empty());+ assert_eq!(s.undo.len(), undo + 1);+ 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;+ for end in [[50., -15.], [-20., 65.]] {+ run(&mut reopened, "sketch.move_point", json!({"point":"l1.end","to":end}));+ let sk = sketch(&reopened);+ let point = sk.point(sk.resolve_point("target").unwrap()).unwrap();+ let mid = line_midpoint(&sk, "l1");+ assert!((if mode == "horizontal" { point.y - mid.y } else { point.x - mid.x }).abs() < 1e-6);+ assert_eq!(sk.points.len(), 5);+ }+ let sk = sketch(&reopened);+ assert!(sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })));+ assert!(sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::HorizontalPoints { .. } | ConstraintKind::VerticalPoints { .. })));+ run(&mut reopened, "sketch.delete", json!({"entities":["l1"]}));+ assert!(!sketch(&reopened).constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })));+ assert!(sketch(&reopened).constraints.iter().any(|c| c.id == result["constraint"].as_str().unwrap()));+ }+ }+}++#[test]+fn midpoint_alignment_rejects_invalid_or_conflicting_references_atomically() {+ let mut s = new_sketch();+ run(&mut s, "sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false}));+ run(&mut s, "sketch.circle.center", json!({"center":[40,50],"radius":3}));+ run(&mut s, "sketch.constraint.fix", json!({"entities":["l1","c1"]}));+ for points in [+ json!([{"midpoint":"l1"},"c1.center"]),+ json!([{"midpoint":"c1"},"origin"]),+ json!([{"midpoint":"missing"},"origin"]),+ json!([{"midpoint":"l1"},{"midpoint":"l1"}]),+ json!([{"midpoint":12},"origin"]),+ json!([{"midpoint":"l1"}]),+ json!([{"midpoint":"l1"},"origin","c1.center"]),+ ] {+ let before = s.doc.to_json();+ let undo = s.undo.len();+ assert!(s.execute("sketch.constraint.horizontal_vertical", &json!({"points":points,"mode":"vertical"})).is_err(), "{points}");+ assert_eq!(s.doc.to_json(), before);+ assert_eq!(s.undo.len(), undo);+ }+}++fn line_midpoint(sk: &solidcraft_sketch::Sketch, id: &str) -> Vec2 {+ // Read the curve's current endpoints: after a corner cut an original endpoint+ // id can still name the retained construction side's corner.+ 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()) * 0.5+}++#[test]+fn midpoint_alignment_reuses_associative_points_and_rejects_self_alignment() {+ use solidcraft_sketch::ConstraintKind;+ let mut s = new_sketch();+ run(&mut s, "sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false}));+ // A drawing-time midpoint is an ordinary, reusable point too.+ run(&mut s, "sketch.line", json!({"points":["mid:l1",[20,40]],"infer":false,"connect":false}));+ run(&mut s, "sketch.point", json!({"point":[24,50],"id":"target"}));+ let count = sketch(&s).points.len();+ let result = run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points":[{"midpoint":"l1"},"target"],"mode":"vertical"}));+ assert!(result["created"]["points"].as_array().unwrap().is_empty());+ assert_eq!(result["created"]["constraints"].as_array().unwrap().len(), 1);+ let sk = sketch(&s);+ assert_eq!(sk.points.len(), count);+ assert_eq!(sk.constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).count(), 1);+ for refs in [json!([{"midpoint":"l1"},"l2.start"]), json!(["l2.start",{"midpoint":"l1"}])] {+ let before = s.doc.to_json();+ let undo = s.undo.len();+ assert!(s.execute("sketch.constraint.horizontal_vertical", &json!({"points":refs})).is_err());+ assert_eq!(s.doc.to_json(), before);+ assert_eq!(s.undo.len(), undo);+ }+}++#[test]+fn midpoint_alignment_constraints_delete_independently_and_leave_the_point() {+ use solidcraft_sketch::ConstraintKind;+ for delete_midpoint in [false, true] {+ let mut s = new_sketch();+ run(&mut s, "sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false}));+ run(&mut s, "sketch.point", json!({"point":[24,40],"id":"target"}));+ run(&mut s, "sketch.constraint.fix", json!({"entity":"l1"}));+ let result = run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points":[{"midpoint":"l1"},"target"],"mode":"vertical"}));+ let sk = sketch(&s);+ let helper = result["created"]["points"][0].as_str().unwrap().to_string();+ let mid = sk.constraints.iter().find(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).unwrap().id.clone();+ let hv = result["constraint"].as_str().unwrap().to_string();+ let deleted = if delete_midpoint { &mid } else { &hv };+ let retained = if delete_midpoint { &hv } else { &mid };+ let before = s.doc.to_json();+ run(&mut s, "sketch.delete", json!({"entities":[deleted]}));+ let sk = sketch(&s);+ assert!(sk.resolve_point(&helper).is_some());+ assert!(sk.constraints.iter().any(|c| &c.id == retained));+ assert!(!sk.constraints.iter().any(|c| &c.id == deleted));+ assert_eq!(sk.points.len(), 5);+ 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;+ assert_eq!(sketch(&reopened).points.len(), 5);+ if delete_midpoint {+ // Once its defining relation is deleted it is an ordinary free point.+ run(&mut reopened, "sketch.move_point", json!({"point":helper,"to":[55,65]}));+ let sk = sketch(&reopened);+ let helper = sk.point(sk.resolve_point(&helper).unwrap()).unwrap();+ let target = sk.point(sk.resolve_point("target").unwrap()).unwrap();+ assert!((helper.x - target.x).abs() < 1e-6);+ assert!(helper.dist(line_midpoint(&sk, "l1")) > 1.0);+ } else {+ run(&mut reopened, "sketch.move_point", json!({"point":"target","to":[55,65]}));+ let sk = sketch(&reopened);+ let helper = sk.point(sk.resolve_point(&helper).unwrap()).unwrap();+ assert!(helper.dist(line_midpoint(&sk, "l1")) < 1e-6);+ assert!((sk.point(sk.resolve_point("target").unwrap()).unwrap().x - helper.x).abs() > 1.0);+ }+ }+}++#[test]+fn midpoint_alignment_keeps_original_side_after_fillet_and_chamfer() {+ use solidcraft_sketch::ConstraintKind;+ for (command, params) in+ [("sketch.fillet", json!({"point":"l1.end","radius":3})), ("sketch.chamfer.equal_distance", json!({"point":"l1.end","distance":3}))]+ {+ let mut s = new_sketch();+ run(&mut s, "sketch.line", json!({"points":[[10,10],[50,10],[50,40]],"infer":true}));+ run(&mut s, "sketch.point", json!({"point":[32,60],"id":"target"}));+ let aligned = run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points":[{"midpoint":"l1"},"target"],"mode":"vertical"}));+ let helper = aligned["created"]["points"][0].as_str().unwrap();+ let before = sketch(&s);+ let original_mid = before.point(before.resolve_point(helper).unwrap()).unwrap();+ run(&mut s, command, params);+ let after = s.doc.to_json();+ let mut reopened = Session::new(solidcraft_doc::Document::from_json(&after).unwrap());+ reopened.active_sketch = s.active_sketch;+ let sk = sketch(&reopened);+ let (point, line) = sk+ .constraints+ .iter()+ .find_map(|c| match c.kind {+ ConstraintKind::Midpoint { p, l } => Some((p, l)),+ _ => None,+ })+ .unwrap();+ assert!(sk.curves[line].construction);+ let mid = sk.point(point).unwrap();+ assert!(mid.dist(original_mid) < 1e-5, "{command}: {mid:?} vs {original_mid:?}");+ assert!((sk.point(sk.resolve_point("target").unwrap()).unwrap().x - mid.x).abs() < 1e-6);+ assert!(mid.dist(line_midpoint(&sk, "l1")) > 0.5, "midpoint belongs to original full side");+ assert!(mid.dist(line_midpoint(&sk, &sk.curves[line].id)) < 1e-6);+ }+}++#[test]+fn midpoint_alignment_remaps_after_unrelated_geometry_is_deleted() {+ use solidcraft_sketch::ConstraintKind;+ let mut s = new_sketch();+ run(&mut s, "sketch.line", json!({"points":[[-30,-20],[-10,-10]],"infer":false,"connect":false}));+ run(&mut s, "sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false}));+ run(&mut s, "sketch.point", json!({"point":[24,40],"id":"target"}));+ let result = run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points":[{"midpoint":"l2"},"target"],"mode":"vertical"}));+ run(&mut s, "sketch.delete", json!({"entities":["l1"]}));+ run(&mut s, "sketch.move_point", json!({"point":"l2.end","to":[60,-10]}));+ let sk = sketch(&s);+ let helper = sk.point(sk.resolve_point(result["created"]["points"][0].as_str().unwrap()).unwrap()).unwrap();+ assert!(helper.dist(line_midpoint(&sk, "l2")) < 1e-6);+ assert!((sk.point(sk.resolve_point("target").unwrap()).unwrap().x - helper.x).abs() < 1e-6);+ assert!(sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Midpoint { l: 0, .. })));+ // Deleting the helper itself removes its H/V and Midpoint relationships.+ run(&mut s, "sketch.delete", json!({"entities":[result["created"]["points"][0]]}));+ assert!(sketch(&s).constraints.is_empty());+}diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rsindex 2e702599b0..8ae0f8674d 100644--- a/crates/ui-egui/src/sketch_tools.rs+++ b/crates/ui-egui/src/sketch_tools.rs@@ -578,6 +578,7 @@ pub fn tool_for(id: &str) -> Option<Tool> {pts: Vec::new(),hover: None,picks: Vec::new(),+ point_picks: Vec::new(),dims: Vec::new(),dim_history: Vec::new(),dims_stage: usize::MAX,diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rsindex c434a46df2..31e413f26c 100644--- a/crates/ui-egui/src/tools.rs+++ b/crates/ui-egui/src/tools.rs@@ -78,6 +78,8 @@ pub struct Tool {pub hover: Option<(Vec2, Option<String>)>,/// Picked entity ids.pub picks: Vec<String>,+ /// Horizontal/Vertical point references: point ids or `{midpoint: line_id}`.+ pub point_picks: Vec<Value>,/// Inline dimension boxes for the shape being drawn, the point count they were made for,/// and whether the first box should take the keyboard.pub dims: Vec<crate::sketch_dims::DimBox>,@@ -126,6 +128,7 @@ impl Tool {pts: Vec::new(),hover: None,picks: Vec::new(),+ point_picks: Vec::new(),dims: Vec::new(),dim_history: Vec::new(),dims_stage: usize::MAX,@@ -145,7 +148,7 @@ pub fn hint(id: &str) -> String {"sketch.arc.three_point" => "Arc: click start, end, then a point on the arc".into(),"sketch.arc.center_point" => "Arc: click centre and start, then click end or type a signed sweep".into(),"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 to align".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(),_ 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()),@@ -163,9 +166,32 @@ fn xy(p: &(Vec2, Option<String>)) -> Value {json!([p.0.x, p.0.y])}-pub fn on_hover(app: &mut SolveApp, proj: &Proj, pos: Pos2) {+/// Shift exposes a line midpoint as a point target, only in the alignment tool.+fn midpoint_at(app: &SolveApp, proj: &Proj, pos: Pos2, radius: f32) -> Option<(Vec2, String)> {+ let sid = app.session.active_sketch?;+ let state = app.session.world_state();+ let ss = state.sketch(sid)?;+ pick(app, proj, pos).into_iter().find_map(|hit| {+ let Hit::SketchCurve { sketch, id, straight: true, .. } = hit else { return None };+ if sketch != sid {+ return None;+ }+ let l = ss.sketch.curve_index(&id)?;+ let solidcraft_engine::sketch::Shape::Line { a, b } = ss.sketch.shape(l)? else { return None };+ let mid = (a + b) * 0.5;+ let screen = proj.to_screen(ss.plane.to_world(mid))?;+ (screen.distance(pos) <= radius).then_some((mid, id))+ })+}++pub fn on_hover(app: &mut SolveApp, proj: &Proj, pos: Pos2, shift: bool) {crate::sketch3d::on_hover(app, proj, pos);- let h = if let Some(point) = app.tool.as_ref().and_then(|tool| crate::sketch_tools::periodic_start_snap(app, tool, proj, pos)) {+ let midpoint = (shift && app.tool.as_ref().is_some_and(|t| t.kind == Kind::HorizontalVertical))+ .then(|| midpoint_at(app, proj, pos, f32::INFINITY))+ .flatten();+ let h = if let Some((point, _)) = midpoint {+ Some((point, Some("Midpoint".into())))+ } else if let Some(point) = app.tool.as_ref().and_then(|tool| crate::sketch_tools::periodic_start_snap(app, tool, proj, pos)) {Some((point, Some("Close smooth loop".into())))} else {sketch_point_at(app, proj, pos)@@ -175,7 +201,7 @@ pub fn on_hover(app: &mut SolveApp, proj: &Proj, pos: Pos2) {}}-pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2) {+pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2, shift: bool) {// A click away dismisses the inline editor; it must not also pick the first entity of// the next dimension before that cancellation has been processed. The type-first value// of the Dimension tool takes clicks itself (a second pick, or where its text goes).@@ -206,25 +232,28 @@ pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2) {}Kind::HorizontalVertical => {let hits = pick(app, proj, pos);+ let midpoint = shift.then(|| midpoint_at(app, proj, pos, 12.0)).flatten();let hit = hits.iter().find(|hit| match hit {Hit::SketchPoint { sketch, .. } | Hit::SketchCurve { sketch, .. } => Some(*sketch) == app.session.active_sketch,_ => false,});- match hit {- Some(Hit::SketchPoint { id, .. }) => {- if let Some(first) = tool.picks.first() {- if first != id {- let _ = app.run(tool.cmd, json!({"points": [first, id]}));- tool.picks.clear();- }- } else {- tool.picks.push(id.clone());+ let point = midpoint.map(|(_, id)| json!({"midpoint": id})).or_else(|| match hit {+ Some(Hit::SketchPoint { id, .. }) => Some(json!(id)),+ _ => None,+ });+ if let Some(point) = point {+ if let Some(first) = tool.point_picks.first() {+ if first != &point && app.run(tool.cmd, json!({"points": [first, point]})).is_ok() {+ tool.point_picks.clear();}+ } else {+ tool.point_picks.push(point);}- Some(Hit::SketchCurve { id, straight: true, .. }) if tool.picks.is_empty() => {- let _ = app.run(tool.cmd, json!({"line": id}));- }- _ => {}+ } else if !shift+ && tool.point_picks.is_empty()+ && let Some(Hit::SketchCurve { id, straight: true, .. }) = hit+ {+ let _ = app.run(tool.cmd, json!({"line": id}));}}Kind::Pick(n) => {@@ -826,6 +855,9 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) {&& let Some(sp) = to(*hp){painter.circle_stroke(sp, if snap.is_some() { 6.0 } else { 3.0 }, stroke);+ if snap.as_deref() == Some("Midpoint") && t.kind == Kind::HorizontalVertical {+ painter.circle_stroke(sp, 8.0, Stroke::new(2.0, tk.accent));+ }painter.text(sp + egui::vec2(10.0, 10.0),egui::Align2::LEFT_TOP,@@ -834,6 +866,21 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) {tk.text_dim,);}+ if t.kind == Kind::HorizontalVertical {+ for target in &t.point_picks {+ let point = if let Some(id) = target.get("midpoint").and_then(Value::as_str) {+ ss.sketch.curve_index(id).and_then(|l| match ss.sketch.shape(l)? {+ solidcraft_engine::sketch::Shape::Line { a, b } => Some((a + b) * 0.5),+ _ => None,+ })+ } else {+ target.as_str().and_then(|id| ss.sketch.resolve_point(id)).and_then(|p| ss.sketch.point(p))+ };+ if let Some(sp) = point.and_then(to) {+ painter.circle_stroke(sp, 6.0, Stroke::new(2.0, tk.accent));+ }+ }+ }let Some(hover) = t.hover.as_ref() else { return };let h = crate::sketch_dims::shown(app, t, hover);if let Some(corners) = polygon_outline(t, h, crate::sketch_dims::locked_value(app, t, "Sides").unwrap_or(6.0)) {diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rsindex 1a8942798c..aaae8c4a2a 100644--- a/crates/ui-egui/src/viewport.rs+++ b/crates/ui-egui/src/viewport.rs@@ -2520,8 +2520,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {if let Some(p) = ui.input(|i| i.pointer.latest_pos()).filter(|p| rect.contains(*p))&& app.tool.is_some(){- crate::tools::on_hover(app, &proj, p);- crate::tools::on_click(app, &proj, p);+ crate::tools::on_hover(app, &proj, p, mods.shift);+ crate::tools::on_click(app, &proj, p, mods.shift);}}// A two-point shape being dragged out (#1630) follows the pointer and ends where it is let go,@@ -2542,11 +2542,11 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {t.pts.clear();crate::sketch_dims::reset(t);}- crate::tools::on_hover(app, &proj, p);- crate::tools::on_click(app, &proj, p);+ crate::tools::on_hover(app, &proj, p, mods.shift);+ crate::tools::on_click(app, &proj, p, mods.shift);}} else if let Some(p) = at {- crate::tools::on_hover(app, &proj, p);+ crate::tools::on_hover(app, &proj, p, mods.shift);}}// A Trim drag's path follows the pointer; letting go trims what it crossed. A path that@@ -2559,8 +2559,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {&& let Some(p) = at&& app.tool.is_some(){- crate::tools::on_hover(app, &proj, p);- crate::tools::on_click(app, &proj, p);+ crate::tools::on_hover(app, &proj, p, mods.shift);+ crate::tools::on_click(app, &proj, p, mods.shift);}} else if let Some(p) = at {crate::sketch_tools::trim_drag_to(app, &proj, p);@@ -2572,7 +2572,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {crate::sketch_text::set_one_letter(mods.shift);if let Some(p) = hover.filter(|_| inside) {if app.tool.is_some() {- crate::tools::on_hover(app, &proj, p);+ crate::tools::on_hover(app, &proj, p, mods.shift);}// Trim also trims by press and drag across the pieces to remove (its own release handling,// so not a click that moved on the way below).@@ -2598,7 +2598,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {&& resp.drag_started_by(egui::PointerButton::Primary)&& let Some(a) = ui.input(|i| i.pointer.press_origin()){- crate::tools::on_click(app, &proj, a);+ crate::tools::on_click(app, &proj, a, mods.shift);app.viewport.draw_drag = app.tool.as_ref().is_some_and(|t| t.pts.len() == 1).then_some(a);} else if app.tool.is_some()&& !app.viewport.trim_drag@@ -2617,7 +2617,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {&& crate::dim_view::pick_reference(ui.ctx(), p, resp.double_clicked());if resp.clicked() && !held && !reference_pick {if app.tool.is_some() {- crate::tools::on_click(app, &proj, p);+ crate::tools::on_click(app, &proj, p, mods.shift);} else if app.dialog.as_ref().is_some_and(|d| d.wants_picks()) {if let Some((hit, Some(sel))) = cand {dialog_pick(app, &hit, sel);diff --git a/crates/ui-egui/tests/point_alignment.rs b/crates/ui-egui/tests/point_alignment.rsindex a3fc4b151f..5e526d8687 100644--- a/crates/ui-egui/tests/point_alignment.rs+++ b/crates/ui-egui/tests/point_alignment.rs@@ -4,6 +4,12 @@ use serde_json::json;use solidcraft_engine::sketch::ConstraintKind;use solidcraft_ui_egui::scenario::Harness;+fn line_midpoint(sk: &solidcraft_engine::sketch::Sketch, id: &str) -> solidcraft_engine::geom::Vec2 {+ let a = sk.point(sk.resolve_point(&format!("{id}.start")).unwrap()).unwrap();+ let b = sk.point(sk.resolve_point(&format!("{id}.end")).unwrap()).unwrap();+ (a + b) * 0.5+}+#[test]fn horizontal_vertical_uses_preselected_line_and_preserves_rejection() {for fixed in [false, true] {@@ -54,7 +60,7 @@ fn horizontal_vertical_leaves_ambiguous_preselection_to_pick_tool() {h.app.session.selection = selection.clone();let undo = h.app.session.undo.len();h.run(&json!([{"start":"sketch.constraint.horizontal_vertical"}])).unwrap();- assert!(h.app.tool.as_ref().unwrap().picks.is_empty());+ assert!(h.app.tool.as_ref().unwrap().point_picks.is_empty());assert_eq!(h.app.session.undo.len(), undo);assert_eq!(h.app.session.selection, selection);assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error));@@ -110,7 +116,7 @@ fn horizontal_vertical_aligns_origin_and_circle_center() {let (first, second) = if origin_first { ([0.0, 0.0], center) } else { (center, [0.0, 0.0]) };let undo = h.app.session.undo.len();h.run(&json!([{"click":{"sketch":first}}, {"expect":{"errors":0}}])).unwrap();- assert_eq!(h.app.tool.as_ref().unwrap().picks.len(), 1);+ assert_eq!(h.app.tool.as_ref().unwrap().point_picks.len(), 1);assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error));assert_eq!(h.app.session.undo.len(), undo);// Repeating the first point must not complete a self-constraint.@@ -128,7 +134,7 @@ fn horizontal_vertical_aligns_origin_and_circle_center() {matches!(c.kind, ConstraintKind::VerticalPoints { .. })}));assert_eq!(h.app.session.undo.len(), undo + 1);- assert!(h.app.tool.as_ref().unwrap().picks.is_empty());+ assert!(h.app.tool.as_ref().unwrap().point_picks.is_empty());h.run(&json!([{"call":"engine.execute","params":{"command":"edit.undo","params":{}}}])).unwrap();assert!((aligned(&h) - 3.0).abs() < 1e-6);h.run(&json!([{"call":"engine.execute","params":{"command":"edit.redo","params":{}}}])).unwrap();@@ -167,11 +173,11 @@ fn horizontal_vertical_ignores_curves_and_cancels_a_pending_point() {{"click":{"sketch":[25,3]}}])).unwrap();- assert!(h.app.tool.as_ref().unwrap().picks.is_empty());+ assert!(h.app.tool.as_ref().unwrap().point_picks.is_empty());assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error));let undo = h.app.session.undo.len();h.run(&json!([{"click":{"sketch":[0,0]}}, {"click":{"sketch":[25,3]}}])).unwrap();- assert_eq!(h.app.tool.as_ref().unwrap().picks.len(), 1);+ assert_eq!(h.app.tool.as_ref().unwrap().point_picks.len(), 1);h.run(&json!([{"key":"Escape"}])).unwrap();assert!(h.app.tool.is_none());assert_eq!(h.app.session.undo.len(), undo);@@ -179,3 +185,155 @@ fn horizontal_vertical_ignores_curves_and_cancels_a_pending_point() {let p = sk.point(sk.resolve_point("c1.center").unwrap()).unwrap();assert!((p.y - 3.0).abs() < 1e-6);}++#[test]+fn shift_picks_midpoint_in_either_order_and_persists_ordinary_constraints() {+ for (target, horizontal) in [([50., 18.], true), ([23., 50.], false)] {+ for midpoint_first in [true, false] {+ let mut h = Harness::new();+ h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();+ h.app.run("sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false})).unwrap();+ h.app.run("sketch.circle.center", json!({"center":target,"radius":3})).unwrap();+ h.call("ui.view", json!({"view":"top"}));+ h.step(&json!({"start":"sketch.constraint.horizontal_vertical"})).unwrap();+ let before = h.app.session.doc.to_json();+ let undo = h.app.session.undo.len();+ h.step(&json!({"move":{"sketch":[20,15]},"shift":true})).unwrap();+ assert_eq!(h.app.tool.as_ref().unwrap().hover.as_ref().unwrap().1.as_deref(), Some("Midpoint"));+ let midpoint = json!({"click":{"sketch":[20,15]},"shift":true});+ let target = json!({"click":{"sketch":target}});+ let (first, second) = if midpoint_first { (&midpoint, &target) } else { (&target, &midpoint) };+ h.step(first).unwrap();+ h.step(first).unwrap();+ assert_eq!(h.app.tool.as_ref().unwrap().point_picks.len(), 1);+ assert_eq!(h.app.session.undo.len(), undo);+ h.step(second).unwrap();+ assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", h.app.status);+ assert!(h.app.tool.as_ref().unwrap().point_picks.is_empty());+ assert_eq!(h.app.session.undo.len(), undo + 1);+ let sk = &h.app.session.model.state().sketches[0].sketch;+ assert_eq!(sk.points.len(), 5);+ assert_eq!(sk.curves.len(), 2);+ let p = sk.point(sk.resolve_point("c1.center").unwrap()).unwrap();+ let mid = line_midpoint(sk, "l1");+ assert!((if horizontal { p.y - mid.y } else { p.x - mid.x }).abs() < 1e-6);+ assert!(sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })));+ let constraint = sk+ .constraints+ .iter()+ .find(|c| matches!(c.kind, ConstraintKind::HorizontalPoints { .. } | ConstraintKind::VerticalPoints { .. }))+ .unwrap()+ .id+ .clone();+ h.step(&json!({"expect":{"glyphs":{constraint.clone():1}}})).unwrap();+ let after = h.app.session.doc.to_json();+ h.app.run("edit.undo", json!({})).unwrap();+ assert_eq!(h.app.session.doc.to_json(), before);+ h.app.run("edit.redo", json!({})).unwrap();+ assert_eq!(h.app.session.doc.to_json(), after);+ // The ordinary constraint glyph remains selectable and deletable.+ h.step(&json!({"key":"Escape"})).unwrap();+ let glyph = solidcraft_ui_egui::sketch_tools::glyph_positions().into_iter().find(|(id, _)| id == &constraint).unwrap().1;+ h.step(&json!({"click":[glyph.x,glyph.y]})).unwrap();+ h.step(&json!({"key":"Delete"})).unwrap();+ let sk = &h.app.session.model.state().sketches[0].sketch;+ assert!(!sk.constraints.iter().any(|c| c.id == constraint));+ assert_eq!(sk.points.len(), 5);+ let midpoint_constraint = sk.constraints.iter().find(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).unwrap().id.clone();+ // The defining Midpoint relationship is editable through the same glyph UI.+ let glyph = solidcraft_ui_egui::sketch_tools::glyph_positions().into_iter().find(|(id, _)| id == &midpoint_constraint).unwrap().1;+ h.step(&json!({"click":[glyph.x,glyph.y]})).unwrap();+ h.step(&json!({"key":"Delete"})).unwrap();+ let sk = &h.app.session.model.state().sketches[0].sketch;+ assert!(!sk.constraints.iter().any(|c| c.id == midpoint_constraint));+ assert_eq!(sk.points.len(), 5);+ }+ }+}++#[test]+fn shift_midpoint_pick_cancels_and_ignores_round_curves() {+ let mut h = Harness::new();+ h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();+ h.app.run("sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false})).unwrap();+ h.app.run("sketch.circle.center", json!({"center":[40,40],"radius":3})).unwrap();+ h.call("ui.view", json!({"view":"top"}));+ h.step(&json!({"start":"sketch.constraint.horizontal_vertical"})).unwrap();+ let before = h.app.session.doc.to_json();+ h.step(&json!({"click":{"sketch":[43,40]},"shift":true})).unwrap();+ assert!(h.app.tool.as_ref().unwrap().point_picks.is_empty());+ h.step(&json!({"click":{"sketch":[20,15]},"shift":true})).unwrap();+ assert_eq!(h.app.tool.as_ref().unwrap().point_picks, vec![json!({"midpoint":"l1"})]);+ h.step(&json!({"key":"Escape"})).unwrap();+ assert!(h.app.tool.is_none());+ assert_eq!(h.app.session.doc.to_json(), before);+}++#[test]+fn shift_can_align_two_midpoints_and_reveal_one_from_anywhere_on_the_line() {+ let mut h = Harness::new();+ h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();+ for points in [json!([[10, 10], [30, 20]]), json!([[15, 40], [35, 50]])] {+ h.app.run("sketch.line", json!({"points":points,"infer":false,"connect":false})).unwrap();+ }+ h.call("ui.view", json!({"view":"top"}));+ h.step(&json!({"start":"sketch.constraint.horizontal_vertical"})).unwrap();+ h.step(&json!({"move":{"sketch":[13,11.5]},"shift":true})).unwrap();+ let hover = h.app.tool.as_ref().unwrap().hover.as_ref().unwrap();+ assert_eq!([hover.0.x, hover.0.y], [20., 15.]);+ assert_eq!(hover.1.as_deref(), Some("Midpoint"));+ h.step(&json!({"click":{"sketch":[20,15]},"shift":true})).unwrap();+ h.step(&json!({"click":{"sketch":[25,45]},"shift":true})).unwrap();+ assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", h.app.status);+ let sk = &h.app.session.model.state().sketches[0].sketch;+ assert_eq!(sk.points.len(), 7);+ assert_eq!(sk.curves.len(), 2);+ let mid = |id| line_midpoint(sk, id);+ assert!((mid("l1").x - mid("l2").x).abs() < 1e-6);+}++#[test]+fn midpoint_aligns_to_the_fixed_origin_without_straightening_the_line() {+ for midpoint_first in [true, false] {+ let mut h = Harness::new();+ h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();+ h.app.run("sketch.line", json!({"points":[[-10,15],[16,25]],"infer":false,"connect":false})).unwrap();+ h.call("ui.view", json!({"view":"top"}));+ h.step(&json!({"start":"sketch.constraint.horizontal_vertical"})).unwrap();+ let midpoint = json!({"click":{"sketch":[3,20]},"shift":true});+ let origin = json!({"click":{"sketch":[0,0]}});+ let (first, second) = if midpoint_first { (&midpoint, &origin) } else { (&origin, &midpoint) };+ h.step(first).unwrap();+ h.step(second).unwrap();+ assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", h.app.status);+ let sk = &h.app.session.model.state().sketches[0].sketch;+ assert_eq!(sk.points.len(), 4);+ let a = sk.point(sk.resolve_point("l1.start").unwrap()).unwrap();+ let b = sk.point(sk.resolve_point("l1.end").unwrap()).unwrap();+ assert!(((a + b) * 0.5).x.abs() < 1e-6);+ assert!((b.x - a.x).abs() > 1. && (b.y - a.y).abs() > 1., "only the midpoint is aligned");+ assert_eq!(sk.point(0).unwrap(), solidcraft_engine::geom::Vec2::ZERO);+ }+}++#[test]+fn conflicting_midpoint_pick_keeps_pending_preview_without_creating_geometry() {+ let mut h = Harness::new();+ h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();+ h.app.run("sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false})).unwrap();+ h.app.run("sketch.circle.center", json!({"center":[24,50],"radius":3})).unwrap();+ h.app.run("sketch.constraint.fix", json!({"entities":["l1","c1"]})).unwrap();+ h.call("ui.view", json!({"view":"top"}));+ h.step(&json!({"start":"sketch.constraint.horizontal_vertical"})).unwrap();+ let before = h.app.session.doc.to_json();+ let undo = h.app.session.undo.len();+ h.step(&json!({"click":{"sketch":[20,15]},"shift":true})).unwrap();+ h.step(&json!({"click":{"sketch":[24,50]}})).unwrap();+ assert!(h.app.status.as_ref().is_some_and(|(_, _, error)| *error));+ assert_eq!(h.app.session.doc.to_json(), before);+ assert_eq!(h.app.session.undo.len(), undo);+ assert_eq!(h.app.tool.as_ref().unwrap().point_picks, vec![json!({"midpoint":"l1"})]);+ h.step(&json!({"key":"Escape"})).unwrap();+ assert!(h.app.tool.is_none());+ assert_eq!(h.app.session.doc.to_json(), before);+}diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.mdindex c74d2c3011..08752de014 100644--- a/docs/book/src/guide/sketching.md+++ b/docs/book/src/guide/sketching.md@@ -174,7 +174,22 @@ fresh link once the source is available; their stored point values are preserved**Horizontal/Vertical** accepts a click on a line or clicks on two distinct sketch points,including the origin, endpoints and circle centres. For two points, it chooses horizontal-or vertical alignment from their current positions. Esc cancels a pending first point.+or vertical alignment from their current positions. Hold **Shift** near a line's midpoint to+highlight and select it as either point. The midpoint follows both endpoints as the line moves,+resizes or rotates. Two line midpoints can also be aligned. Hovering and the first pick are+only previews; Esc cancels them without changing the sketch. Accepting the second pick reuses+or creates a sketch point with an ordinary Midpoint constraint, then adds the H/V constraint+in one undo step. Both constraints can be selected and deleted independently; deleting either+keeps the point. After a fillet or chamfer, its Midpoint constraint refers to the original full+side, retained as construction geometry, just like a manually constrained midpoint.++Scripts use the same command, with a midpoint reference in the `points` array:++```json+{"command":"sketch.constraint.horizontal_vertical","params":{"points":[{"midpoint":"l1"},"c1.center"],"mode":"vertical"}}+```++`mode` can be `horizontal` or `vertical`; omitting it chooses from the current positions.The solver is SolidCraft's own (damped Gauss–Newton with degree-of-freedom analysis). Constraints:coincident, horizontal/vertical, parallel, perpendicular, tangent, equal, concentric, collinear,