From 74d690db9956217acfbc5cd1ca9c6d8c19b76c38 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 3 Dec 2026 10:32:33 -0500 Subject: [PATCH] solidcore: swept volume of a solid carried along a screw A screw motion for the swept volume (tangency-labs/solidcore#3532): a turn about a fixed axis with a steady rise along it, any number of turns. Kernel (sweep::swept_volume): Motion::Screw; its characteristic, n . (a x r) + lead (n . a) = 0, exact for planes (a plane square to n x a, off the axis by the lead), spheres (the plane through the centre square to a x (o - c) + lead a), coaxial cylinders (along themselves), coaxial cones (none), coaxial tori (the equators) and cylinders about a parallel axis (the meridians); other surfaces of revolution are refused by name (ScrewOffAxis). Walls and paths are the turn's exact rational arcs lifted by the rise at their angles, as the screw sweep lifts its walls (screw::lift_error, now pub(crate)), in as many equal pieces as keep the lift within the body's tolerance. A face's prism is certified embedded under a screw where each helix meets it once leaving: a plane square to the axis; a plane along it or a parallel cylinder shorter along the axis than a turn's rise (or in less than a turn); a leaning plane where the rise outruns the turn; a coaxial cone or torus half. The motion's end is the kernel's matrix (Motion::end_matrix). Ops: a screw always takes the union of the solid and its front faces' prisms. Tests: brep-bench swept/square-bar-screwed-through-rod's closed form (bmander/brep-bench, MIT OR Apache-2.0) to 1e-6; a screw off a cone's axis refused by name; kernel unit tests of the path and the plane cut. Co-Authored-By: Claude Opus 5.5 --- .../crates/solidcore-ops/src/swept_volume.rs | 32 +- .../solidcore-ops/tests/swept_volume.rs | 54 +++ .../crates/solidcore-sweep/src/sweep/screw.rs | 2 +- .../solidcore-sweep/src/sweep/swept_volume.rs | 432 +++++++++++++++++- 4 files changed, 490 insertions(+), 30 deletions(-) diff --git a/solidcore/crates/solidcore-ops/src/swept_volume.rs b/solidcore/crates/solidcore-ops/src/swept_volume.rs index ebca735fa8d..29923b67166 100644 --- a/solidcore/crates/solidcore-ops/src/swept_volume.rs +++ b/solidcore/crates/solidcore-ops/src/swept_volume.rs @@ -1,5 +1,5 @@ //! The swept volume of a solid under a rigid motion: everything the solid passes through as it -//! slides along a straight line or turns about a fixed axis (the kernel's +//! slides along a straight line, turns about a fixed axis or is screwed along one (the kernel's //! `solidcore::sweep::swept_volume`, which holds the geometry and its derivation). //! //! The workflow, as kernel calls: @@ -22,7 +22,6 @@ use solidcore_record::brep::{ Brep as Record, Curve2, Edge, Face, Loop, OrientedEdge, OrientedFace, Region, Shell, Surface, }; -use crate::affine; use crate::body::Body; use crate::split::{split_faces, Tool}; use crate::{Error, Result}; @@ -49,8 +48,8 @@ fn invalid(e: solidcore_record::brep::Invalid) -> Error { /// certifies it embedded, otherwise the body united with each front face's prism. /// /// # Errors -/// - [`Error::Unsupported`] with the reason: a motion that moves nothing or turns a whole -/// revolution, a face whose characteristic has no exact form yet (a B-spline face, a torus +/// - [`Error::Unsupported`] with the reason: a motion that moves nothing, a turn of a whole +/// revolution, a screw past the kernel's bounds, a face whose characteristic has no exact form yet (a B-spline face, a torus /// slid aslant, a surface of revolution turned about a skew axis), a vertex on a turn's axis, /// a face whose prism the motion may carry across itself; /// - [`Error::Record`] for geometry the record refuses; @@ -76,7 +75,8 @@ pub fn swept_volume(body: &Body, motion: &Motion) -> Result { } let face = sorted.record.faces.get(fi).ok_or(Error::Exception)?; let surface = solidcore_convert::surface(&face.surface).map_err(invalid)?; - if !kernel::prism_embeds(&surface, &motion) { + let edges = face_curves(&sorted.record, face)?; + if !kernel::prism_embeds(&surface, &motion, &edges) { return Err(Error::Unsupported( "swept volume: a face this motion may carry across itself is not swept yet", )); @@ -98,6 +98,7 @@ fn envelope_embeds(cut: &Body, s: &Sorted, motion: &Motion) -> Result { } match motion { Motion::Slide { .. } => Ok(true), + Motion::Screw { .. } => Ok(false), Motion::Turn { .. } => { let surfaces = s .record @@ -240,12 +241,14 @@ fn cut_at_characteristics(body: &Body, motion: &Motion) -> Result { )) } -/// The matrix of `motion`'s end. -fn end_matrix(motion: &Motion) -> Result { - match *motion { - Motion::Slide { by } => affine::translation(by), - Motion::Turn { point, axis, angle } => affine::rotation(point, axis, angle), - } +/// The curves of `face`'s edges, each in its own parameter (its NURBS form when it has one). +fn face_curves(record: &Record, face: &Face) -> Result> { + face_edges(face) + .map(|oe| { + let edge = record.edges.get(oe.edge as usize).ok_or(Error::Exception)?; + solidcore_convert::curve(edge.nurbs.as_ref().unwrap_or(&edge.curve)).map_err(invalid) + }) + .collect() } /// A straight pcurve from `a` to `b` over `[t0, t1]`. @@ -276,7 +279,7 @@ struct Sorted { fn sort(cut: &Body, motion: &Motion) -> Result { let (record, order) = cut.to_record()?; let moved_body = cut.copy()?; - moved_body.transform(&end_matrix(motion)?)?; + moved_body.transform(&motion.end_matrix())?; let (moved, _) = moved_body.to_record()?; if moved.faces.len() != record.faces.len() || moved.edges.len() != record.edges.len() @@ -512,7 +515,8 @@ fn assemble( .enumerate() { if on { - let path = kernel::path(motion, vertex.point, record.tolerance).map_err(refused)?; + let path = kernel::path(motion, vertex.point, record.tolerance, record.tolerance) + .map_err(refused)?; let curve = solidcore_convert::record_curve(path).map_err(invalid)?; *slot = Some(index(out.edges.len())?); out.edges.push(Edge { @@ -575,7 +579,7 @@ fn assemble( .map_err(invalid)?; let t = source.interval; let unit = [0.0, 1.0]; - let wall = kernel::wall(motion, &along, t).map_err(refused)?; + let wall = kernel::wall(motion, &along, t, record.tolerance).map_err(refused)?; // a flat wall is the plane it lies in, its trims the kernel's let (surface, domain) = match kernel::flat_wall(&wall, [t, unit]) { Some((plane, domain)) => { diff --git a/solidcore/crates/solidcore-ops/tests/swept_volume.rs b/solidcore/crates/solidcore-ops/tests/swept_volume.rs index fc815535e08..ad22e4cc391 100644 --- a/solidcore/crates/solidcore-ops/tests/swept_volume.rs +++ b/solidcore/crates/solidcore-ops/tests/swept_volume.rs @@ -438,3 +438,57 @@ fn what_has_no_exact_characteristic_is_refused_by_name() { let r = swept_volume(&drum, &Motion::Slide { by: [0.0; 3] }); assert!(matches!(r, Err(Error::Unsupported(_))), "{r:?}"); } + +/// A body placed by a screw about the z axis at `from` degrees, then everything it passes +/// through to `to` degrees, rising `per_turn` a turn. +fn screwed(body: &Body, from: f64, to: f64, per_turn: f64) -> Body { + body.transform(&affine::rotation([0.0; 3], [0.0, 0.0, 1.0], degrees(from)).unwrap()) + .unwrap(); + body.transform(&affine::translation([0.0, 0.0, per_turn * from / 360.0]).unwrap()) + .unwrap(); + swept_volume( + body, + &Motion::Screw { + point: [0.0; 3], + axis: [0.0, 0.0, 1.0], + angle: degrees(to - from), + rise: per_turn * (to - from) / 360.0, + }, + ) + .unwrap() +} + +/// swept/square-bar-screwed-through-rod: a square thread, π5²·20 − (20/6)·2π∫₄⁵ ρ w(ρ) dρ, +/// w(ρ) = 2 + (6/π)·acos(4/ρ). Four turns: each face's prism is embedded, the faces along the +/// axis being shorter along it (2) than the rise of a turn (6). +#[test] +fn a_square_bar_screwed_through_a_rod() { + let rod = make_cylinder([0.0; 3], 5.0, 20.0).unwrap(); + let bar = make_box([4.0, -8.0, -1.0], [8.0, 16.0, 2.0]).unwrap(); + let swept = screwed(&bar, -90.0, 1350.0, 6.0); + matches( + "square thread", + &cut(rod, swept), + 1_300.550_213_182_866_9, + 821.167_155_563_891_5, + ); +} + +/// A screw that would need a cone's characteristic off its axis is refused by name. +#[test] +fn a_screw_off_a_cones_axis_is_refused_by_name() { + let bit = upright_revolution(5.0, &[[0.0, -2.0], [5.0, 3.0], [0.0, 3.0]]); + let r = swept_volume( + &bit, + &Motion::Screw { + point: [0.0; 3], + axis: [0.0, 0.0, 1.0], + angle: 1.0, + rise: 1.0, + }, + ); + assert!( + matches!(r, Err(Error::Unsupported(why)) if why.contains("screwed")), + "{r:?}" + ); +} diff --git a/solidcore/crates/solidcore-sweep/src/sweep/screw.rs b/solidcore/crates/solidcore-sweep/src/sweep/screw.rs index 4e41a24f754..58069f7f381 100644 --- a/solidcore/crates/solidcore-sweep/src/sweep/screw.rs +++ b/solidcore/crates/solidcore-sweep/src/sweep/screw.rs @@ -293,7 +293,7 @@ impl Stations { /// How far, in radians of turn, the rational quadratic lift of a span of half-angle /// `half` leads or lags the true lift, at most (sampled: the difference is smooth, odd /// and nought at the span's middle and ends, about `0.008 h^3`). -fn lift_error(half: f64) -> f64 { +pub(crate) fn lift_error(half: f64) -> f64 { let mut worst: f64 = 0.0; for i in 0..=2048 { let s = f64::from(i) / 2048.0; diff --git a/solidcore/crates/solidcore-sweep/src/sweep/swept_volume.rs b/solidcore/crates/solidcore-sweep/src/sweep/swept_volume.rs index ce442e2c23a..0d4065e72bd 100644 --- a/solidcore/crates/solidcore-sweep/src/sweep/swept_volume.rs +++ b/solidcore/crates/solidcore-sweep/src/sweep/swept_volume.rs @@ -49,6 +49,19 @@ pub enum Motion { /// The move from start to end. by: [f64; 3], }, + /// A screw: a turn by `angle` radians, right-handed about the line through `point` along + /// `axis`, and with it a rise of `rise` along the axis, both at a steady rate (`angle` may + /// make several turns). + Screw { + /// A point on the axis. + point: [f64; 3], + /// The axis (any length but none). + axis: [f64; 3], + /// The turn, radians, positive. + angle: f64, + /// The rise along the axis over the whole motion. + rise: f64, + }, /// A turn by `angle` radians, right-handed about the line through `point` along `axis`. Turn { /// A point on the axis. @@ -80,6 +93,10 @@ pub enum Refusal { OnAxis, /// An edge curve with no NURBS form here (a traced intersection). CurveKind, + /// A cone or torus screwed about an axis parallel to its own but off it, a surface of + /// revolution screwed about an axis not parallel to its own: its characteristic is no line + /// or circle. + ScrewOffAxis, } impl Refusal { @@ -100,6 +117,9 @@ impl Refusal { } Refusal::OnAxis => "swept volume: a vertex on the turn's axis is not swept yet", Refusal::CurveKind => "swept volume: an edge without a NURBS form", + Refusal::ScrewOffAxis => { + "swept volume: a cylinder, cone or torus screwed about an axis other than its own has no exact characteristic yet" + } } } } @@ -139,6 +159,9 @@ fn finite(a: V) -> bool { /// How much smaller than the scale a length is taken as none. const SMALL: f64 = 1e-12; +/// The most turns a screw makes. +pub const MAX_SCREW_TURNS: f64 = 100.0; + impl Motion { /// The motion with its axis made unit, or why it is refused: not finite, moving nothing, /// or a turn of a whole revolution or more. @@ -163,6 +186,29 @@ impl Motion { let axis = unit(axis).ok_or(Refusal::Motion)?; Ok(Motion::Turn { point, axis, angle }) } + Motion::Screw { + point, + axis, + angle, + rise, + } => { + if !finite(point) || !angle.is_finite() || angle <= 0.0 || !rise.is_finite() { + return Err(Refusal::Motion); + } + if angle > MAX_SCREW_TURNS * 2.0 * core::f64::consts::PI { + return Err(Refusal::Motion); + } + if rise == 0.0 { + return Motion::Turn { point, axis, angle }.checked(); + } + let axis = unit(axis).ok_or(Refusal::Motion)?; + Ok(Motion::Screw { + point, + axis, + angle, + rise, + }) + } } } @@ -173,6 +219,12 @@ impl Motion { match *self { Motion::Slide { by } => by, Motion::Turn { point, axis, angle } => mul(cross(axis, sub(p, point)), angle), + Motion::Screw { + point, + axis, + angle, + rise, + } => add(mul(cross(axis, sub(p, point)), angle), mul(axis, rise)), } } @@ -204,12 +256,35 @@ impl Motion { } } + /// The motion's end as an affine matrix in the row form a body's transform takes: rows 0-2 + /// the images of x, y and z, row 3 the move of the origin (`p' = p·A + t`). + #[must_use] + pub fn end_matrix(&self) -> [[f64; 4]; 4] { + let o = self.at([0.0; 3], 1.0); + let row = |e: V| { + let q = sub(self.at(e, 1.0), o); + [q[0], q[1], q[2], 0.0] + }; + [ + row([1.0, 0.0, 0.0]), + row([0.0, 1.0, 0.0]), + row([0.0, 0.0, 1.0]), + [o[0], o[1], o[2], 1.0], + ] + } + /// `p` moved by the fraction `t` of the motion. #[must_use] pub fn at(&self, p: V, t: f64) -> V { match *self { Motion::Slide { by } => add(p, mul(by, t)), Motion::Turn { point, axis, angle } => turn(point, axis, angle * t, p), + Motion::Screw { + point, + axis, + angle, + rise, + } => add(turn(point, axis, angle * t, p), mul(axis, rise * t)), } } } @@ -308,6 +383,12 @@ pub fn characteristic( match motion { Motion::Slide { by } => slide_characteristic(surface, *by, reach), Motion::Turn { point, axis, .. } => turn_characteristic(surface, *point, *axis, reach), + Motion::Screw { + point, + axis, + angle, + rise, + } => screw_characteristic(surface, *point, *axis, rise / angle, reach), } } @@ -396,6 +477,77 @@ fn slide_characteristic(s: &Surface, d: V, reach: Reach<'_>) -> Result, +) -> Result { + // a plane of unit normal n: (n × a) · (x - c) = -lead (n · a), a plane square to n × a + let plane = |n: V| -> Result { + let n = unit(n).ok_or(Refusal::SurfaceKind)?; + let m = cross(n, a); + let len = norm(m); + if len <= SMALL { + return Ok(Characteristic::None); + } + let m = mul(m, 1.0 / len); + let offset = -lead * dot(n, a) / len; + Ok(Characteristic::Cut(vec![plane_tool( + add(c, mul(m, offset)), + m, + reach, + )])) + }; + match s { + Surface::Plane { u_axis, v_axis, .. } => plane(cross(*u_axis, *v_axis)), + Surface::PlaneThrough { + origin, + u_point, + v_point, + } => plane(cross(sub(*u_point, *origin), sub(*v_point, *origin))), + Surface::Sphere { frame, .. } => { + // (x - o) · (a × (o - c) + lead a) = 0: the plane through the centre + let o = frame.origin; + let normal = add(cross(a, sub(o, c)), mul(a, lead)); + let normal = unit(normal).ok_or(Refusal::Motion)?; + Ok(Characteristic::Cut(vec![plane_tool(o, normal, reach)])) + } + Surface::Cylinder { frame, .. } + | Surface::Cone { frame, .. } + | Surface::Torus { frame, .. } => { + let o = frame.origin; + let e = z_of(frame); + if norm(cross(a, e)) > SMALL { + return Err(Refusal::ScrewOffAxis); + } + let oc = sub(o, c); + let w = sub(oc, mul(e, dot(oc, e))); + let coaxial = norm(w) <= SMALL * norm(oc).max(1.0); + match (s, coaxial) { + // the screw slides it along itself + (Surface::Cylinder { .. }, true) => Ok(Characteristic::Along), + // n · a is the same all round, and n · (a × r) is nought + (Surface::Cone { .. }, true) => Ok(Characteristic::None), + // n · v = lead sin w: the equators + (Surface::Torus { .. }, true) => { + Ok(Characteristic::Cut(vec![plane_tool(o, e, reach)])) + } + // n · a = 0: as turned, the meridians in the plane of both axes + (Surface::Cylinder { .. }, false) => { + let normal = unit(cross(e, w)).ok_or(Refusal::Motion)?; + Ok(Characteristic::Cut(vec![plane_tool(o, normal, reach)])) + } + _ => Err(Refusal::ScrewOffAxis), + } + } + _ => Err(Refusal::SurfaceKind), + } +} + /// A plane of normal `n` slid along the unit `d`: along itself when `d` lies in it. fn plane_slid(n: V, d: V) -> Result { let n = unit(n).ok_or(Refusal::SurfaceKind)?; @@ -592,18 +744,64 @@ fn nurbs_of(curve: &Curve, interval: [f64; 2]) -> Result<(Vec, Vec<[f64; 4] /// The rational arc a turn carries `p` along, as homogeneous control points, with the knots /// over `[0, 1]`: quadratic pieces of at most a quarter turn each. fn arc(point: V, axis: V, angle: f64, p: V) -> (Vec, Vec<[f64; 4]>) { - let pieces = (angle / (core::f64::consts::FRAC_PI_2) - 1e-9) + helix(point, axis, angle, 0.0, quarter_turns(angle), p) +} + +/// The pieces of at most a quarter turn each that `angle` takes. +fn quarter_turns(angle: f64) -> usize { + (angle / (core::f64::consts::FRAC_PI_2) - 1e-9) .ceil() - .max(1.0) as usize; + .max(1.0) as usize +} + +/// The most pieces a screw's paths are cut into. +pub const MAX_SCREW_PIECES: usize = 40_000; + +/// How many equal pieces a screw's paths take so that each piece's rational quadratic lift (the +/// screw sweep's, [`super::screw`]) strays at most `fit` (the body's tolerance) along the axis +/// from the true helix (the stray is odd about each piece's middle, so a volume it bounds +/// barely moves): +/// at least one per quarter turn. +/// +/// # Errors +/// [`Refusal::Motion`] past [`MAX_SCREW_PIECES`]. +fn screw_pieces(angle: f64, rise: f64, fit: f64) -> Result { + let lead = (rise / angle).abs(); + let mut pieces = quarter_turns(angle); + while lead * super::screw::lift_error(0.5 * angle / pieces as f64) > fit { + pieces = (pieces as f64 * 1.25).ceil() as usize; + if pieces > MAX_SCREW_PIECES { + return Err(Refusal::Motion); + } + } + Ok(pieces) +} + +/// The rational path a screw (a turn by `angle` with a rise of `rise`) carries `p` along, in +/// `pieces` equal pieces, as homogeneous control points, with the knots over `[0, 1]`: each +/// piece the exact rational quadratic arc of the turn, its three points lifted by the rise at +/// their angles, so the path keeps the exact distance from the axis and angle and strays only +/// in its rise ([`super::screw::lift_error`]). +fn helix( + point: V, + axis: V, + angle: f64, + rise: f64, + pieces: usize, + p: V, +) -> (Vec, Vec<[f64; 4]>) { let step = angle / pieces as f64; let w = det::cos(step / 2.0); + let lift = |a: f64| mul(axis, rise * a / angle); let foot = add(point, mul(axis, dot(axis, sub(p, point)))); let mut knots = vec![0.0, 0.0, 0.0]; let mut net = Vec::new(); for k in 0..pieces { - let start = turn(point, axis, step * k as f64, p); - let mid_on = turn(point, axis, step * (k as f64 + 0.5), p); - let mid = add(foot, mul(sub(mid_on, foot), 1.0 / w)); + let a0 = step * k as f64; + let am = step * (k as f64 + 0.5); + let start = add(turn(point, axis, a0, p), lift(a0)); + let mid_on = turn(point, axis, am, p); + let mid = add(add(foot, mul(sub(mid_on, foot), 1.0 / w)), lift(am)); net.push([start[0], start[1], start[2], 1.0]); net.push([mid[0] * w, mid[1] * w, mid[2] * w, w]); if k + 1 < pieces { @@ -612,18 +810,20 @@ fn arc(point: V, axis: V, angle: f64, p: V) -> (Vec, Vec<[f64; 4]>) { knots.push(t); } } - let end = turn(point, axis, angle, p); + let end = add(turn(point, axis, angle, p), lift(angle)); net.push([end[0], end[1], end[2], 1.0]); knots.extend([1.0, 1.0, 1.0]); (knots, net) } /// The path of `p` under `motion` (checked), on `[0, 1]`: a line for a slide, a rational arc -/// for a turn. +/// for a turn, a rational path within `fit` (the body's tolerance) of the helix for a +/// screw. /// /// # Errors -/// [`Refusal::OnAxis`] for a point a turn does not move. -pub fn path(motion: &Motion, p: V, tolerance: f64) -> Result { +/// [`Refusal::OnAxis`] for a point a turn does not move; [`Refusal::Motion`] for a screw past +/// [`MAX_SCREW_PIECES`]. +pub fn path(motion: &Motion, p: V, tolerance: f64, fit: f64) -> Result { match *motion { Motion::Slide { by } => Ok(Curve::Line { start: p, @@ -637,16 +837,33 @@ pub fn path(motion: &Motion, p: V, tolerance: f64) -> Result { let (knots, homogeneous) = arc(point, axis, angle, p); Ok(Curve::RationalSpline { knots, homogeneous }) } + Motion::Screw { + point, + axis, + angle, + rise, + } => { + let pieces = screw_pieces(angle, rise, fit)?; + let (knots, homogeneous) = helix(point, axis, angle, rise, pieces, p); + Ok(Curve::RationalSpline { knots, homogeneous }) + } } } /// The wall `curve` (over `interval`, in its own parameter) sweeps under `motion` (checked): /// `u` the curve's parameter, `v` the motion's in `[0, 1]`, so that `v = 0` is the curve, `v = /// 1` its image at the motion's end, and each `u = const` the path ([`path`]) of that point. +/// A screw's wall is within `fit` (the body's tolerance) of the true helical sweep, exactly as far from the axis and at +/// the angle; the others are exact. /// /// # Errors -/// [`Refusal::CurveKind`] for a curve with no NURBS here. -pub fn wall(motion: &Motion, curve: &Curve, interval: [f64; 2]) -> Result { +/// [`Refusal::CurveKind`] for a curve with no NURBS here; those of [`path`]. +pub fn wall( + motion: &Motion, + curve: &Curve, + interval: [f64; 2], + fit: f64, +) -> Result { let (u_knots, net) = nurbs_of(curve, interval)?; let rational = matches!(curve, Curve::RationalSpline { .. }); match *motion { @@ -683,13 +900,28 @@ pub fn wall(motion: &Motion, curve: &Curve, interval: [f64; 2]) -> Result { + Motion::Turn { .. } | Motion::Screw { .. } => { + let (point, axis, angle, rise) = match *motion { + Motion::Screw { + point, + axis, + angle, + rise, + } => (point, axis, angle, rise), + Motion::Turn { point, axis, angle } => (point, axis, angle, 0.0), + Motion::Slide { .. } => return Err(Refusal::Motion), + }; + let pieces = if rise == 0.0 { + quarter_turns(angle) + } else { + screw_pieces(angle, rise, fit)? + }; let mut v_knots = Vec::new(); let mut homogeneous = Vec::new(); for h in &net { let w = h[3]; let p = [h[0] / w, h[1] / w, h[2] / w]; - let (knots, ring) = arc(point, axis, angle, p); + let (knots, ring) = helix(point, axis, angle, rise, pieces, p); v_knots = knots; homogeneous.push( ring.iter() @@ -714,8 +946,24 @@ pub fn wall(motion: &Motion, curve: &Curve, interval: [f64; 2]) -> Result ρ |n × a|` out to the +/// face's farthest point); a coaxial cone or torus half once. #[must_use] -pub fn prism_embeds(surface: &Surface, motion: &Motion) -> bool { +pub fn prism_embeds(surface: &Surface, motion: &Motion, edges: &[Curve]) -> bool { + if let Motion::Screw { + point, + axis, + angle, + rise, + } = *motion + { + return screw_prism_embeds(surface, point, axis, angle, rise, edges); + } match (surface, motion) { ( Surface::Plane { .. } @@ -738,6 +986,98 @@ pub fn prism_embeds(surface: &Surface, motion: &Motion) -> bool { } } +/// The control points of `curves` (each a bound of its curve: the curve lies in their hull). +fn hull_points(curves: &[Curve]) -> Vec { + let mut out = Vec::new(); + for c in curves { + match c { + Curve::Line { start, end } => out.extend([*start, *end]), + Curve::Polyline { points } | Curve::Spline { points, .. } => out.extend(points), + Curve::RationalSpline { homogeneous, .. } => out.extend( + homogeneous + .iter() + .filter(|h| h[3] > 0.0) + .map(|h| [h[0] / h[3], h[1] / h[3], h[2] / h[3]]), + ), + Curve::Circle { frame, radius } => { + let r = *radius; + for (sx, sy) in [(1.0, 1.0), (1.0, -1.0), (-1.0, 1.0), (-1.0, -1.0)] { + out.push(add( + frame.origin, + add(mul(frame.x_axis, sx * r), mul(frame.y_axis, sy * r)), + )); + } + } + Curve::Ellipse { frame, radii } => { + for (sx, sy) in [(1.0, 1.0), (1.0, -1.0), (-1.0, 1.0), (-1.0, -1.0)] { + out.push(add( + frame.origin, + add( + mul(frame.x_axis, sx * radii[0]), + mul(frame.y_axis, sy * radii[1]), + ), + )); + } + } + Curve::SurfaceIntersection { .. } => {} + } + } + out +} + +/// [`prism_embeds`] under a screw. +fn screw_prism_embeds(s: &Surface, c: V, a: V, angle: f64, rise: f64, edges: &[Curve]) -> bool { + let points = hull_points(edges); + if points.is_empty() { + return false; + } + let along = |p: &V| dot(sub(*p, c), a); + let lo = points.iter().map(along).fold(f64::INFINITY, f64::min); + let hi = points.iter().map(along).fold(f64::NEG_INFINITY, f64::max); + let reach = points + .iter() + .map(|p| norm(cross(sub(*p, c), a))) + .fold(0.0, f64::max); + let lead = (rise / angle).abs(); + let pitch = lead * 2.0 * core::f64::consts::PI; + let short = angle < 2.0 * core::f64::consts::PI || hi - lo < pitch; + let plane = |n: V| { + let Some(n) = unit(n) else { return false }; + let na = dot(n, a).abs(); + let np = norm(cross(n, a)); + if np <= SMALL { + true + } else if na <= SMALL { + short + } else { + lead * na > np * reach + } + }; + match s { + Surface::Plane { u_axis, v_axis, .. } => plane(cross(*u_axis, *v_axis)), + Surface::PlaneThrough { + origin, + u_point, + v_point, + } => plane(cross(sub(*u_point, *origin), sub(*v_point, *origin))), + Surface::Cylinder { frame, .. } + | Surface::Cone { frame, .. } + | Surface::Torus { frame, .. } => { + let e = z_of(frame); + if norm(cross(a, e)) > SMALL { + return false; + } + let oc = sub(frame.origin, c); + let coaxial = norm(sub(oc, mul(a, dot(oc, a)))) <= SMALL * norm(oc).max(1.0); + match s { + Surface::Cylinder { .. } => coaxial || short, + _ => coaxial, + } + } + _ => false, + } +} + /// Whether every circle a turn moves points on meets a convex solid in one arc, and the turn /// is short enough that no point leaving the solid comes round to it again: the solid's faces /// all turn about one line `A` parallel to the turn's axis (planes square to it; cylinders, @@ -1106,7 +1446,8 @@ mod tests { axis: [0.0, 0.0, 1.0], angle: 3.0, }; - let Ok(Curve::RationalSpline { knots, homogeneous }) = path(&m, [2.0, 0.0, 1.0], 1e-9) + let Ok(Curve::RationalSpline { knots, homogeneous }) = + path(&m, [2.0, 0.0, 1.0], 1e-9, 1e-9) else { panic!("no arc") }; @@ -1118,4 +1459,65 @@ mod tests { turn([0.0; 3], [0.0, 0.0, 1.0], 3.0, [2.0, 0.0, 1.0]) )); } + + /// A screw's path ends where the motion puts the point, and its middle keeps the point's + /// distance from the axis. + #[test] + fn a_screw_path_ends_where_the_motion_does() { + let m = Motion::Screw { + point: [0.0; 3], + axis: [0.0, 0.0, 1.0], + angle: 9.0, + rise: 5.0, + } + .checked() + .unwrap(); + let p = [3.0, 1.0, 2.0]; + let Ok(Curve::RationalSpline { homogeneous, .. }) = path(&m, p, 1e-9, 1e-7) else { + panic!("no path") + }; + let last = homogeneous.last().unwrap(); + assert!(close([last[0], last[1], last[2]], m.at(p, 1.0))); + assert!(homogeneous.len() > 13, "{} points", homogeneous.len()); + } + + /// A plane along the axis screwed: its characteristic plane is the turn's, moved off the + /// axis by the lead; a cone off the screw's axis is refused. + #[test] + fn a_screw_cuts_a_plane_and_refuses_an_offset_cone() { + let m = Motion::Screw { + point: [0.0; 3], + axis: [0.0, 0.0, 1.0], + angle: 1.0, + rise: 2.0, + }; + let reach = Reach { + points: &[[0.0; 3]], + bulge: 1.0, + }; + // the plane x + z = 0: n · v = (n × a) · x + 2 n · a = 0, n × a = (0, -1, 0)/√2 + let plane = Surface::Plane { + origin: [0.0; 3], + u_axis: [0.0, 1.0, 0.0], + v_axis: [1.0, 0.0, -1.0], + }; + let Ok(Characteristic::Cut(tools)) = characteristic(&plane, &m, reach) else { + panic!("no cut") + }; + let Some((Surface::Plane { origin, .. }, _)) = tools.first() else { + panic!("no plane") + }; + // -y · √2/2 ... : y = 2 (n · a) / |n × a| · ... the tool passes through y = ±2 + assert!((origin[1].abs() - 2.0).abs() < 1e-12, "{origin:?}"); + let cone = Surface::Cone { + frame: Frame { + origin: [5.0, 0.0, 0.0], + x_axis: [1.0, 0.0, 0.0], + y_axis: [0.0, 1.0, 0.0], + }, + radius_at_origin: 1.0, + half_angle: 0.3, + }; + assert_eq!(characteristic(&cone, &m, reach), Err(Refusal::ScrewOffAxis)); + } }