Allow sketch Mirror to use origin axes (#4193) (#4207)

* claim: #4193

* Sketch Mirror: an origin axis can be the mirror line (#4193)

Mirror accepted only a straight curve of the sketch. It now also takes an
origin axis that lies in the sketch plane ({axis: X|Y|Z}), projected into
the sketch as a fixed linked line, so the copies stay symmetric to it and
follow the source when it moves.

* Sketch Mirror: use current sketch store (#4193)
This commit is contained in:
raykholo authored and GitHub committed 2026-10-29 05:08:00 +00:00
1 parent fed7ea0c88
commit afe7dcd4e1
6 files changed
+159 -12

No files matched your search

+18 -5
View File
@@ -8,7 +8,7 @@ use solidcraft_doc::ProfileSel;
use solidcraft_geom::Vec2;
use solidcraft_sketch::{ConstraintKind, Curve, CurveKind, Shape, Sketch, intersections, intersections_within};
use super::sketch::{add_c, edit, ids_of, solve_current};
use super::sketch::{add_c, edit, ids_of, line_or_axis_ref, solve_current};
use super::sketch_store;
use super::{CommandSpec, in_sketch};
use crate::params::{bad, bool_, expr, num, req_expr, req_vec2, str_, string_list, vec2, vec2_list};
@@ -97,7 +97,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.at("SKETCH", "PATTERN")
.icon("sketch_mirror")
.enabled(in_sketch)
.params(concat!("entities: [curve/point ids], line: mirror line id (symmetry constraints are added)", created_doc!())),
.params(concat!("entities: [curve/point ids], line: straight curve id, x / y for a sketch axis, or {axis: X|Y|Z} for an origin axis in the sketch plane (symmetry constraints are added)", created_doc!())),
CommandSpec::new("sketch.pattern.circular", "Circular Pattern", pattern_circular)
.at("SKETCH", "PATTERN")
.icon("sketch_circ_pattern")
@@ -2630,11 +2630,24 @@ fn copy_through(
fn mirror(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.mirror";
let origin_axis =
p.get("line").filter(|line| line.is_object()).map(|line| super::sketch_project::origin_axis_line(s, p, line, cmd)).transpose()?;
let (out, info) = edit(s, p, cmd, false, |sk, _| {
let (cs, ps) = entities(sk, p, cmd)?;
let lid = str_(p, "line").ok_or_else(|| bad(cmd, "`line` must be the mirror line"))?;
let l = sk.curve_index(lid).ok_or_else(|| bad(cmd, format!("unknown curve `{lid}`")))?;
let Some(Shape::Line { a, b }) = sk.shape(l) else { return Err(bad(cmd, "the mirror must be a line")) };
let l = if let Some((source, geom)) = origin_axis {
let link =
sk.links.iter().find(|link| link.kind == solidcraft_sketch::LinkKind::Project && link.source == source).map(|link| link.id.clone());
let link = match link {
Some(link) => link,
None => sk.add_link(solidcraft_sketch::LinkKind::Project, source, &geom)?,
};
sk.link_curves(&link).first().copied().ok_or_else(|| bad(cmd, "the origin axis does not resolve to a straight line"))?
} else {
line_or_axis_ref(sk, p.get("line"), cmd, "line")?
};
let Some(Shape::Line { a, b }) = sk.shape(l) else {
return Err(bad(cmd, "the mirror must be a straight curve of this sketch or an origin axis in its plane"));
};
let u = (b - a).normalized().ok_or_else(|| bad(cmd, "degenerate mirror line"))?;
let refl = move |q: Vec2| {
let foot = a + u * (q - a).dot(u);
@@ -3184,3 +3184,57 @@ fn extend_two_collinear_lines_are_refused_as_collinear() {
let e = s.execute("sketch.extend", &json!({"curves": [a, c]})).unwrap_err().to_string();
assert!(e.contains("collinear"), "{e}");
}
#[test]
fn mirror_origin_axes_keep_symmetry_and_fully_constrained_sources_driving_copies() {
for axis in ["x", "y"] {
let mut s = new_sketch();
run(&mut s, "parameters.add", json!({"name":"width","expression":"10 mm"}));
run(&mut s, "sketch.line", json!({"points":[["width","3 mm"],["width + 5 mm","8 mm"]],"ids":["source"]}));
let before = run(&mut s, "sketch.inspect", json!({}))["dof"].clone();
assert_eq!(before, 0);
let out = run(&mut s, "sketch.mirror", json!({"entities":["source"],"line":axis}));
assert_eq!(out["sketch"]["dof"], before);
let copy = out["curves"][0].as_str().unwrap();
for width in [10, 20] {
if width == 20 {
run(&mut s, "parameters.change", json!({"name":"width","expression":"20 mm"}));
}
let sk = sketch(&s);
let l = sk.sketch_axis_curve(axis).unwrap();
assert!(sk.is_linked_curve(l) && sk.curves[l].construction);
assert_eq!(sk.constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Symmetric { l: line, .. } if line == l)).count(), 2);
for (source_end, copy_end, x, y) in [("start", "end", width, 3), ("end", "start", width + 5, 8)] {
let source = sk.point(sk.resolve_point(&format!("source.{source_end}")).unwrap()).unwrap();
assert!(source.dist(Vec2::new(x as f64, y as f64)) < 1e-6);
let expected = if axis == "y" { Vec2::new(-source.x, source.y) } else { Vec2::new(source.x, -source.y) };
let actual = sk.point(sk.resolve_point(&format!("{copy}.{copy_end}")).unwrap()).unwrap();
assert!(actual.dist(expected) < 1e-6, "{axis}: {actual:?} != {expected:?}");
}
assert_eq!(run(&mut s, "sketch.inspect", json!({}))["dof"], before);
}
}
}
#[test]
fn mirror_origin_axis_in_rotated_plane_reuses_projection_and_rejects_invalid_lines() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane":{"origin":[0,5,0],"x_dir":[1,1,0],"y_dir":[-1,1,0]}}));
run(&mut s, "sketch.line", json!({"points":[[10,3],[15,8]],"ids":["source"]}));
let out = run(&mut s, "sketch.mirror", json!({"entities":["source"],"line":{"axis":"Y"}}));
let sk = sketch(&s);
let copy = out["curves"][0].as_str().unwrap();
for (source_end, copy_end) in [("start", "end"), ("end", "start")] {
let source = sk.point(sk.resolve_point(&format!("source.{source_end}")).unwrap()).unwrap();
let copy = sk.point(sk.resolve_point(&format!("{copy}.{copy_end}")).unwrap()).unwrap();
assert!(copy.dist(Vec2::new(source.y, source.x)) < 1e-6, "{source:?}: {copy:?}");
}
run(&mut s, "sketch.mirror", json!({"entities":["source"],"line":{"axis":"Y"}}));
assert_eq!(sketch(&s).links.len(), 1);
run(&mut s, "sketch.circle.center", json!({"center":[20,10],"radius":2,"id":"circle"}));
let before = s.doc.to_json();
for line in [json!({"axis":"Z"}), json!({"axis":"bad"}), json!({"plane":"XY"}), json!("circle"), json!("missing")] {
assert!(s.execute("sketch.mirror", &json!({"entities":["source"],"line":line})).is_err(), "{line}");
assert_eq!(s.doc.to_json(), before);
}
}
+23
View File
@@ -231,6 +231,29 @@ pub(super) mod refresh_count {
}
}
/// Resolve an origin axis as a mirror line, keeping its projection linked and fixed.
pub(super) fn origin_axis_line(s: &Session, p: &Value, line: &Value, cmd: &str) -> Result<(LinkSource, Vec<solidcraft_sketch::LinkGeom>)> {
let id = sketch_store::target(s, p, cmd)?;
let doc = placed_candidate(s, &s.doc);
let st = s.model.state_before(id);
let st = state_for_sketch(s, &doc, id, &st)?;
let plane = sketch_plane(&doc, id, &st)?;
let src = source(s, line, cmd)?;
let LinkSource::Axis { name } = &src else { return Err(bad(cmd, "the mirror line must be a straight sketch curve or an origin axis")) };
let dir = match name.as_str() {
"X" => Vec3::X,
"Y" => Vec3::Y,
"Z" => Vec3::Z,
_ => return Err(bad(cmd, "the origin axis must be X, Y or Z")),
};
if plane.normal().dot(dir).abs() > 1e-9 || plane.normal().dot(plane.origin).abs() > 1e-6 {
return Err(bad(cmd, "the origin axis must lie in the sketch plane"));
}
let (vals, _) = doc.param_values();
let r = resolve(&doc, &vals, &st, &plane, LinkKind::Project, &src)?;
Ok((r.source, r.geom))
}
/// Add a link for `src` to sketch `id` in `doc` (not stored in the session). Returns the link id.
pub(super) fn add_link(s: &Session, doc: &Document, id: u64, sk: &mut Sketch, kind: LinkKind, src: LinkSource) -> Result<String> {
add_link_unless_present(s, doc, id, sk, kind, src, false).map(|l| l.unwrap_or_default())
+17 -5
View File
@@ -794,14 +794,26 @@ pub fn commands(app: &SolveApp, k: &Mod, inputs: &[SelInput], extra: &Map<String
if entities.is_empty() {
return Err("Select the sketch curves or points to mirror first".into());
}
// The AXES mask also takes an origin axis, which is not a curve of this sketch and
// cannot be a mirror line.
let line = match items(inputs, 1).first() {
Some(Sel::SketchCurve { id, .. }) => id.clone(),
Some(_) => return Err("The mirror line must be a straight curve of this sketch, not an origin axis".into()),
Some(Sel::SketchCurve { id, .. }) => json!(id),
Some(sel @ Sel::Axis { name }) if matches!(name.as_str(), "X" | "Y" | "Z") => {
if let Some(axis) = crate::tools::sketch_axis_of(app, name) {
json!(axis)
} else {
let (origin, dir) = crate::dialogs::axis_of(app, sel).ok_or("Select an origin axis")?;
let st = app.session.world_state();
let plane =
st.sketch(app.session.active_sketch.ok_or("No sketch is being edited")?).ok_or("The sketch no longer exists")?.plane;
if plane.normal().dot(dir).abs() > 1e-9 || plane.normal().dot(origin - plane.origin).abs() > 1e-6 {
return Err("The origin axis must lie in the sketch plane".into());
}
json!({"axis":name})
}
}
Some(_) => return Err("The mirror line must be a straight curve of this sketch or an origin axis in its plane".into()),
None => return Err("Select the mirror line".into()),
};
if entities.contains(&line) {
if line.as_str().is_some_and(|line| entities.iter().any(|entity| entity == line)) {
return Err("The mirror line cannot also be mirrored".into());
}
("sketch.mirror", json!({"entities": entities, "line": line}))
+46 -1
View File
@@ -230,7 +230,7 @@ fn a_half_filled_window_is_an_error_instead_of_a_command() {
// The AXES mask also takes an origin axis, which is no curve of this sketch.
let mut origin_axis = mirror_inputs();
origin_axis[0].items = vec![Sel::SketchCurve { id: ids[1].clone(), sketch: None }];
origin_axis[1].items = vec![Sel::Axis { name: "Y".into() }];
origin_axis[1].items = vec![Sel::Axis { name: "Z".into() }];
assert!(commands(&h.app, &Mod::Mirror, &origin_axis, &serde_json::Map::new()).is_err());
// The line itself must not be in the entities: the old click flow could not express that
// either, and the engine silently dropped it.
@@ -898,3 +898,48 @@ fn circular_quantity_keeps_its_expression_when_reopened_and_follows_parameter_ch
let sid = h.app.session.active_sketch.unwrap();
assert_eq!(h.app.session.world_state().sketch(sid).unwrap().sketch.curves.len(), 7);
}
#[test]
fn mirror_origin_axis_picks_use_the_same_reference_as_symmetry() {
for (plane, name, expected) in [("XY", "X", "x"), ("XY", "Y", "y"), ("XZ", "Z", "y"), ("YZ", "Y", "x")] {
let mut h = Harness::new();
h.app.run("sketch.create", json!({"plane":plane})).unwrap();
h.app.run("sketch.line", json!({"points":[[10,3],[15,8]],"ids":["source"]})).unwrap();
h.step(&json!({"start":"sketch.mirror"})).unwrap();
let d = h.app.dialog.as_mut().unwrap();
d.inputs[0].items = vec![Sel::SketchCurve { id: "source".into(), sketch: None }];
h.settle();
h.step(&json!({"click":{"handle":"dialog:Mirror line"}})).unwrap();
let on_axis = match name {
"X" => [10, 0, 0],
"Y" => [0, 10, 0],
_ => [0, 0, 10],
};
h.step(&json!({"click":{"world":on_axis}})).unwrap();
assert_eq!(h.app.dialog.as_ref().unwrap().inputs[1].items, vec![Sel::Axis { name: name.into() }]);
if plane == "XY" && name == "Y" {
h.step(&json!({"shot":"mirror-origin-y-before"})).unwrap();
}
let cmds = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap();
assert_eq!(cmds[0].1["line"], expected);
h.frames(2);
h.step(&json!({"key":"Enter"})).unwrap();
assert!(h.app.dialog.is_none(), "{:?}", h.app.status);
if plane == "XY" && name == "Y" {
h.step(&json!({"shot":"mirror-origin-y-after"})).unwrap();
}
let st = h.app.session.model.state();
let sk = &st.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch;
assert!(sk.sketch_axis_curve(expected).is_some());
assert_eq!(sk.constraints.iter().filter(|c| matches!(c.kind, solidcraft_engine::sketch::ConstraintKind::Symmetric { .. })).count(), 2);
}
let mut h = Harness::new();
h.app.run("sketch.create", json!({"plane":{"origin":[0,5,0],"x_dir":[1,1,0],"y_dir":[-1,1,0]}})).unwrap();
h.app.run("sketch.line", json!({"points":[[10,3],[15,8]],"ids":["source"]})).unwrap();
let mut inputs = mirror_inputs();
inputs[0].items = vec![Sel::SketchCurve { id: "source".into(), sketch: None }];
inputs[1].items = vec![Sel::Axis { name: "Y".into() }];
let cmds = commands(&h.app, &Mod::Mirror, &inputs, &serde_json::Map::new()).unwrap();
assert_eq!(cmds[0].1["line"], json!({"axis":"Y"}));
h.app.run(&cmds[0].0, cmds[0].1.clone()).unwrap();
}
+1 -1
View File
@@ -749,7 +749,7 @@ pub(crate) fn projection_preselection(selection: &[solidcraft_engine::Sel]) -> O
/// `x` or `y` when the origin axis `name` is the active sketch's own x or y axis: along it, and
/// through the sketch's origin.
fn sketch_axis_of(app: &SolveApp, name: &str) -> Option<&'static str> {
pub(crate) fn sketch_axis_of(app: &SolveApp, name: &str) -> Option<&'static str> {
use solidcraft_engine::geom::Vec3;
let dir = match name {
"X" => Vec3::X,