Align: move bodies by frames that follow sketch and model geometry (#6257) (#7123)

* claim: #6257

* Align: move bodies by frames that follow sketch and model geometry (#6257)

solid.align takes from_frame and to_frame: a joint origin on the model
(a face's or round end's centre, an edge's middle, a corner, found again
by name) or a sketch point or a sketch circle's, arc's or ellipse's
centre. Both are resolved on every evaluation, so the bodies follow
their target when it changes. An optional angle turns the bodies about
the target's direction after the move.

The Align dialog takes sketch points and curves as From and To, offers
the Joint Origin snap and an Angle row.

* Align frames: box the joint origin (clippy large_enum_variant)

* Align frames: every moved body on the frame's component, placed once

* Align frames: a sketch id's length in characters

* Align frames: the dialog test's sketch curve hit carries its point

* Align frames: the dialog test takes Vec2 from solidcore-record

---------

Co-authored-by: MateuszSychXpl <151755914+MateuszSychXpl@users.noreply.github.com>
This commit is contained in:
Mateusz Sych
2026-11-03 15:47:52 +00:00
committed by GitHub
parent a8bc6b2945
commit bfb32cd6e1
12 changed files with 388 additions and 30 deletions
+87 -14
View File
@@ -2,8 +2,8 @@
use serde_json::Value;
use solidcore_record::Vec3;
use solidcraft_doc::FeatureKind;
use solidcraft_doc::expr::Kind;
use solidcraft_doc::{AlignFrame, FeatureKind};
use solidcraft_doc::{BodyName, SketchId};
use solidcraft_doc::{Dir, FacePick, Position};
use solidcraft_geom::prelude::*;
@@ -44,7 +44,7 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("solid.align", "Align", align)
.at("SOLID", "MODIFY")
.icon("align")
.params("bodies: [names]; from: [x,y,z] | \"origin\" | {snap: vertex|edge_mid|face_center|circle_center, at: [x,y,z]} | from_face: [x,y,z] | from_plane: XY|XZ|YZ|construction or offset plane name or id|{origin, normal}; to: (the same) | to_face: [x,y,z] | to_plane: (a plane as from_plane; the point or face goes onto it along its normal, and the plane may move later: the bodies follow); faces and planes also turn to meet; flip?: bool; axes?: [x, y, z] (point-to-point only: which world axes the offset moves along; default all three, at least one true)"),
.params("bodies: [names]; from: [x,y,z] | \"origin\" | {snap: vertex|edge_mid|face_center|circle_center, at: [x,y,z]} | from_face: [x,y,z] | from_plane: XY|XZ|YZ|construction or offset plane name or id|{origin, normal}; to: (the same) | to_face: [x,y,z] | to_plane: (a plane as from_plane; the point or face goes onto it along its normal, and the plane may move later: the bodies follow); from_frame / to_frame: a frame found again whenever the design changes, so the bodies follow it, in place of that side's point, face or plane: a joint origin as joint.create takes one ({face|circle|edge|point: [x,y,z]}, a face's name, a named joint origin) or {sketch, point|curve} (a sketch point, or a circle's, arc's or ellipse's centre, z along the sketch's normal), on the bodies' own component; faces, planes and frames also turn to meet; flip?: bool; axes?: [x, y, z] (point-to-point only: which world axes the offset moves along; default all three, at least one true); angle?: expr (a turn about the target's direction after the move)"),
CommandSpec::new("solid.remove", "Remove", remove).at("SOLID", "MODIFY").icon("delete").params("bodies: [names] (removed from here on in the timeline)"),
];
@@ -444,12 +444,26 @@ fn align(s: &mut Session, p: &Value) -> Result<Value> {
p.get(key).map(|_| super::features::plane_param(s, p.get(key), cmd)).transpose()
};
let (from_plane, to_plane) = (plane(s, "from_plane")?, plane(s, "to_plane")?);
let world_pick = |s: &Session, pk: &str, fk: &str, plane: &Option<solidcraft_doc::PlaneRef>| -> Result<(Vec3, Option<Vec3>)> {
if plane.is_some() {
// Or a frame (#6257), found again when the feature is evaluated.
let (from_frame, to_frame) = (align_frame(s, p, "from", &bodies)?, align_frame(s, p, "to", &bodies)?);
// A target on the bodies that move would move away with them: it must be found the same
// without them.
if let Some(fr @ AlignFrame::Origin { .. }) = &to_frame {
let st = s.model.state();
let mut rest = (*st).clone();
rest.bodies.retain(|b| !bodies.contains(&b.name));
let same = |(a, n): (Vec3, Vec3), (b, m): (Vec3, Vec3)| a.dist(b) <= 1e-9 * (1.0 + a.len()) && n.dot(m) > 1.0 - 1e-12;
if !matches!((fr.resolve(&s.doc, &st), fr.resolve(&s.doc, &rest)), (Ok(a), Ok(b)) if same(a, b)) {
return Err(bad(cmd, "`to_frame` is on a body that moves: pick the target on another body or on a sketch"));
}
}
// Worked out from the plane or the frame when the feature is evaluated.
let held = |plane: &Option<solidcraft_doc::PlaneRef>, frame: &Option<AlignFrame>| plane.is_some() || frame.is_some();
let world_pick = |s: &Session, pk: &str, fk: &str, held: bool| -> Result<(Vec3, Option<Vec3>)> {
if held {
if p.get(pk).is_some() || p.get(fk).is_some() {
return Err(bad(cmd, format!("give `{pk}_plane` or `{pk}`/`{fk}`, not both")));
}
// Worked out from the plane when the feature is evaluated.
return Ok((Vec3::ZERO, None));
}
if let Some(fp) = p.get(fk).and_then(vec3) {
@@ -471,24 +485,36 @@ fn align(s: &mut Session, p: &Value) -> Result<Value> {
.map(|v| (v, None))
.ok_or_else(|| bad(cmd, format!("give `{pk}`, `{fk}` or `{pk}_plane` ([x, y, z], \"origin\", or a plane)")))
};
let pick = |s: &Session, pk: &str, fk: &str, plane: &Option<solidcraft_doc::PlaneRef>| -> Result<(Vec3, Option<Vec3>)> {
let (at, n) = world_pick(s, pk, fk, plane)?;
if plane.is_some() {
let pick = |s: &Session, pk: &str, fk: &str, held: bool| -> Result<(Vec3, Option<Vec3>)> {
let (at, n) = world_pick(s, pk, fk, held)?;
if held {
return Ok((at, n));
}
Ok((solidcraft_doc::apply_point(&inverse, at), n.and_then(|n| solidcraft_doc::apply_vector(&inverse, n).normalized())))
};
let (from, from_normal) = pick(s, "from", "from_face", &from_plane)?;
let (to, to_normal) = pick(s, "to", "to_face", &to_plane)?;
// Faces turn only to meet another face or a plane; a plane's normal is read when evaluated.
let (from, from_normal) = pick(s, "from", "from_face", held(&from_plane, &from_frame))?;
let (to, to_normal) = pick(s, "to", "to_face", held(&to_plane, &to_frame))?;
// A turn about the target's direction after the move.
let angle = expr(p, "angle");
if let Some(a) = &angle {
check_expr(s, a, Kind::Angle, cmd, "angle")?;
if to_normal.is_none() && !held(&to_plane, &to_frame) {
return Err(bad(cmd, "`angle` turns about the target's direction: give `to_frame`, `to_face` or `to_plane`"));
}
}
// Faces turn only to meet another face, a plane or a frame; a plane's normal and a frame's z
// are read when evaluated. A target face's normal is also the axis of an `angle`.
let (from_normal, to_normal) = match (from_normal, to_normal) {
(Some(a), Some(b)) => (Some(a), Some(b)),
(a, b) if from_plane.is_some() || to_plane.is_some() => (a, b),
(a, b) if held(&from_plane, &from_frame) || held(&to_plane, &to_frame) || angle.is_some() => (a, b),
_ => (None, None),
};
let axes = axes_param(p, cmd)?;
if axes.is_some() && (from_plane.is_some() || to_plane.is_some() || from_normal.is_some() || to_normal.is_some()) {
return Err(bad(cmd, "`axes` applies to point-to-point alignment: leave out `from_face`, `to_face`, `from_plane` and `to_plane`"));
if axes.is_some() && (held(&from_plane, &from_frame) || held(&to_plane, &to_frame) || from_normal.is_some() || to_normal.is_some()) {
return Err(bad(
cmd,
"`axes` applies to point-to-point alignment: leave out `from_face`, `to_face`, `from_plane`, `to_plane`, `from_frame` and `to_frame`",
));
}
// The directions are stored in the same frame as `from`/`to` (the first moved body's frame).
let axes = axes.map(|mask| {
@@ -512,10 +538,57 @@ fn align(s: &mut Session, p: &Value) -> Result<Value> {
from_plane,
to_plane,
axes,
from_frame,
to_frame,
angle,
},
)
}
/// The longest sketch point or curve id an Align frame takes.
const MAX_SKETCH_ID: usize = 256;
/// An Align side's frame (#6257), `<key>_frame`: a joint origin as `joint.create` takes one, or a
/// sketch point or the centre of a sketch circle, arc or ellipse (`{sketch, point|curve}`), on the
/// moved bodies' component (all of them on one, placed once). It takes the place of `<key>`,
/// `<key>_face` and `<key>_plane`, and is checked to resolve now.
fn align_frame(s: &Session, p: &Value, key: &str, bodies: &[String]) -> Result<Option<AlignFrame>> {
let cmd = "solid.align";
let fk = format!("{key}_frame");
let Some(v) = p.get(&fk).filter(|v| !v.is_null()) else { return Ok(None) };
if let Some(other) = [key.to_string(), format!("{key}_face"), format!("{key}_plane")].into_iter().find(|k| p.get(k).is_some()) {
return Err(bad(cmd, format!("give `{fk}` or `{other}`, not both")));
}
let st = s.model.state();
let (frame, on) = match v.get("sketch") {
Some(sk) => {
let sketch = super::features::sketch_id(s, Some(sk), cmd, &fk)?;
let id = |k: &str| str_(v, k).filter(|n| !n.is_empty() && n.chars().count() <= MAX_SKETCH_ID).map(str::to_string);
let frame = match (id("point"), id("curve")) {
(Some(point), None) => AlignFrame::SketchPoint { sketch: SketchId(sketch), point },
(None, Some(curve)) => AlignFrame::SketchCurve { sketch: SketchId(sketch), curve },
_ => return Err(bad(cmd, format!("`{fk}`: a sketch frame takes `point` or `curve` (an id of 1 to {MAX_SKETCH_ID} characters)"))),
};
(frame, s.doc.feature(sketch).map_or(0, |f| f.component))
}
None => {
let origin = super::joints::origin_param(s, Some(v), cmd)?;
let on = super::joints::component_of(s, origin.occurrence);
(AlignFrame::Origin { origin: Box::new(origin) }, on)
}
};
// The move is worked out in that component's coordinates: every body must be in it, and a
// component placed twice would not say which placement the picks were made in.
if bodies.iter().any(|b| st.body(b).map_or(0, |b| s.doc.model_body_component(b)) != on) {
return Err(bad(cmd, format!("not supported yet: `{fk}` on another component than the bodies")));
}
if on != 0 && s.doc.occurrences.iter().filter(|o| o.component == on).count() != 1 {
return Err(bad(cmd, format!("not supported yet: `{fk}` on a component placed more than once")));
}
frame.resolve(&s.doc, &st).map_err(|e| bad(cmd, format!("`{fk}`: {e}")))?;
Ok(Some(frame))
}
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "solid.remove";
let bodies = string_list(cmd, p, "bodies")?;
@@ -951,6 +951,120 @@ fn align_takes_planes_and_the_origin() {
assert!(s.execute("solid.align", &json!({"bodies": ["C"], "from": [0, 0, 0], "to_plane": "Nowhere"})).is_err());
}
/// The bounding box of body `name`: min and max.
fn bounds(s: &mut Session, name: &str) -> ([f64; 3], [f64; 3]) {
let m = measure(s);
let b = m["bodies"].as_array().and_then(|bs| bs.iter().find(|b| b["name"] == name)).cloned().unwrap_or_else(|| panic!("no body {name}: {m}"));
let g = |k: &str, i: usize| b["bbox"][k][i].as_f64().unwrap_or(f64::NAN);
([g("min", 0), g("min", 1), g("min", 2)], [g("max", 0), g("max", 1), g("max", 2)])
}
fn assert_bounds(s: &mut Session, name: &str, lo: [f64; 3], hi: [f64; 3]) {
let (a, b) = bounds(s, name);
let near = |x: [f64; 3], y: [f64; 3]| x.iter().zip(y).all(|(p, q)| (p - q).abs() < 1e-6);
assert!(near(a, lo) && near(b, hi), "{name}: {a:?}..{b:?}, want {lo:?}..{hi:?}");
}
/// Align by frames (#6257): a body's face centre lands on a sketch circle's centre and follows it
/// when the parameter that places the circle changes; a turn about the target's z, a sketch point
/// as the target with a flip, and a frame on the body that follows the body's own edits.
#[test]
fn align_by_frames_follows_its_target() {
// B is 10 x 20 x 10 at (50, 0, 20); sketch S on XY has a circle at (X, 5) and a point at (20, X).
let target = || {
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name": "X", "expression": "0 mm"}));
run(&mut s, "parameters.add", json!({"name": "H", "expression": "10 mm"}));
run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": "H", "corner": [50, 0, 20], "body_name": "B"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
run(&mut s, "sketch.circle.center", json!({"center": ["X", 5], "radius": 3, "id": "ring"}));
run(&mut s, "sketch.point", json!({"point": [20, "X"], "id": "p"}));
run(&mut s, "sketch.line", json!({"points": [[0, 30], [10, 30]], "ids": ["edge"]}));
run(&mut s, "sketch.finish", json!({}));
s
};
let bottom = json!({"face": [55, 10, 20]});
let ring = json!({"sketch": "S", "curve": "ring"});
// The bottom face (z down) onto the circle (z up): no turn, B sits on XY centred on it.
let mut s = target();
run(&mut s, "solid.align", json!({"bodies": ["B"], "from_frame": bottom, "to_frame": ring}));
assert_bounds(&mut s, "B", [-5., -5., 0.], [5., 15., 10.]);
// The circle moves: B follows it, and still does in the saved design.
run(&mut s, "parameters.change", json!({"name": "X", "expression": "30 mm"}));
assert_bounds(&mut s, "B", [25., -5., 0.], [35., 15., 10.]);
let mut r = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());
assert_bounds(&mut r, "B", [25., -5., 0.], [35., 15., 10.]);
// A quarter turn about the circle's z through its centre.
let mut s = target();
run(&mut s, "solid.align", json!({"bodies": ["B"], "from_frame": bottom, "to_frame": ring, "angle": 90}));
assert_bounds(&mut s, "B", [-10., 0., 0.], [10., 10., 10.]);
// The top face onto the sketch point, flipped (z along z): B hangs under XY. The frame on B
// follows B's own height.
let mut s = target();
run(
&mut s,
"solid.align",
json!({"bodies": ["B"], "from_frame": {"face": [55, 10, 30]}, "to_frame": {"sketch": "S", "point": "p"}, "flip": true}),
);
assert_bounds(&mut s, "B", [15., -10., -10.], [25., 10., 0.]);
run(&mut s, "parameters.change", json!({"name": "H", "expression": "15 mm"}));
assert_bounds(&mut s, "B", [15., -10., -15.], [25., 10., 0.]);
// A face pick with an angle about the target face's normal; a sketch frame onto a fixed point.
let mut s = target();
run(&mut s, "solid.align", json!({"bodies": ["B"], "from": [50, 0, 20], "to_face": [55, 10, 30], "angle": 0}));
run(&mut s, "solid.align", json!({"bodies": ["B"], "from_frame": {"sketch": "S", "point": "p"}, "to": [20, 0, 5]}));
// Refused: a side given twice, an angle with no target direction, a frame on the bodies that
// move, unknown or wrong sketch geometry, ids out of range, a degenerate frame.
let mut s = target();
for bad in [
json!({"from": [0, 0, 0], "from_frame": bottom, "to_frame": ring}),
json!({"from_frame": bottom, "to_frame": ring, "to_plane": "XY"}),
json!({"from_frame": bottom, "to": [0, 0, 0], "angle": 30}),
json!({"from_frame": bottom, "to_frame": ring, "angle": "3 mm"}),
json!({"from_frame": bottom, "to_frame": {"face": [55, 10, 30]}}),
json!({"from_frame": bottom, "to_frame": {"sketch": "Nope", "point": "p"}}),
json!({"from_frame": bottom, "to_frame": {"sketch": "S", "point": "zz"}}),
json!({"from_frame": bottom, "to_frame": {"sketch": "S", "curve": "edge"}}),
json!({"from_frame": bottom, "to_frame": {"sketch": "S", "point": "p", "curve": "ring"}}),
json!({"from_frame": bottom, "to_frame": {"sketch": "S", "point": ""}}),
json!({"from_frame": bottom, "to_frame": {"sketch": "S", "point": "q".repeat(300)}}),
json!({"from_frame": bottom, "to_frame": {"frame": {"origin": [0, 0, 0], "z": [0, 0, 0]}}}),
json!({"from_frame": {"face": "no such face"}, "to_frame": ring}),
] {
let mut p = bad.clone();
p["bodies"] = json!(["B"]);
assert!(s.execute("solid.align", &p).is_err(), "{bad}");
}
// One frame does not move bodies of two components.
run(&mut s, "component.create", json!({"name": "Part"}));
run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [80, 0, 0], "body_name": "P"}));
run(&mut s, "component.activate", json!({"component": "root"}));
assert!(s.execute("solid.align", &json!({"bodies": ["B", "P"], "from_frame": bottom, "to_frame": ring})).is_err());
assert!(!s.doc.features.iter().any(|f| matches!(f.kind, solidcraft_doc::FeatureKind::Align { .. })), "nothing refused was added");
// A design file whose frame no longer resolves (here a degenerate one) fails the feature
// with a message; it never panics.
let mut s = target();
run(&mut s, "solid.align", json!({"bodies": ["B"], "from_frame": bottom, "to_frame": ring}));
let mut v: Value = serde_json::from_str(&s.doc.to_json()).unwrap();
fn spoil(v: &mut Value) {
match v {
Value::Object(o) if o.get("type").and_then(Value::as_str) == Some("align") => {
o.insert(
"to_frame".into(),
json!({"type": "origin", "origin": {"occurrence": 0, "snap": {"type": "frame", "origin": [0, 0, 0], "z": [0, 0, 0]}}}),
);
}
Value::Object(o) => o.values_mut().for_each(spoil),
Value::Array(a) => a.iter_mut().for_each(spoil),
_ => {}
}
}
spoil(&mut v);
let mut r = Session::new(solidcraft_doc::Document::from_json(&v.to_string()).unwrap());
measure(&mut r);
assert!(r.model.results.iter().any(|x| x.error.as_deref().is_some_and(|e| e.contains("degenerate"))), "the Align reports its frame");
}
#[test]
fn coil_and_loft_to_a_point() {
use std::f64::consts::{PI, TAU};
+1 -1
View File
@@ -498,7 +498,7 @@ fn same_frame(s: &Session, o: &JointOrigin, at: Vec3, z: Vec3) -> bool {
const MAX_FACE_NAME: usize = 16_384;
/// The component an occurrence places (0 for the root, or an unknown occurrence).
fn component_of(s: &Session, occurrence: u64) -> u64 {
pub(crate) fn component_of(s: &Session, occurrence: u64) -> u64 {
if occurrence == 0 { 0 } else { s.doc.occurrences.iter().find(|o| o.id == occurrence).map_or(0, |o| o.component) }
}