diff --git a/crates/doc/src/clipboard.rs b/crates/doc/src/clipboard.rs index 3d8311181..f2f1e7526 100644 --- a/crates/doc/src/clipboard.rs +++ b/crates/doc/src/clipboard.rs @@ -291,6 +291,17 @@ impl crate::Feature { K::Revolve { axis: crate::AxisRef::Model { geo }, .. } | K::SurfaceRevolve { axis: crate::AxisRef::Model { geo }, .. } | K::Pattern { pattern: crate::PatternKind::Circular { axis_ref: Some(geo), .. }, .. } => remap_geo(geo, ids, bodies, 0)?, + // An Align frame's joint origin finds its faces and edges by name, as the feature's + // own face names are found. + K::Align { from_frame, to_frame, .. } => { + for fr in [from_frame, to_frame].into_iter().flatten() { + if let crate::AlignFrame::Origin { origin } = fr { + for n in origin.snap.face_names_mut() { + *n = remap_topology(n, ids, bodies); + } + } + } + } _ => {} } Ok(()) diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 5a4572f7f..0e55cdf3c 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -610,6 +610,51 @@ impl<'de> Deserialize<'de> for FlangeEdge { } } +/// One side of an Align by frames (#6257): an origin and a z direction, found again from the +/// geometry each time the design is evaluated, so the bodies follow it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum AlignFrame { + /// A joint origin on the model (its component's coordinates): its origin and z. + Origin { origin: Box }, + /// A sketch point; z along the sketch's normal. + SketchPoint { sketch: SketchId, point: String }, + /// The centre of a sketch circle, arc or ellipse; z along the sketch's normal. + SketchCurve { sketch: SketchId, curve: String }, +} + +impl AlignFrame { + /// The frame's origin and unit z in the model state `st` (its component's coordinates). + pub fn resolve(&self, doc: &Document, st: &crate::ModelState) -> Result<(Vec3, Vec3)> { + let sketch = |id: &SketchId| st.sketch(id.0).ok_or_else(|| DocError::Unknown(format!("sketch {id}"))); + let (o, z) = match self { + AlignFrame::Origin { origin } => { + let m = crate::joints::resolve_origin(doc, st, origin)?; + (Vec3::new(m[3][0], m[3][1], m[3][2]), Vec3::new(m[2][0], m[2][1], m[2][2])) + } + AlignFrame::SketchPoint { sketch: id, point } => { + let ss = sketch(id)?; + let q = ss.sketch.point_index(point).and_then(|i| ss.sketch.point(i)); + (ss.plane.to_world(q.ok_or_else(|| DocError::Unknown(format!("sketch point `{point}`")))?), ss.plane.normal()) + } + AlignFrame::SketchCurve { sketch: id, curve } => { + use solidcraft_sketch::CurveKind; + let ss = sketch(id)?; + let kind = ss.sketch.curve_index(curve).and_then(|i| ss.sketch.curves.get(i)).map(|c| &c.kind); + let centre = match kind.ok_or_else(|| DocError::Unknown(format!("sketch curve `{curve}`")))? { + CurveKind::Circle { c, .. } | CurveKind::Arc { c, .. } | CurveKind::Ellipse { c, .. } => ss.sketch.point(*c), + _ => return Err(DocError::Invalid(format!("sketch curve `{curve}` is not a circle, arc or ellipse"))), + }; + (ss.plane.to_world(centre.ok_or_else(|| DocError::Invalid(format!("sketch curve `{curve}` has no centre")))?), ss.plane.normal()) + } + }; + match z.normalized() { + Some(z) if o.is_finite() => Ok((o, z)), + _ => Err(DocError::Invalid("the frame has no finite origin and direction".into())), + } + } +} + /// Feature definitions. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] #[serde(tag = "type", rename_all = "snake_case")] @@ -1172,6 +1217,19 @@ pub enum FeatureKind { /// offset in full. #[serde(default, skip_serializing_if = "Option::is_none")] axes: Option>, + /// A frame on the bodies (#6257), found again on every evaluation: its origin and z are + /// the `from` point and normal. Replaces `from`, `from_normal` and `from_plane`. + #[serde(default, skip_serializing_if = "Option::is_none")] + from_frame: Option, + /// A frame the bodies move onto, found again on every evaluation, so they follow it when + /// it moves. Replaces `to`, `to_normal` and `to_plane`. + #[serde(default, skip_serializing_if = "Option::is_none")] + to_frame: Option, + /// A turn about the target's direction (its frame's z, face normal or plane normal), + /// through where `from` lands, after the move. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[walk(angle = "Angle")] + angle: Option, }, /// A helical coil: a circular or square section swept `turns` times about `axis`, rising /// `pitch` per turn, on a helix of `diameter` (the section's centre, or its inside or outside). diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rs index 4083078e8..4072380b9 100644 --- a/crates/doc/src/eval_more.rs +++ b/crates/doc/src/eval_more.rs @@ -89,17 +89,26 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, } Ok(()) } - FeatureKind::Align { bodies, from, to, from_normal, to_normal, flip, from_plane, to_plane, axes } => { + FeatureKind::Align { bodies, from, to, from_normal, to_normal, flip, from_plane, to_plane, axes, from_frame, to_frame, angle } => { // A plane on either side is worked out now, so the bodies follow it when it moves. let (mut from, mut from_normal) = (from.0, from_normal.and_then(|n| n.normalized())); if let Some(p) = from_plane { let pl = doc.resolve_plane_in(vals, p, 0, Some(&*st))?; (from, from_normal) = (pl.origin, Some(pl.normal())); } - let target = to_plane.as_ref().map(|p| doc.resolve_plane_in(vals, p, 0, Some(&*st))).transpose()?; - let (to, to_normal) = match &target { - Some(pl) => (pl.origin, Some(pl.normal())), - None => (to.0, to_normal.and_then(|n| n.normalized())), + // So is a frame (#6257): its origin and z, found again from the geometry. + if let Some(fr) = from_frame { + let (o, z) = fr.resolve(doc, st)?; + (from, from_normal) = (o, Some(z)); + } + let target = match to_frame { + Some(_) => None, + None => to_plane.as_ref().map(|p| doc.resolve_plane_in(vals, p, 0, Some(&*st))).transpose()?, + }; + let (to, to_normal) = match (to_frame, &target) { + (Some(fr), _) => fr.resolve(doc, st).map(|(o, z)| (o, Some(z)))?, + (None, Some(pl)) => (pl.origin, Some(pl.normal())), + (None, None) => (to.0, to_normal.and_then(|n| n.normalized())), }; let mut m = translation(Vec3::ZERO); if let (Some(a), Some(b)) = (from_normal, to_normal) { @@ -143,6 +152,19 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, m[3][0] += d.x; m[3][1] += d.y; m[3][2] += d.z; + // Then the turn about the target's direction, through where `from` landed. + if let Some(e) = angle { + let a = val(vals, e, Kind::Angle)?; + if !a.is_finite() { + return Err(DocError::Invalid("the Align angle is not a finite number".into())); + } + let n = to_normal.ok_or_else(|| { + DocError::Invalid("an Align angle turns about the target's direction: move onto a frame, a face or a plane".into()) + })?; + if a.abs() > 1e-12 { + m = crate::mat_mul(&rotation(apply_point(&m, from), n, a), &m); + } + } if bodies.is_empty() { return Err(DocError::Invalid("no bodies to align".into())); } diff --git a/crates/doc/src/format/pending/align-frames.rs b/crates/doc/src/format/pending/align-frames.rs new file mode 100644 index 000000000..e1793d1e3 --- /dev/null +++ b/crates/doc/src/format/pending/align-frames.rs @@ -0,0 +1,7 @@ +//! An Align feature (`FeatureKind::Align`) saves optional `from_frame` and `to_frame` (a joint +//! origin on the model, `{"type": "origin", "origin": {...}}`, or a sketch point or the centre of a +//! sketch circle, arc or ellipse, `{"type": "sketch_point", "sketch": id, "point": ""}` / +//! `{"type": "sketch_curve", "sketch": id, "curve": ""}`), found again from the geometry on +//! every evaluation so the bodies follow them, and an optional `angle` expression (a turn about the +//! target's direction). Older designs have none of them and evaluate as before. The last release +//! refuses a design with this change by its newer format number. diff --git a/crates/doc/src/walk.rs b/crates/doc/src/walk.rs index 90a114681..22564ac5b 100644 --- a/crates/doc/src/walk.rs +++ b/crates/doc/src/walk.rs @@ -67,6 +67,8 @@ impl Walk for crate::thread_forms::ThreadForm {} impl Walk for crate::thread_forms::ThreadHand {} impl Walk for crate::thread_forms::ThreadTip {} impl Walk for crate::thread_forms::SteepFlank {} +// An Align frame's joint origin: picks in its component's coordinates, found by their names. +impl Walk for Box {} /// A reference walks itself: a sketch, a feature or a body. macro_rules! reference { diff --git a/crates/engine/src/cmd/features_more.rs b/crates/engine/src/cmd/features_more.rs index 3c5c991f2..b23dae96c 100644 --- a/crates/engine/src/cmd/features_more.rs +++ b/crates/engine/src/cmd/features_more.rs @@ -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 { 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| -> Result<(Vec3, Option)> { - 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, frame: &Option| plane.is_some() || frame.is_some(); + let world_pick = |s: &Session, pk: &str, fk: &str, held: bool| -> Result<(Vec3, Option)> { + 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 { .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| -> Result<(Vec3, Option)> { - 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)> { + 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 { 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), `_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 ``, +/// `_face` and `_plane`, and is checked to resolve now. +fn align_frame(s: &Session, p: &Value, key: &str, bodies: &[String]) -> Result> { + 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 { let cmd = "solid.remove"; let bodies = string_list(cmd, p, "bodies")?; diff --git a/crates/engine/src/cmd/features_more_tests.rs b/crates/engine/src/cmd/features_more_tests.rs index 2a8683aec..83ea9ad97 100644 --- a/crates/engine/src/cmd/features_more_tests.rs +++ b/crates/engine/src/cmd/features_more_tests.rs @@ -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}; diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index 59515de81..ee8a3db87 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -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) } } diff --git a/crates/ui-egui/src/browser_card_tests.rs b/crates/ui-egui/src/browser_card_tests.rs index bc697ae32..924a2792f 100644 --- a/crates/ui-egui/src/browser_card_tests.rs +++ b/crates/ui-egui/src/browser_card_tests.rs @@ -770,7 +770,7 @@ fn browser_occurrence_clicks_fill_align_components_input() { h.app.start("solid.align"); { let d = h.app.dialog.as_mut().unwrap(); - d.kind = crate::dialogs::Kind::Align { flip: false, components: true, axes: [true; 3] }; + d.kind = crate::dialogs::Kind::Align { flip: false, components: true, axes: [true; 3], angle: String::new() }; d.inputs[0].label = "Components"; d.active = 0; } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c361bbdaf..a18faa8f5 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -102,6 +102,9 @@ const PROJECT_GEOMETRY: Accept = /// What Intersect cuts with the sketch plane, picked one by one: faces, model edges and the /// curves of other sketches (#10484); an edge or a sketch line gives the points where it crosses. const INTERSECT_GEOMETRY: Accept = EDGES | FACES | selection::SKETCH_LINES; +/// What Align's From and To pick: model geometry, planes and the origin, and sketch points and +/// circles (a frame the bodies follow, #6257). +const ALIGN_PICKS: Accept = FACES | EDGES | selection::VERTICES | PLANES | selection::ORIGIN | selection::POINTS | CURVES; const HOLE_TYPES: [&str; 3] = ["simple", "counterbore", "countersink"]; const HOLE_LABELS: [&str; 3] = ["Simple", "Counterbore", "Countersink"]; @@ -288,6 +291,8 @@ crate::dialog_descriptor::dialog_descriptors! { components: bool, /// Point-to-point: which of the world X, Y and Z axes take the offset. axes: [bool; 3], + /// A turn about the target's direction after the move (blank: none). + angle: String, }, /// Remove bodies from here on in the timeline. Remove, @@ -910,12 +915,14 @@ impl Dialog { } "solid.align" => { let components = s.selection.iter().any(|x| matches!(x, Sel::Occurrence { .. })); + // Bodies also take sketch points and circles: a frame the bodies follow (#6257). + let picks = if components { FACES | EDGES | selection::VERTICES | PLANES | selection::ORIGIN } else { ALIGN_PICKS }; Dialog::new( - Kind::Align { flip: false, components, axes: [true; 3] }, + Kind::Align { flip: false, components, axes: [true; 3], angle: String::new() }, vec![ SelInput::new(if components { "Components" } else { "Bodies" }, BODIES, true), - SelInput::new("From", FACES | EDGES | selection::VERTICES | PLANES | selection::ORIGIN, false), - SelInput::new("To", FACES | EDGES | selection::VERTICES | PLANES | selection::ORIGIN, false), + SelInput::new("From", picks, false), + SelInput::new("To", picks, false), ], ) } @@ -5087,7 +5094,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S need(0, "faces")?; ("face.delete", json!({"faces": face_points(0)})) } - Kind::Align { flip, components, axes } => { + Kind::Align { flip, components, axes, angle } => { need(0, if *components { "components" } else { "bodies" })?; need(1, "what to move from")?; need(2, "where to move it to")?; @@ -5107,6 +5114,17 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S for (i, key) in [(1, "from"), (2, "to")] { let snap = d.extra.get(&format!("{key}_snap")).and_then(Value::as_str).unwrap_or("picked"); match (sels(d, i).first(), snap) { + // A sketch point or circle is a frame whatever the snap: the bodies follow it + // when it moves (#6257). + (Some(sel @ (Sel::SketchPoint { .. } | Sel::SketchCurve { .. })), _) if !*components => { + p[format!("{key}_frame")] = construct_ref(app, sel)? + } + // The joint origin the Joint dialog makes of the pick, found again by name. + (Some(sel @ (Sel::Face { .. } | Sel::Edge { .. } | Sel::Vertex { .. })), "origin") + if !*components && !matches!(sel, Sel::Vertex { body, .. } if body.is_empty()) => + { + p[format!("{key}_frame")] = crate::dialogs_assembly::snap_of(s, sel).ok_or("this pick has no joint origin")?.param; + } (Some(Sel::Face { point, .. }), "center") => p[key] = json!({"snap": "face_center", "at": pt(*point)}), (Some(Sel::Face { point, .. } | Sel::Edge { point, .. }), "circle") => { p[key] = json!({"snap": "circle_center", "at": pt(*point)}) @@ -5118,9 +5136,13 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S (Some(Sel::Vertex { point, .. }), _) => p[key] = pt(*point), // A plane stays a plane, so the bodies follow it when it moves. (Some(Sel::Plane { name }), _) => p[format!("{key}_plane")] = json!(name), - _ => return Err("pick faces, edges, vertices or planes".into()), + _ => return Err("pick faces, edges, vertices, planes or sketch points".into()), } } + // Frames and a turn are the bodies' (#6257); components align without them. + if !*components && !angle.trim().is_empty() { + p["angle"] = json!(angle.trim()); + } (if *components { "occurrence.align" } else { "solid.align" }, p) } Kind::Remove => { diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index 6b27fec97..640e97815 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -896,17 +896,25 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo }); ui.add(egui::Label::new(crate::i18n::tr("ui.emboss_wrap_note")).wrap()); } - Kind::Align { flip, components, axes: [ax, ay, az] } => { + Kind::Align { flip, components, axes: [ax, ay, az], angle } => { // Where on the picked face or edge to snap: as picked (a face turns to meet - // the other, an edge at its middle), its centre, or a round one's centre. + // the other, an edge at its middle), its center, a round one's center, or, for bodies, + // the joint origin the Joint dialog makes of it (found again as the part changes, #6257). + let snaps: &[(&str, &str)] = if *components { + &[("As Picked", "picked"), ("Center", "center"), ("Circle Center", "circle")] + } else { + &[("As Picked", "picked"), ("Center", "center"), ("Circle Center", "circle"), ("Joint Origin", "origin")] + }; for (label, key) in [("From Snap", "from_snap"), ("To Snap", "to_snap")] { form_row(ui, label, |ui| { - extra_choice(ui, &mut d.extra, key, key, &[("As Picked", "picked"), ("Center", "center"), ("Circle Center", "circle")]); + extra_choice(ui, &mut d.extra, key, key, snaps); }); } if *components { ui_kit::options(ui, "feature_options", &mut [("Flip", flip)]); } else { + // A turn about the target's direction after the move (#6257). + enter |= hint_row(ui, "Angle", angle, tr("none")); ui_kit::options(ui, "feature_options", &mut [("Flip", flip), ("X", ax), ("Y", ay), ("Z", az)]); } // A part inside a subassembly placed more than once sits where that shared diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index c64f9d29a..3762dbfd5 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -1979,6 +1979,47 @@ fn align_snaps_to_centres_and_edge_middles() { assert_eq!(p["to"]["snap"], json!("edge_mid")); } +/// Align by frames (#6257): a sketch circle or point picked as To is a frame whatever the snap, a +/// face with the Joint Origin snap is the joint origin the Joint dialog makes of it, and Angle is +/// sent when given; As Picked builds what it built before. +#[test] +fn align_takes_sketch_frames_and_joint_origins() { + let mut app = boxed(); + app.run("sketch.create", json!({"plane": "XY", "name": "S"})).unwrap(); + app.run("sketch.circle.center", json!({"center": [60, 5], "radius": 3, "id": "ring"})).unwrap(); + app.run("sketch.point", json!({"point": [70, 5], "id": "p"})).unwrap(); + app.run("sketch.finish", json!({})).unwrap(); + let sketch = app.session.doc.find_feature("S").unwrap().id; + let mut d = start(&mut app, vec![], "solid.align"); + d.inputs[0].items = vec![Sel::Body { name: "Body1".into() }]; + let bottom = face(&app, Vec3::new(20.0, 15.0, 0.0)); + d.inputs[1].items = vec![bottom.clone()]; + d.active = 2; + let ring = d + .candidate(&app.session, &crate::viewport::Hit::SketchCurve { sketch, id: "ring".into(), straight: false, point: Vec3::new(63.0, 5.0, 0.0) }); + assert!(ring.is_some(), "the To input takes a sketch circle"); + d.pick(&app.session, ring.unwrap()); + let p = apply_commands(&app, &d).unwrap().remove(0).1; + assert_eq!(p["to_frame"], json!({"sketch": sketch, "curve": "ring"})); + assert!(p["from_face"].is_array() && p.get("from_frame").is_none() && p.get("angle").is_none(), "{p}"); + // The Joint Origin snap, and a turn. + d.extra.insert("from_snap".into(), json!("origin")); + if let Kind::Align { angle, .. } = &mut d.kind { + *angle = "45".into(); + } + let p = apply_commands(&app, &d).unwrap().remove(0).1; + assert_eq!(p["from_frame"], crate::dialogs_assembly::snap_of(&app.session, &bottom).unwrap().param); + assert!(p.get("from_face").is_none() && p["angle"] == json!("45"), "{p}"); + // A sketch point is a frame too, and the command runs. + d.inputs[2].items.clear(); + let at = solidcore_record::Vec2::new(70.0, 5.0); + let point = d.candidate(&app.session, &crate::viewport::Hit::SketchPoint { sketch, id: "p".into(), at }).unwrap(); + d.pick(&app.session, point); + assert_eq!(apply_commands(&app, &d).unwrap().remove(0).1["to_frame"], json!({"sketch": sketch, "point": "p"})); + let id = apply(&mut app, &d); + assert!(app.session.model.result(id).is_some_and(|r| r.error.is_none())); +} + /// The Align dialog takes a plane (viewport or browser click) and the origin plane stays a plane /// in the command, so the bodies follow it when it moves. #[test] @@ -2015,7 +2056,7 @@ fn align_components_input_picks_occurrence_from_viewport_body_and_skips_root_bod let second = app.run("occurrence.copy", json!({"component": comp, "translate": [30, 0, 0]})).unwrap()["occurrence"].as_u64().unwrap(); let mut d = start(&mut app, vec![], "solid.align"); - d.kind = Kind::Align { flip: false, components: true, axes: [true; 3] }; + d.kind = Kind::Align { flip: false, components: true, axes: [true; 3], angle: String::new() }; d.inputs[0].label = "Components"; d.active = 0;