From 26ca82735b41b3ea8b17605c0a317ffadb47bcbe Mon Sep 17 00:00:00 2001 From: raykholo Date: Thu, 22 Oct 2026 18:21:11 +0000 Subject: [PATCH] Circular Pattern and Revolve: a construction axis can be the axis (#2885, #4506) (#3796) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * claim: #2885 * Circular Pattern and Revolve: a construction axis can be the axis (#2885) The dialogs send a picked axis by its name, but solid.pattern.circular only knew X, Y and Z, and solid.revolve / surface.revolve read any other name as a sketch line id. Picking a construction axis therefore failed. - solid.pattern.circular takes a construction axis name, saves it as `axis_feature` and turns about the axis as evaluated, so the copies follow it when it is edited. - AxisRef::Construction { name } for revolve and surface revolve, resolved at evaluation and checked to lie in the sketch plane. - construct.plane.at_angle accepts a construction axis name (its fixed axis line is taken from the axis as it is now). - Reopening these features shows the construction axis as the pick. - Design format: pending/construction-axis-refs.rs. * Construction axis references follow the axis in the feature's component frame (#4506) - Revolve, Surface Revolve and Circular Pattern resolve a construction axis where it is evaluated, mapped into the feature's component frame. - A line of the revolved sketch with the same id as a construction axis still wins, so existing scripts keep their meaning. - Tests: the revolve keeps the reference through save and reopen and follows an edited axis (60π to 80π mm³); perpendicular, offset and profile-crossing axes are refused without changing the design. --- crates/doc/src/document.rs | 6 ++ crates/doc/src/eval.rs | 56 +++++++++++++++---- crates/doc/src/eval_surface.rs | 2 +- .../format/pending/construction-axis-refs.rs | 4 ++ crates/doc/src/naming.rs | 4 +- crates/engine/src/cmd/features.rs | 55 ++++++++++++------ crates/engine/src/cmd/patterns_tests.rs | 29 ++++++++++ .../src/cmd/revolve_convention_tests.rs | 53 ++++++++++++++++++ crates/engine/src/cmd/surface.rs | 4 +- crates/ui-egui/src/dialogs.rs | 7 ++- crates/ui-egui/src/dialogs_surface.rs | 1 + 11 files changed, 188 insertions(+), 33 deletions(-) create mode 100644 crates/doc/src/format/pending/construction-axis-refs.rs diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index d396f24e7..c740fa793 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -368,6 +368,8 @@ pub enum AxisRef { World { axis: String }, /// Any line in the sketch plane, in world coordinates. Line { origin: Position, dir: Dir }, + /// A construction axis feature, by name, where it is when the revolve is evaluated. + Construction { name: FeatureName }, } /// Persistent cylindrical Emboss selection, authored in the feature component frame. @@ -2028,6 +2030,10 @@ pub enum PatternKind { alignment: solidcraft_sketch::PatternAlignment, #[serde(default, skip_serializing_if = "std::ops::Not::not")] reversed: bool, + /// A construction axis the copies turn about, by name, followed when it moves; + /// `origin` and `axis` are where it was when the pattern was made. + #[serde(default, skip_serializing_if = "Option::is_none")] + axis_feature: Option, }, /// Copies along a chain of sketch curves: instance k moves by path(k·spacing) − path(0), /// measured along the path from its start. diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index dec38fc68..4eba4b2dd 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -3320,7 +3320,17 @@ fn blend_target(state: &ModelState, body: &Option, edges: &[Vec }) } -pub(crate) fn revolve_axis(ss: &SolvedSketch, axis: &AxisRef) -> Result<(Vec2, Vec2)> { +/// The revolve axis in the sketch's 2D coordinates (a point on it, its direction). `construct` +/// gives a construction axis, by name, in the sketch's 3D frame. +pub(crate) fn revolve_axis(ss: &SolvedSketch, axis: &AxisRef, construct: &dyn Fn(&str) -> Result<(Vec3, Vec3)>) -> Result<(Vec2, Vec2)> { + let in_plane = |origin: Vec3, dir: Vec3| { + let pl = &ss.plane; + let d = dir.normalized().ok_or_else(|| DocError::Invalid("revolve axis has no direction".into()))?; + if d.dot(pl.normal()).abs() > 1e-9 || pl.height(origin).abs() > 1e-6 { + return Err(DocError::Invalid("the revolve axis does not lie in the sketch plane".into())); + } + Ok((pl.to_local(origin), Vec2::new(d.dot(pl.x), d.dot(pl.y)))) + }; match axis { AxisRef::SketchLine { curve } => { let ci = ss.sketch.curve_index(curve).ok_or_else(|| DocError::Unknown(format!("sketch line `{curve}`")))?; @@ -3350,17 +3360,37 @@ pub(crate) fn revolve_axis(ss: &SolvedSketch, axis: &AxisRef) -> Result<(Vec2, V } Ok((pl.to_local(Vec3::ZERO), Vec2::new(d.dot(pl.x), d.dot(pl.y)))) } - AxisRef::Line { origin, dir } => { - let pl = &ss.plane; - let d = dir.normalized().ok_or_else(|| DocError::Invalid("revolve axis has no direction".into()))?; - if d.dot(pl.normal()).abs() > 1e-9 || pl.height(origin.0).abs() > 1e-6 { - return Err(DocError::Invalid("the revolve axis does not lie in the sketch plane".into())); - } - Ok((pl.to_local(origin.0), Vec2::new(d.dot(pl.x), d.dot(pl.y)))) + AxisRef::Line { origin, dir } => in_plane(origin.0, dir.0), + AxisRef::Construction { name } => { + let (origin, dir) = construct(name)?; + in_plane(origin, dir) } } } +/// A construction axis `name` of the timeline so far, as evaluated, in the frame of component +/// `comp`: a point on it and its direction. Without a document (`doc` None) it is taken in its +/// own component's frame. +pub(crate) fn construction_axis_in(doc: Option<&Document>, st: &ModelState, name: &str, comp: u64) -> Result<(Vec3, Vec3)> { + let c = st + .construct + .iter() + .find(|c| c.name == name) + .ok_or_else(|| DocError::Unknown(format!("construction axis `{name}` (it must come earlier in the timeline)")))?; + let crate::construct::ConstructGeom::Axis { origin, dir } = &c.geom else { + return Err(DocError::Invalid(format!("`{name}` is not a construction axis"))); + }; + let Some(doc) = doc else { return Ok((*origin, *dir)) }; + let owner = doc.feature(c.feature).map_or(0, |f| f.component); + if owner == comp || doc.occurrences.is_empty() { + return Ok((*origin, *dir)); + } + let inverse = + crate::mat_inverse(&doc.component_transform(comp)).ok_or_else(|| DocError::Invalid("the feature's component frame is invalid".into()))?; + let relative = crate::mat_mul(&inverse, &doc.component_transform(owner)); + Ok((crate::apply_point(&relative, *origin), crate::apply_vector(&relative, *dir))) +} + /// Whether a drill from `p` along `d` reaches material: it starts into a body (`touches`), or, /// when `ahead` is set, a body lies further along `d`. A spot exactly on a surface counts only /// when the drill enters there, not when it leaves. Only the bodies in `scope` count. @@ -4395,7 +4425,7 @@ fn feature_tools_with_constructor( f.component, )?; let regions = solidcraft_sketch::merge_regions(&select_profiles(&ss, profiles)?); - let (o, d) = revolve_axis(&ss, axis)?; + let (o, d) = revolve_axis(&ss, axis, &|name| construction_axis_in(Some(doc), st, name, f.component))?; // To Object is in this feature's component frame: the model as seen from there. let tst = if to.is_some() { state_in_frame(doc, st, f.component) } else { std::borrow::Cow::Borrowed(st) }; // Where the tool meets its targets is measured where they are shown (#3383). @@ -5179,7 +5209,11 @@ fn pattern_transforms(doc: &Document, vals: &BTreeMap, st: &Model out.push(m); } } - crate::PatternKind::Circular { origin, axis, count: c, angle, alignment, reversed } => { + crate::PatternKind::Circular { origin, axis, count: c, angle, alignment, reversed, axis_feature } => { + let (origin, axis) = match axis_feature { + Some(name) => construction_axis_in(Some(doc), st, name, component)?, + None => (origin.0, axis.0), + }; let n = count(c)?; let total = val(vals, angle, Kind::Angle)?; let full = (total.abs() - std::f64::consts::TAU).abs() < 1e-9; @@ -5191,7 +5225,7 @@ fn pattern_transforms(doc: &Document, vals: &BTreeMap, st: &Model 0.0 }; for i in 1..n { - out.push(rotation(origin.0, axis.0, step * alignment.multiplier(i, *reversed))); + out.push(rotation(origin, axis, step * alignment.multiplier(i, *reversed))); } } } diff --git a/crates/doc/src/eval_surface.rs b/crates/doc/src/eval_surface.rs index ef141b29d..f1635d45d 100644 --- a/crates/doc/src/eval_surface.rs +++ b/crates/doc/src/eval_surface.rs @@ -304,7 +304,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, f.component, )?; - let (o, d) = revolve_axis(&ss, axis)?; + let (o, d) = revolve_axis(&ss, axis, &|name| construction_axis_in(Some(doc), st, name, f.component))?; let a = val(vals, angle, Kind::Angle)?; let (start, sweep) = match (angle2, symmetric) { (Some(a2), _) => { diff --git a/crates/doc/src/format/pending/construction-axis-refs.rs b/crates/doc/src/format/pending/construction-axis-refs.rs new file mode 100644 index 000000000..326269515 --- /dev/null +++ b/crates/doc/src/format/pending/construction-axis-refs.rs @@ -0,0 +1,4 @@ +//! A circular pattern can turn about a construction axis (`axis_feature`, its name) and a revolve +//! or surface revolve can take one as its axis (`"type": "construction"`, with `name`); both follow +//! the axis when it is edited. Older designs need no transformation: they name no construction +//! axis. The last release refuses a design saved with this (the newer format number). diff --git a/crates/doc/src/naming.rs b/crates/doc/src/naming.rs index 613a55049..a0622b472 100644 --- a/crates/doc/src/naming.rs +++ b/crates/doc/src/naming.rs @@ -583,7 +583,9 @@ fn role_name(f: &Feature, before: &ModelState, ps: &[Vec3], ns: &[Vec3], fi: usi } FeatureKind::Revolve { sketch, axis, .. } => { let Some(ss) = before.sketch(sketch.0) else { return format!("F{fid}:face:{fi}") }; - let Ok((o2, d2)) = crate::eval::revolve_axis(ss, axis) else { return format!("F{fid}:face:{fi}") }; + let Ok((o2, d2)) = crate::eval::revolve_axis(ss, axis, &|name| crate::eval::construction_axis_in(None, before, name, 0)) else { + return format!("F{fid}:face:{fi}"); + }; let (o, d) = (ss.plane.to_world(o2), (ss.plane.to_world(o2 + d2) - ss.plane.to_world(o2)).normalized().unwrap_or(Vec3::Z)); // A flat face holding the axis is an angle cap: on the sketch plane, or the far one. let flat = !ns.is_empty() && ns.windows(2).all(|w| w[0].cross(w[1]).len() < 1e-6) && ns.iter().all(|m| m.dot(d).abs() < 1e-6); diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 2bd92b1ee..c7d750fab 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -29,7 +29,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("solid.revolve", "Revolve", revolve) .at("SOLID", "CREATE") .icon("revolve") - .params("axis: sketch line id | x | y (sketch axes) | X|Y|Z (world); angle?: expr (default 360 deg); angle2?: expr (Two Sides: the other side's angle); direction?: symmetric (angle split either side, independent of axis direction); convention?: sketch_normal|legacy_axis_start (default sketch_normal; legacy retains older angular starts); to?: [x,y,z] (To Object: turn until that face, vertex or point); sketch?, profiles? | face: [x,y,z] (a planar body face as the profile) and face_body?: name (whose face, where faces of several bodies meet), operation?, targets?, name?, body_name?"), + .params("axis: sketch line id | x | y (sketch axes) | X|Y|Z (world) | construction axis name (followed when edited) | {origin, dir}; angle?: expr (default 360 deg); angle2?: expr (Two Sides: the other side's angle); direction?: symmetric (angle split either side, independent of axis direction); convention?: sketch_normal|legacy_axis_start (default sketch_normal; legacy retains older angular starts); to?: [x,y,z] (To Object: turn until that face, vertex or point); sketch?, profiles? | face: [x,y,z] (a planar body face as the profile) and face_body?: name (whose face, where faces of several bodies meet), operation?, targets?, name?, body_name?"), CommandSpec::new("solid.sweep", "Sweep", sweep) .at("SOLID", "CREATE") .icon("sweep") @@ -58,7 +58,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("solid.pattern.circular", "Circular Pattern", pattern_circ) .at("SOLID", "CREATE") .icon("pattern_circ") - .params("features: [names] | bodies: [names] | components: [names]; axis: X|Y|Z | {origin, dir}; count; angle? (default 360 deg; partial arcs include both ends); alignment?: left|center|right (default right; original stays fixed); reversed?: bool (Flip; selects the extra side for even centered counts)"), + .params("features: [names] | bodies: [names] | components: [names]; axis: X|Y|Z | construction axis name (followed when edited) | {origin, dir}; count; angle? (default 360 deg; partial arcs include both ends); alignment?: left|center|right (default right; original stays fixed); reversed?: bool (Flip; selects the extra side for even centered counts)"), CommandSpec::new("solid.pattern.path", "Pattern on Path", pattern_path) .at("SOLID", "CREATE") .icon("pattern_path") @@ -108,7 +108,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("construct.plane.at_angle", "Plane at Angle", plane_angle) .at("SOLID", "CONSTRUCT") .icon("plane_angle") - .params("base: XY|XZ|YZ|plane name; axis: X|Y|Z|{origin, dir}; angle: expr; name?"), + .params("base: XY|XZ|YZ|plane name; axis: X|Y|Z|construction axis name (where it is now)|{origin, dir}; angle: expr; name?"), CommandSpec::new("solid.split_face", "Split Face", split_face) .at("SOLID", "MODIFY") .icon("split_face") @@ -816,7 +816,7 @@ fn revolve(s: &mut Session, p: &Value) -> Result { } None => (feature_sketch(s, p, cmd)?, None), }; - let axis = axis_param(p, cmd)?; + let axis = axis_param(s, sketch, p, cmd)?; let angle = expr(p, "angle").unwrap_or_else(|| "360 deg".into()); check_expr(s, &angle, Kind::Angle, cmd, "angle")?; let profiles = match face_profile { @@ -852,9 +852,10 @@ fn revolve(s: &mut Session, p: &Value) -> Result { add_feature(s, p, kind) } -/// A revolve axis from its parameter: a sketch line id, the sketch's x or y axis, a world axis, -/// or {origin, dir}. -pub(super) fn axis_param(p: &Value, cmd: &str) -> Result { +/// A revolve axis of `sketch` from its parameter: a sketch line id, the sketch's x or y axis, a +/// world axis, a construction axis by name (followed when it is edited) or {origin, dir}. A line +/// of the sketch wins over a construction axis of the same name. +pub(super) fn axis_param(s: &Session, sketch: u64, p: &Value, cmd: &str) -> Result { if let Some(o) = p.get("axis").filter(|v| v.is_object()) { let origin = o.get("origin").and_then(vec3).unwrap_or(Vec3::ZERO); let dir = o.get("dir").and_then(vec3).ok_or_else(|| bad(cmd, "axis needs `dir`"))?; @@ -863,11 +864,22 @@ pub(super) fn axis_param(p: &Value, cmd: &str) -> Result { match str_(p, "axis") { Some(a @ ("X" | "Y" | "Z")) => Ok(AxisRef::World { axis: a.into() }), Some(a @ ("x" | "y")) => Ok(AxisRef::SketchAxis { axis: a.into() }), + Some(name) if !is_sketch_line(s, sketch, name) && is_construction_axis(s, name) => Ok(AxisRef::Construction { name: name.into() }), Some(id) => Ok(AxisRef::SketchLine { curve: id.into() }), - None => Err(bad(cmd, "`axis` must be a sketch line id, x, y (sketch axes), X, Y, Z or {origin, dir}")), + None => Err(bad(cmd, "`axis` must be a sketch line id, x, y (sketch axes), X, Y, Z, a construction axis or {origin, dir}")), } } +/// Whether `curve` is a curve of the sketch feature `sketch`. +fn is_sketch_line(s: &Session, sketch: u64, curve: &str) -> bool { + matches!(s.doc.feature(sketch).map(|f| &f.kind), Some(FeatureKind::Sketch { sketch, .. }) if sketch.curve_index(curve).is_some()) +} + +/// Whether `name` is a construction axis feature of the design. +fn is_construction_axis(s: &Session, name: &str) -> bool { + s.doc.find_feature(name).is_some_and(|f| matches!(f.kind, FeatureKind::ConstructionAxis { .. })) +} + fn radius_expr(s: &Session, p: &Value, cmd: &str) -> Result { match (expr(p, "radius"), expr(p, "diameter")) { (Some(r), _) => Ok(r), @@ -1325,13 +1337,22 @@ fn source_features(s: &Session, p: &Value, cmd: &str) -> Result> { Ok(names) } -fn axis_line(p: &Value, cmd: &str) -> Result<(Vec3, Vec3)> { +/// An axis line from `axis`: X, Y, Z, a construction axis by name or {origin, dir}. A construction +/// axis comes back where it is now, with its name. +fn axis_line(s: &Session, p: &Value, cmd: &str) -> Result<(Vec3, Vec3, Option)> { match p.get("axis") { Some(Value::String(a)) => match a.to_ascii_uppercase().as_str() { - "X" => Ok((Vec3::ZERO, Vec3::X)), - "Y" => Ok((Vec3::ZERO, Vec3::Y)), - "Z" => Ok((Vec3::ZERO, Vec3::Z)), - _ => Err(bad(cmd, "axis must be X, Y, Z or {origin, dir}")), + "X" => Ok((Vec3::ZERO, Vec3::X, None)), + "Y" => Ok((Vec3::ZERO, Vec3::Y, None)), + "Z" => Ok((Vec3::ZERO, Vec3::Z, None)), + _ if is_construction_axis(s, a) => { + let (_, _, origin, dir) = crate::view::construction_axes(s) + .into_iter() + .find(|(_, name, _, _)| name == a) + .ok_or_else(|| bad(cmd, format!("construction axis `{a}` has no geometry: fix its definition first")))?; + Ok((origin, dir, Some(a.as_str().into()))) + } + _ => Err(bad(cmd, "axis must be X, Y, Z, a construction axis or {origin, dir}")), }, Some(o @ Value::Object(_)) => { let origin = match o.get("origin") { @@ -1341,7 +1362,7 @@ fn axis_line(p: &Value, cmd: &str) -> Result<(Vec3, Vec3)> { })?, }; let dir = o.get("dir").and_then(vec3).and_then(|d| d.normalized()).ok_or_else(|| bad(cmd, "axis needs a non-zero `dir`"))?; - Ok((origin, dir)) + Ok((origin, dir, None)) } _ => Err(bad(cmd, "`axis` is required")), } @@ -1425,7 +1446,7 @@ fn pattern_rect(s: &mut Session, p: &Value) -> Result { fn pattern_circ(s: &mut Session, p: &Value) -> Result { let cmd = "solid.pattern.circular"; let (features, bodies) = pattern_sources(s, p, cmd)?; - let (origin, axis) = axis_line(p, cmd)?; + let (origin, axis, axis_feature) = axis_line(s, p, cmd)?; let count = req_expr(cmd, p, "count")?; check_expr(s, &count, Kind::Unitless, cmd, "count")?; let angle = expr(p, "angle").unwrap_or_else(|| "360 deg".into()); @@ -1437,6 +1458,7 @@ fn pattern_circ(s: &mut Session, p: &Value) -> Result { angle, alignment: super::alignment_param(p, "alignment", cmd)?, reversed: super::reversed_param(p, "reversed", cmd)?, + axis_feature, }; finish_pattern(s, p, features, pattern, bodies) } @@ -1613,7 +1635,8 @@ fn plane_offset(s: &mut Session, p: &Value) -> Result { fn plane_angle(s: &mut Session, p: &Value) -> Result { let cmd = "construct.plane.at_angle"; let base = plane_param(s, p.get("base"), cmd)?; - let (axis_origin, axis_dir) = axis_line(p, cmd)?; + // The plane keeps the axis line as it is now. + let (axis_origin, axis_dir, _) = axis_line(s, p, cmd)?; let angle = req_expr(cmd, p, "angle")?; check_expr(s, &angle, Kind::Angle, cmd, "angle")?; add_feature( diff --git a/crates/engine/src/cmd/patterns_tests.rs b/crates/engine/src/cmd/patterns_tests.rs index 4d4a7e56f..e9a3a0e4e 100644 --- a/crates/engine/src/cmd/patterns_tests.rs +++ b/crates/engine/src/cmd/patterns_tests.rs @@ -230,6 +230,35 @@ fn patterns_of_bodies() { assert!(s.execute("solid.pattern.rectangular", &json!({"bodies": ["Nope"], "dir1": [1, 0, 0], "count1": 2, "spacing1": 5})).is_err()); } +/// A construction axis picked in the dialog comes as its name (#2885): the copies turn about it, +/// and follow it when it is edited. +#[test] +fn circular_pattern_about_a_construction_axis_follows_it() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [40, 0, 0], "body_name": "Cube"})); + let axis = |x: f64| json!({"a": {"point": [x, 0, 0]}, "b": {"point": [x, 0, 10]}, "name": "Axis1"}); + run(&mut s, "construct.axis.two_points", axis(30.0)); + run(&mut s, "solid.pattern.circular", json!({"bodies": ["Cube"], "axis": "Axis1", "count": 4})); + // The x and y extent of the four cubes. + let span = |s: &Session| { + let st = s.model.state(); + assert_eq!(st.bodies.len(), 4); + let mut out = [f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY]; + for b in st.bodies.iter().filter_map(|mb| solidcraft_kernel::measure(&mb.body).ok()).map(|m| m.bbox) { + out = [out[0].min(b.min.x), out[1].max(b.max.x), out[2].min(b.min.y), out[3].max(b.max.y)]; + } + out + }; + // About x = 30: the cube at x 40…42 also lands at 18…20, and at y ±(10…12). + for (got, want) in span(&s).into_iter().zip([18.0, 42.0, -12.0, 12.0]) { + assert!((got - want).abs() < 1e-6, "{got} vs {want}"); + } + run(&mut s, "timeline.redefine", json!({"feature": "Axis1", "command": "construct.axis.two_points", "params": axis(35.0)})); + for (got, want) in span(&s).into_iter().zip([28.0, 42.0, -7.0, 7.0]) { + assert!((got - want).abs() < 1e-6, "{got} vs {want}"); + } +} + #[test] fn patterns_of_components_place_occurrences() { let mut s = Session::default(); diff --git a/crates/engine/src/cmd/revolve_convention_tests.rs b/crates/engine/src/cmd/revolve_convention_tests.rs index e2f40d67e..4e1d55de4 100644 --- a/crates/engine/src/cmd/revolve_convention_tests.rs +++ b/crates/engine/src/cmd/revolve_convention_tests.rs @@ -307,3 +307,56 @@ fn curved_targets_keep_only_the_material_before_the_post_for_both_axis_signs() { } } } + +/// The construction-axis points of a feature's JSON moved along x by `dx`. +fn shift_points(v: &mut Value, dx: f64) { + match v { + Value::Array(a) if a.len() == 3 && a.iter().all(Value::is_number) => a[0] = json!(a[0].as_f64().unwrap() + dx), + Value::Array(a) => a.iter_mut().for_each(|x| shift_points(x, dx)), + Value::Object(o) => o.values_mut().for_each(|x| shift_points(x, dx)), + _ => {} + } +} + +/// A construction axis picked as the revolve axis (#2885, #4506) is saved by name, survives +/// saving and opening, and the revolve follows the axis when it is edited. +#[test] +fn construction_axis_revolve_follows_the_axis() { + let mut s = Session::default(); + run(&mut s, "construct.axis.two_points", json!({"a":{"point":[0,0,0]},"b":{"point":[0,30,0]},"name":"Axis1"})); + profile(&mut s, false); + run(&mut s, "solid.revolve", json!({"sketch":"Profile","axis":"Axis1","angle":"180 deg","operation":"new","profiles":[0],"name":"Turn"})); + let turn = s.doc.find_feature("Turn").unwrap(); + assert!(matches!(&turn.kind, FeatureKind::Revolve { axis: solidcraft_doc::AxisRef::Construction { name }, .. } if name == "Axis1")); + let reopened = Document::from_json(&s.doc.to_json()).unwrap(); + assert_eq!(reopened.find_feature("Turn").unwrap().kind, turn.kind); + let volume = |s: &Session| solidcraft_kernel::measure(&s.model.state().bodies[0].body).unwrap().volume; + assert!((volume(&s) - 60.0 * PI).abs() < 0.05); + assert!((volume(&Session::new(reopened)) - 60.0 * PI).abs() < 0.05); + // Moving the axis 1 mm away from the profile widens the ring: radii 3 to 5 instead of 2 to 4. + let mut axis = serde_json::to_value(s.doc.find_feature("Axis1").unwrap()).unwrap(); + let def = if axis.get("def").is_some() { axis.get_mut("def") } else { axis.pointer_mut("/kind/def") }.unwrap(); + shift_points(def, -1.0); + let set = if axis.get("def").is_some() { json!({"def": axis["def"]}) } else { json!({"kind": {"def": axis["kind"]["def"]}}) }; + run(&mut s, "timeline.edit", json!({"feature":"Axis1","set":set})); + assert!((volume(&s) - 80.0 * PI).abs() < 0.05, "{}", volume(&s)); +} + +#[test] +fn construction_axis_revolve_rejects_invalid_axes_atomically() { + for (a, b, message) in [ + ([0, 0, 0], [0, 0, 30], "does not lie in the sketch plane"), + ([0, 0, 1], [0, 30, 1], "does not lie in the sketch plane"), + ([3, 0, 0], [3, 30, 0], "profile crosses the revolve axis"), + ] { + let mut s = Session::default(); + run(&mut s, "construct.axis.two_points", json!({"a":{"point":a},"b":{"point":b},"name":"Axis1"})); + profile(&mut s, false); + let before = s.doc.to_json(); + let error = + s.execute("solid.revolve", &json!({"sketch":"Profile","axis":"Axis1","angle":"180 deg","operation":"new"})).unwrap_err().to_string(); + assert!(error.contains(message), "{error}"); + assert_eq!(s.doc.to_json(), before); + assert!(s.model.state().bodies.is_empty()); + } +} diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs index 39a1d6806..f2c488641 100644 --- a/crates/engine/src/cmd/surface.rs +++ b/crates/engine/src/cmd/surface.rs @@ -43,7 +43,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("surface.revolve", "Surface Revolve", surface_revolve) .at("SURFACE", "CREATE") .icon("surface_revolve") - .params("sketch?: id|name; curves?: [curve ids] and/or profiles? (as surface.extrude); axis: sketch line id|x|y|X|Y|Z|{origin, dir}; angle?: expr (default 360 deg); angle2?: expr (the other side); symmetric?: bool; name?, body_name? (a surface body, no caps; a solid where a full turn closes it)"), + .params("sketch?: id|name; curves?: [curve ids] and/or profiles? (as surface.extrude); axis: sketch line id|x|y|X|Y|Z|construction axis name|{origin, dir}; angle?: expr (default 360 deg); angle2?: expr (the other side); symmetric?: bool; name?, body_name? (a surface body, no caps; a solid where a full turn closes it)"), CommandSpec::new("surface.sweep", "Surface Sweep", surface_sweep) .at("SURFACE", "CREATE") .icon("surface_sweep") @@ -333,7 +333,7 @@ fn surface_revolve(s: &mut Session, p: &Value) -> Result { let cmd = "surface.revolve"; let sketch = feature_sketch(s, p, cmd)?; let (profiles, curves) = sheet_inputs(p, cmd)?; - let axis = axis_param(p, cmd)?; + let axis = axis_param(s, sketch, p, cmd)?; let angle = expr(p, "angle").unwrap_or_else(|| "360 deg".into()); check_expr(s, &angle, Kind::Angle, cmd, "angle")?; let angle2 = expr(p, "angle2"); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index f20648b4a..a2dd5f67f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4240,6 +4240,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option Some(Sel::Axis { name: axis.to_ascii_uppercase() }), AxisRef::SketchAxis { axis } => Some(Sel::Axis { name: axis.to_ascii_lowercase() }), AxisRef::SketchLine { curve } => Some(Sel::SketchCurve { id: curve.clone() }), + AxisRef::Construction { name } => Some(Sel::Axis { name: name.to_string() }), _ => None, }; if let Some(inp) = d.inputs.get_mut(1) { @@ -4571,12 +4572,14 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { + PatternKind::Circular { origin, axis, count, angle, alignment, reversed, axis_feature } => { let mut d = start("solid.pattern.circular")?; d.extra.insert("alignment".into(), json!(alignment)); d.extra.insert("reversed".into(), json!(reversed)); d.kind = Kind::PatternCirc { count: count.to_string(), angle: angle.to_string() }; - match world_axis(axis.0).filter(|_| origin.len() < 1e-9) { + // The construction axis it turns about, else an origin axis or its line. + let named = axis_feature.as_ref().map(|n| n.to_string()); + match named.or_else(|| world_axis(axis.0).filter(|_| origin.len() < 1e-9)) { Some(name) => { if let Some(inp) = d.inputs.get_mut(1) { inp.items = vec![Sel::Axis { name }]; diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index c64ede7e9..650775a95 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -808,6 +808,7 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K AxisRef::World { axis } => (Some(Sel::Axis { name: axis.to_ascii_uppercase() }), None), AxisRef::SketchAxis { axis } => (Some(Sel::Axis { name: axis.to_ascii_lowercase() }), None), AxisRef::SketchLine { curve } => (Some(Sel::SketchCurve { id: curve.clone() }), None), + AxisRef::Construction { name } => (Some(Sel::Axis { name: name.to_string() }), None), AxisRef::Line { origin, dir } => ( None, Some(json!({