SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Sketch: constrain to an edge of any body, a mirrored copy too (#6348) (#6617)
yhamil04d7252f2240bd
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rsindex 9afcc606ed..95cccd8cbd 100644--- a/crates/engine/src/cmd/sketch.rs+++ b/crates/engine/src/cmd/sketch.rs@@ -25,6 +25,12 @@ macro_rules! connect_doc {};}+macro_rules! model_operand_doc {+ () => {+ "; any of them may be a model edge {edge: [x,y,z], body?} or vertex {vertex: [x,y,z], body?}, projected into the sketch first (reported in created)"+ };+}+pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("sketch.create", "Create Sketch", create_sketch).at("SOLID", "CREATE")@@ -131,27 +137,27 @@ pub static COMMANDS: &[CommandSpec] = &[.at("SKETCH", "CONSTRAINTS").icon("c_coincident").enabled(in_sketch)- .params("a, b: points, a point and a curve or sketch axis (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created), or two distinct lines (joins their closest endpoints), or two circles/arcs (the second lies on the first: concentric and equal, `constraints` lists both)"),+ .params(concat!("a, b: points, a point and a curve or sketch axis (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created), or two distinct lines (joins their closest endpoints), or two circles/arcs (the second lies on the first: concentric and equal, `constraints` lists both)", model_operand_doc!())),CommandSpec::new("sketch.constraint.tangent", "Tangent", c_tangent).at("SKETCH", "CONSTRAINTS").icon("c_tangent").enabled(in_sketch)- .params("a, b: curves or sketch axes (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created)"),+ .params(concat!("a, b: curves or sketch axes (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created)", model_operand_doc!())),CommandSpec::new("sketch.constraint.equal", "Equal", c_equal).at("SKETCH", "CONSTRAINTS").icon("c_equal").enabled(in_sketch)- .params("a, b: lines or circles/arcs; or curves: [2 to 200 lines or circles/arcs], each made equal to the first, in one step"),+ .params(concat!("a, b: lines or circles/arcs; or curves: [2 to 200 lines or circles/arcs], each made equal to the first, in one step", model_operand_doc!())),CommandSpec::new("sketch.constraint.parallel", "Parallel", c_parallel).at("SKETCH", "CONSTRAINTS").icon("c_parallel").enabled(in_sketch)- .params("a, b: lines or sketch axes (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created)"),+ .params(concat!("a, b: lines or sketch axes (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created)", model_operand_doc!())),CommandSpec::new("sketch.constraint.perpendicular", "Perpendicular", c_perpendicular).at("SKETCH", "CONSTRAINTS").icon("c_perpendicular").enabled(in_sketch)- .params("a, b: lines or sketch axes (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created)"),+ .params(concat!("a, b: lines or sketch axes (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created)", model_operand_doc!())),CommandSpec::new("sketch.constraint.fix", "Fix/UnFix", c_fix).at("SKETCH", "CONSTRAINTS").icon("c_fix")@@ -161,22 +167,22 @@ pub static COMMANDS: &[CommandSpec] = &[.at("SKETCH", "CONSTRAINTS").icon("c_midpoint").enabled(in_sketch)- .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)"),+ .params(concat!("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)", model_operand_doc!())),CommandSpec::new("sketch.constraint.concentric", "Concentric", c_concentric).at("SKETCH", "CONSTRAINTS").icon("c_concentric").enabled(in_sketch)- .params("a, b: circles/arcs"),+ .params(concat!("a, b: circles/arcs", model_operand_doc!())),CommandSpec::new("sketch.constraint.collinear", "Collinear", c_collinear).at("SKETCH", "CONSTRAINTS").icon("c_collinear").enabled(in_sketch)- .params("a, b: lines or sketch axes (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created)"),+ .params(concat!("a, b: lines or sketch axes (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created)", model_operand_doc!())),CommandSpec::new("sketch.constraint.symmetry", "Symmetry", c_symmetry).at("SKETCH", "CONSTRAINTS").icon("c_symmetry").enabled(in_sketch)- .params("a, b: two points or two curves (lines mirror their ends, circles/arcs their centres); line: symmetry line id, or x / y for the sketch's own axes (a curve with that id wins; an axis becomes a linked construction line on it, reported in created); or point (or a point id as line, \"origin\" too): symmetric about that point, each pair joined by a construction line it is the midpoint of"),+ .params(concat!("a, b: two points or two curves (lines mirror their ends, circles/arcs their centres); line: symmetry line id, or x / y for the sketch's own axes (a curve with that id wins; an axis becomes a linked construction line on it, reported in created); or point (or a point id as line, \"origin\" too): symmetric about that point, each pair joined by a construction line it is the midpoint of", model_operand_doc!())),CommandSpec::new("sketch.construction", "Normal/Construction", construction).at("SKETCH", "CREATE").icon("construction")@@ -1862,6 +1868,7 @@ fn c_horizontal_vertical(s: &mut Session, p: &Value) -> Result<Value> {fn c_coincident(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "sketch.constraint.coincident";+ let p = &super::sketch_project::project_operands(s, p, cmd, &["a", "b"])?;// Already tied (e.g. connected when it was drawn there): nothing to add.let sk = s.doc.sketch(target_sketch(s, p, cmd)?)?;if let Some((a, b)) = two_round(sk, p) {@@ -1973,6 +1980,7 @@ fn two_curves_or_axes(sk: &mut Sketch, p: &Value, cmd: &str) -> Result<(usize, u}fn c_tangent(s: &mut Session, p: &Value) -> Result<Value> {+ let p = &super::sketch_project::project_operands(s, p, "sketch.constraint.tangent", &["a", "b"])?;constrain(s, p, "sketch.constraint.tangent", |sk| {two_curves_or_axes(sk, p, "sketch.constraint.tangent").map(|(a, b)| ConstraintKind::Tangent { a, b })})@@ -1981,6 +1989,7 @@ fn c_equal(s: &mut Session, p: &Value) -> Result<Value> {if p.get("curves").is_some() {return equal_curves(s, p);}+ let p = &super::sketch_project::project_operands(s, p, "sketch.constraint.equal", &["a", "b"])?;constrain(s, p, "sketch.constraint.equal", |sk| two_curves(sk, p, "sketch.constraint.equal").map(|(a, b)| ConstraintKind::Equal { a, b }))}@@ -2016,27 +2025,32 @@ fn equal_curves(s: &mut Session, p: &Value) -> Result<Value> {Ok(json!({"constraints": out, "sketch": info}))}fn c_parallel(s: &mut Session, p: &Value) -> Result<Value> {+ let p = &super::sketch_project::project_operands(s, p, "sketch.constraint.parallel", &["a", "b"])?;constrain(s, p, "sketch.constraint.parallel", |sk| {two_curves_or_axes(sk, p, "sketch.constraint.parallel").map(|(a, b)| ConstraintKind::Parallel { a, b })})}fn c_perpendicular(s: &mut Session, p: &Value) -> Result<Value> {+ let p = &super::sketch_project::project_operands(s, p, "sketch.constraint.perpendicular", &["a", "b"])?;constrain(s, p, "sketch.constraint.perpendicular", |sk| {two_curves_or_axes(sk, p, "sketch.constraint.perpendicular").map(|(a, b)| ConstraintKind::Perpendicular { a, b })})}fn c_concentric(s: &mut Session, p: &Value) -> Result<Value> {+ let p = &super::sketch_project::project_operands(s, p, "sketch.constraint.concentric", &["a", "b"])?;constrain(s, p, "sketch.constraint.concentric", |sk| {two_curves(sk, p, "sketch.constraint.concentric").map(|(a, b)| ConstraintKind::Concentric { a, b })})}fn c_collinear(s: &mut Session, p: &Value) -> Result<Value> {+ let p = &super::sketch_project::project_operands(s, p, "sketch.constraint.collinear", &["a", "b"])?;constrain(s, p, "sketch.constraint.collinear", |sk| {two_curves_or_axes(sk, p, "sketch.constraint.collinear").map(|(a, b)| ConstraintKind::Collinear { a, b })})}fn c_midpoint(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "sketch.constraint.midpoint";+ let p = &super::sketch_project::project_operands(s, p, cmd, &["a", "b", "point", "line"])?;let p = &line_stays(s, p, cmd);constrain(s, p, cmd, |sk| {if p.get("a").is_none() && p.get("b").is_none() {@@ -2134,6 +2148,7 @@ fn arc_end(sk: &Sketch, c: usize, q: usize) -> bool {fn c_symmetry(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "sketch.constraint.symmetry";+ let p = &super::sketch_project::project_operands(s, p, cmd, &["a", "b", "line", "point"])?;let (ids, info) = edit(s, p, cmd, true, |sk, _| {if let Some(c) = symmetry_center(sk, p, cmd)? {return symmetry_about_point(sk, p, c, cmd);diff --git a/crates/engine/src/cmd/sketch_project.rs b/crates/engine/src/cmd/sketch_project.rsindex 6120439d6d..5749b94319 100644--- a/crates/engine/src/cmd/sketch_project.rs+++ b/crates/engine/src/cmd/sketch_project.rs@@ -333,6 +333,38 @@ fn include_cmd(s: &mut Session, p: &Value) -> Result<Value> {run_links(s, p, "sketch.include_3d", LinkKind::Include)}+/// A constraint's operands may be model geometry (#6348): an `{edge: [x,y,z], body?}` or+/// `{vertex: [x,y,z], body?}` under one of `keys` is projected into the sketch first, as+/// Project does, and stands for the projected curve (or point) in the parameters returned.+/// Any body's edges work, a mirrored or patterned copy's too; the link keeps the edge's+/// persistent name, so the constraint follows the edge through rebuilds.+pub(super) fn project_operands(s: &mut Session, p: &Value, cmd: &str, keys: &[&str]) -> Result<Value> {+ let model = |v: &Value| v.get("edge").is_some() || v.get("vertex").is_some();+ if !keys.iter().any(|k| p.get(*k).is_some_and(model)) {+ return Ok(p.clone());+ }+ let id = super::sketch::target_sketch(s, p, cmd)?;+ let mut doc = (*s.doc).clone();+ let mut sk = doc.sketch(id)?.clone();+ refresh(s, &doc, id, &mut sk);+ let mut out = p.clone();+ for key in keys {+ let Some(v) = p.get(*key).filter(|v| model(v)) else { continue };+ let src = source(s, v, cmd)?;+ let what = src.describe();+ let link = add_link(s, &doc, id, &mut sk, LinkKind::Project, src).map_err(|e| bad(cmd, format!("{what}: {e}")))?;+ // An edge stands for its curve (a point when it is seen end on), a vertex for its point.+ let curve = if v.get("edge").is_some() { sk.link_curves(&link).first().and_then(|c| sk.curves.get(*c)).map(|c| c.id.clone()) } else { None };+ let entity = curve+ .or_else(|| sk.link_points(&link).first().and_then(|q| sk.points.get(*q)).map(|q| q.id.clone()))+ .ok_or_else(|| bad(cmd, format!("{what} projects to nothing on this sketch")))?;+ out[*key] = json!(entity);+ }+ *doc.sketch_mut(id)? = sk;+ *s.doc_mut() = doc;+ Ok(out)+}+/// Add one link from `src` to the active sketch and report it.fn one_link(s: &mut Session, cmd: &str, kind: LinkKind, src: LinkSource) -> Result<Value> {let id = s.active_sketch.ok_or_else(|| EngineError::Other("no sketch is being edited".into()))?;diff --git a/crates/engine/src/cmd/sketch_project_edge_tests.rs b/crates/engine/src/cmd/sketch_project_edge_tests.rsindex b5db66a298..db3528ae19 100644--- a/crates/engine/src/cmd/sketch_project_edge_tests.rs+++ b/crates/engine/src/cmd/sketch_project_edge_tests.rs@@ -226,3 +226,64 @@ fn an_edge_link_saved_without_a_name_is_found_as_before_and_named_by_the_next_edassert_eq!(trouble(&s), "");assert_line(&s, 150.0, (0.0, 50.0), "width 150");}++/// The ends of curve `curve` of sketch `Top` as the model solves it.+fn line_of(s: &Session, curve: &str) -> (Vec2, Vec2) {+ let st = s.model.state();+ let sk = &st.sketch(s.doc.find_feature("Top").unwrap().id).unwrap().sketch;+ match sk.shape(sk.curve_index(curve).unwrap()) {+ Some(Shape::Line { a, b }) => (a, b),+ other => panic!("not a line: {other:?}"),+ }+}++/// An edge of a mirrored body is constrained to like any other body's edge (#6348). The plate+/// mirrored about YZ gives a copy from x = -width to 0. Collinear with the copy's outer top+/// edge (x = -width) projects that edge into the sketch and holds the line on it, in one step;+/// the link keeps the copy's edge name, so the line follows the copy when the width changes,+/// and after the design is saved and opened. A vertex of the copy works the same way, and a+/// reference that misses every edge changes nothing.+#[test]+fn a_line_is_constrained_collinear_with_an_edge_of_a_mirrored_body() {+ let mut s = Session::default();+ plate(&mut s);+ run(&mut s, "solid.mirror", json!({"bodies": ["Body1"], "plane": "YZ", "name": "Twin"}));+ let copy = s.model.state().bodies.iter().find(|b| b.name != "Body1").map(|b| b.name.clone()).expect("the mirrored copy");+ run(&mut s, "sketch.create", json!({"plane": "XY", "offset": "20 mm", "name": "Top"}));+ run(&mut s, "sketch.line", json!({"points": [[-90, 5], [-90, 45]]}));+ let before = s.doc.clone();+ let out = run(&mut s, "sketch.constraint.collinear", json!({"a": "l1", "b": {"edge": [-100, 25, 20], "body": copy}}));+ assert_eq!(out["created"]["curves"].as_array().map(Vec::len), Some(1), "the projected edge: {out}");+ let stored = s.doc.sketch(s.doc.find_feature("Top").unwrap().id).unwrap();+ assert_eq!(stored.links.len(), 1);+ assert!(matches!(&stored.links[0].source, LinkSource::Edge { body, .. } if *body == copy), "{:?}", stored.links[0].source);+ let name = stored.links[0].edge_name.clone().expect("the copy's edge keeps its name");+ // Undone in one step: the projection and the constraint together.+ run(&mut s, "edit.undo", json!({}));+ assert_eq!(s.doc.to_json(), before.to_json());+ run(&mut s, "edit.redo", json!({}));+ run(&mut s, "sketch.finish", json!({}));+ let on_edge = |s: &Session, x: f64, when: &str| {+ let (a, b) = line_of(s, "l1");+ assert!((a.x - x).abs() < 1e-6 && (b.x - x).abs() < 1e-6, "{when}: expected the line on x = {x}: {a:?} {b:?}");+ };+ on_edge(&s, -100.0, "constrained");+ for width in [150.0, 60.0] {+ set_width(&mut s, width);+ assert_eq!(trouble(&s), "", "width {width}");+ assert!(!link(&s).lost, "width {width}");+ on_edge(&s, -width, &format!("width {width}"));+ }+ let opened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());+ assert_eq!(link(&opened).edge_name.as_deref(), Some(name.as_str()));+ on_edge(&opened, -60.0, "opened");+ // A vertex of the copy: the line's end goes onto its corner (-60, 50, 20).+ run(&mut s, "sketch.edit", json!({"sketch": "Top"}));+ run(&mut s, "sketch.constraint.coincident", json!({"a": "l1.end", "b": {"vertex": [-60, 50, 20], "body": copy}}));+ let (_, end) = line_of(&s, "l1");+ assert!(end.dist(Vec2::new(-60.0, 50.0)) < 1e-6, "{end:?}");+ // Nothing there: an error, and the sketch as it was.+ let before = s.doc.to_json();+ assert!(s.execute("sketch.constraint.collinear", &json!({"a": "l1", "b": {"edge": [500, 500, 20], "body": copy}})).is_err());+ assert_eq!(s.doc.to_json(), before);+}diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rsindex 6a9236bc4b..ecc73632ce 100644--- a/crates/ui-egui/src/sketch_tools.rs+++ b/crates/ui-egui/src/sketch_tools.rs@@ -676,7 +676,7 @@ fn active_sketch(app: &SolveApp) -> Option<u64> {}/// A model reference for a hit (for Project and friends).-fn model_ref(app: &SolveApp, h: &Hit) -> Option<Value> {+pub(crate) fn model_ref(app: &SolveApp, h: &Hit) -> Option<Value> {let active = active_sketch(app);Some(match h {Hit::Vertex { body, point } => json!({"vertex": [point.x, point.y, point.z], "body": body}),diff --git a/crates/ui-egui/src/symmetry_pick_tests.rs b/crates/ui-egui/src/symmetry_pick_tests.rsindex da7d9c19fd..4aafd83982 100644--- a/crates/ui-egui/src/symmetry_pick_tests.rs+++ b/crates/ui-egui/src/symmetry_pick_tests.rs@@ -1,5 +1,6 @@//! The Symmetry tool's third pick may be the origin point or an origin axis (#1075); with three//! lines, the construction line between the other two is the symmetry line in any pick order (#1796).+//! A constraint tool's pick may be a body's edge, a mirrored copy's too (#6348).use serde_json::json;use solidcraft_engine::geom::Vec2;@@ -96,3 +97,36 @@ fn three_selected_lines_take_the_construction_line_as_the_symmetry_line() {let params = crate::tools::constraint_preselection("sketch.constraint.symmetry", &sel(["left", "right", "mid"]), None).unwrap();assert_eq!(params["line"], "mid");}++/// A plate from x = 20 to 120 (y 0..50, 20 thick) mirrored about YZ, a sketch on its top with the+/// plate's top face projected, and a line at x = -100 over the copy, whose outer top edge is at+/// x = -120 and not in the sketch. Collinear: the line, then that edge. The click on the edge+/// projects it, and the line goes onto it, in one undo step (#6348).+#[test]+fn collinear_with_an_edge_of_a_mirrored_body_projects_the_edge() {+ let mut h = Harness::new();+ h.app.run("sketch.create", json!({"plane":"XY","name":"Base"})).unwrap();+ h.app.run("sketch.rectangle.two_point", json!({"p0":[20,0],"p1":[120,50]})).unwrap();+ h.app.run("sketch.finish", json!({})).unwrap();+ h.app.run("solid.extrude", json!({"sketch":"Base","distance":"20 mm"})).unwrap();+ h.app.run("solid.mirror", json!({"bodies":["Body1"],"plane":"YZ"})).unwrap();+ h.app.run("sketch.create", json!({"plane":{"face":[70,25,20]},"name":"Top"})).unwrap();+ h.app.run("sketch.line", json!({"points":[[-100,10],[-100,40]],"ids":["side"]})).unwrap();+ h.app.cam.target = solidcraft_engine::geom::Vec3::new(-60.0, 25.0, 20.0);+ h.app.cam.distance = 300.0;+ h.settle();+ let sketch = h.app.session.active_sketch.unwrap();+ let links = |h: &Harness| h.app.session.doc.sketch(sketch).unwrap().links.len();+ assert_eq!(links(&h), 1, "the plate's top face only");+ h.app.start("sketch.constraint.collinear");+ let line = h.call("ui.at", json!({"sketch":[-100,25]}))["result"].clone();+ h.step(&json!({ "click": line })).unwrap();+ let edge = h.call("ui.at", json!({"world":[-120,25,20]}))["result"].clone();+ h.step(&json!({ "click": edge })).unwrap();+ assert_eq!(links(&h), 2, "the copy's edge is projected");+ let (a, b) = (point(&h, "side.start"), point(&h, "side.end"));+ assert!((a.x + 120.0).abs() < 1e-6 && (b.x + 120.0).abs() < 1e-6, "on the copy's edge: {a:?} {b:?}");+ h.app.run("edit.undo", json!({})).unwrap();+ assert_eq!(links(&h), 1, "undone with the constraint");+ assert!((point(&h, "side.start").x + 100.0).abs() < 1e-6);+}diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rsindex 11d1bd58dc..7bac922757 100644--- a/crates/ui-egui/src/tools.rs+++ b/crates/ui-egui/src/tools.rs@@ -282,11 +282,21 @@ pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2, shift: bool) {// Symmetry's third pick may be an origin axis lying along the sketch's own x or y// (#1075); the command names those `x` / `y`.let axis_ok = tool.cmd == "sketch.constraint.symmetry" && tool.picks.len() == 2;- if let Some(id) = hits.iter().find_map(|h| match h {+ let entity = hits.iter().find_map(|h| match h {Hit::SketchPoint { id, .. } | Hit::SketchCurve { id, .. } => Some(id.clone()),Hit::Axis { name } if axis_ok => sketch_axis_of(app, name).map(str::to_string),_ => None,- }) {+ });+ // With nothing of the sketch there, a body's edge or vertex is picked (kept as its+ // reference): the command projects it, so any body can be constrained to, a mirrored+ // copy too (#6348). Projected geometry is already fixed, so Fix takes sketch entities.+ let model = || {+ hits.iter()+ .filter(|h| tool.cmd != "sketch.constraint.fix" && matches!(h, Hit::Edge { .. } | Hit::Vertex { .. }))+ .find_map(|h| crate::sketch_tools::model_ref(app, h))+ .map(|r| r.to_string())+ };+ if let Some(id) = entity.or_else(model) {tool.picks.push(id);}if tool.picks.len() >= n {@@ -710,17 +720,17 @@ fn symmetry_args(picks: &[Value], sketch: Option<&solidcraft_engine::sketch::Ske}fn run_pick(app: &mut SolveApp, t: &Tool) {- let k = &t.picks;+ // An entity id, or a model edge's or vertex's reference.+ let k: Vec<Value> = t.picks.iter().map(|pick| serde_json::from_str(pick).ok().filter(Value::is_object).unwrap_or_else(|| json!(pick))).collect();let params = match t.cmd {"sketch.constraint.fix" => json!({"entity": k[0]}),"sketch.constraint.coincident" => json!({"a": k[0], "b": 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" => {- let picks: Vec<Value> = k.iter().map(|pick| json!(pick)).collect();let params = {let state = app.session.world_state();- symmetry_args(&picks, app.session.active_sketch.and_then(|id| state.sketch(id)).map(|ss| &ss.sketch))+ symmetry_args(&k, app.session.active_sketch.and_then(|id| state.sketch(id)).map(|ss| &ss.sketch))};let Some(params) = params else {app.set_status("Symmetry: pick two points or two curves and the line between them", true);