Skip to main content

axiolid_construct/
revolve.rs

1//! Revolution of a profile about an axis.
2//!
3//! The profile is flattened to rings in its own plane, then each ring point
4//! is rotated about the axis in steps chosen by the chord budget. A full
5//! turn closes on itself; a partial turn is capped by the profile at each
6//! end.
7//!
8//! Pappus gives the oracle: a full revolution has volume `2*pi*R*A`, where
9//! `R` is the centroid's distance from the axis and `A` the profile area.
10//!
11//! # How far the walls sit from the surface (#231)
12//!
13//! [`revolve`] bounds the distance from every point of the surface swept by
14//! the GIVEN rings to its triangles by `tolerance.linear()`. Rings that
15//! chord a curved profile add their own deviation on top: a caller that
16//! wants the exact surface of revolution within a budget `c` flattens the
17//! profile to `c_p` and revolves to `c - c_p`. The reference compiler takes
18//! half each, which minimises the triangle count for a fixed sum: the steps
19//! round the profile and round the axis each grow as the inverse square
20//! root of their share, so their product is smallest at an even split. The
21//! two shares add because a rotation is an isometry: a point of the exact
22//! surface is the rotation of a profile point within `c_p` of the ring
23//! polygon, so it is within `c_p` of the same rotation of the polygon.
24//!
25//! Each ring segment `q_a -> q_b` sweeps, between the stations at angles
26//! `t` and `t + h`, the surface `R(s) q(x)` with `q(x) = (1-x) q_a + x q_b`.
27//! For fixed `x` the point `R(s) q(x)` runs along an arc of radius
28//! `rho(x)`, its distance from the axis, and the chord between the arc's
29//! ends is the row at `x` of the bilinear patch over the quad
30//! `R(t) q_a, R(t) q_b, R(t+h) q_a, R(t+h) q_b` (a rotation is linear in
31//! the point). An arc of angle `h` stays within its sagitta
32//! `rho (1 - cos(h/2))` of its chord, and `rho(x)` is the norm of an affine
33//! function, so convex in `x` and largest at a ring vertex: every point of
34//! the swept surface is within `rho_max (1 - cos(h/2))` of the patch, with
35//! `rho_max` the largest vertex distance from the axis over every ring --
36//! the outer equator, for a torus, never the tube centre. The patch is in
37//! turn within `loft::quad_deviation` of the two triangles the
38//! loft cuts it into. When the axis lies in the profile's plane every quad
39//! is a planar trapezoid (its two chords are images of parallel radial
40//! vectors under the same `R(t+h) - R(t)`), convex while the segment stays
41//! on one side of the axis, and that term is zero: the bound is the sagitta
42//! alone, whatever the sign of the Gaussian curvature (the inner side of a
43//! torus is saddle-shaped, but its trapezoids are still flat). An axis off
44//! the profile's plane sweeps hyperboloidal quads; their measured twist is
45//! added, and the step shrinks until the sum fits.
46//!
47//! Every span of a revolution is the first span rotated, so the twist is
48//! measured once.
49
50use axiolid_contracts::{GeomError, GeomResult, Operation};
51use axiolid_core::{Point2, Point3, Scalar, Tolerance, Vec3};
52use axiolid_guarantees::Sign;
53use axiolid_mesh::TriMesh;
54use axiolid_predicates::arithmetic::{expansion_sign, expansion_sum};
55use axiolid_predicates::two_product;
56
57use crate::profile::Rings;
58
59/// The most steps a revolution or a circle takes before it refuses the
60/// budget, rather than meet it with a coarser mesh that breaks the bound
61/// the caller asked for.
62pub(crate) const MAX_STEPS: usize = 4096;
63
64/// Rotation of `p` about the axis through `origin` along unit `dir`.
65///
66/// Rodrigues' formula. Written out rather than pulled from a matrix type
67/// so the axis stays arbitrary: a revolution is not a Z-up operation.
68pub(crate) fn rotate(p: Point3, origin: Point3, dir: Vec3, angle: Scalar) -> Point3 {
69    let v = p - origin;
70    let (s, c) = angle.sin_cos();
71    origin + v * c + dir.cross(v) * s + dir * (dir.dot(v) * (1.0 - c))
72}
73
74/// Angular steps so the swept arc meets the chord budget.
75///
76/// The widest point of the profile governs: a ring point at distance `r`
77/// from the axis traces a circle of that radius, and its sagitta is
78/// `r(1 - cos(dtheta/2))`. Using the maximum radius means every other
79/// point is sampled at least as finely. A budget that needs more than
80/// [`MAX_STEPS`] steps is refused, never met by fewer.
81pub(crate) fn steps(max_radius: Scalar, angle: Scalar, tol: Scalar) -> GeomResult<usize> {
82    if !(tol.is_finite() && tol > 0.0) {
83        return Err(GeomError::InvalidInput(format!(
84            "chord budget must be positive and finite, got {tol}"
85        )));
86    }
87    if !(max_radius.is_finite() && max_radius > 0.0) {
88        return Ok(8);
89    }
90    let ratio = (1.0 - (tol / max_radius).min(1.0)).clamp(-1.0, 1.0);
91    let per = 2.0 * ratio.acos();
92    let n = (angle.abs() / per).ceil();
93    // NaN (a zero step) counts as too many.
94    if n.is_nan() || n > MAX_STEPS as Scalar {
95        return Err(too_many_steps());
96    }
97    Ok((n as usize).max(2))
98}
99
100/// The refusal for a budget that needs more than [`MAX_STEPS`] steps.
101pub(crate) fn too_many_steps() -> GeomError {
102    GeomError::BudgetExceeded {
103        resource: "revolution angular steps",
104    }
105}
106
107/// The next step count to try when `n` misses the budget: a quarter more,
108/// so a near miss costs little and a far one converges in a few rounds.
109pub(crate) fn grow(n: usize) -> GeomResult<usize> {
110    let next = n + n / 4 + 1;
111    if next > MAX_STEPS {
112        return Err(too_many_steps());
113    }
114    Ok(next)
115}
116
117/// Steps for a revolution of `rings` through `angle` whose walls stay
118/// within `budget` of the surface the rings sweep (see the module notes).
119fn bounded_steps(
120    rings: &Rings,
121    axis_origin: Point3,
122    dir: Vec3,
123    angle: Scalar,
124    max_r: Scalar,
125    budget: Scalar,
126) -> GeomResult<usize> {
127    let at = |t: Scalar| {
128        crate::loft::place(rings, |p| {
129            rotate(Point3::new(p.x, p.y, 0.0), axis_origin, dir, t)
130        })
131    };
132    let mut n = steps(max_r, angle, budget)?;
133    loop {
134        let h = angle / n as Scalar;
135        let sagitta = max_r * (1.0 - (0.5 * h).cos());
136        // The loft walks the stations from the far end back, so each span
137        // runs from angle `t + h` to `t`; every span is this one rotated.
138        let twist = crate::loft::span_deviation(&at(h), &at(0.0));
139        if sagitta + twist <= budget {
140            return Ok(n);
141        }
142        n = grow(n)?;
143    }
144}
145
146/// Exact sign of `d x (p - a)`, the side of `p` of the line through `a`
147/// along `d`: `d.x*p.y - d.x*a.y - d.y*p.x + d.y*a.x`, summed as expansions.
148///
149/// Not `orient2d(a, a + d, p)`: `a + d` rounds, which tilts the line it
150/// decides against.
151fn side_of_axis(a: Point2, d: Vec3, p: Point2) -> Sign {
152    let term = |x: Scalar, y: Scalar, negate: bool| {
153        let (product, error) = two_product(x, y);
154        if negate {
155            [-error, -product]
156        } else {
157            [error, product]
158        }
159    };
160    let mut sum = expansion_sum(&term(d.x, p.y, false), &term(d.x, a.y, true));
161    sum = expansion_sum(&sum, &term(d.y, p.x, true));
162    sum = expansion_sum(&sum, &term(d.y, a.x, false));
163    expansion_sign(&sum)
164}
165
166/// Refuse rings that lie on both sides of the axis, or touch it (#351).
167///
168/// Decided when the axis lies in the profile's plane, where "side" is
169/// meaningful: each vertex is classified by the exact sign of its cross
170/// product with the axis direction, with no tolerance band. Vertices
171/// strictly on both sides are a crossing (the swept solid passes through
172/// itself) and `InvalidInput`; a vertex on the axis, which includes an edge
173/// lying on it, collapses the swept wall to a line and is
174/// `UnsupportedInput`, as in the exact path (`revolve_exact`). An edge
175/// cannot meet the axis between two vertices without one of those two
176/// cases.
177///
178/// "In the plane" follows the exact path: the axis origin and direction
179/// leave it only beyond `tolerance.linear()` in z, so placement noise does
180/// not switch the check off. An axis parallel to the plane but offset from
181/// it is checked for crossing only: no ring point reaches the axis, since
182/// its radius stays at least the offset. An axis leaning out of the plane
183/// is unchecked and tracked in #362.
184pub(crate) fn check_axis_side(
185    rings: &Rings,
186    axis_origin: Point3,
187    axis_direction: Vec3,
188    tolerance: Tolerance,
189) -> GeomResult<()> {
190    // TODO(#362): an axis leaning out of the profile plane is not judged.
191    if axis_direction.z.abs() > tolerance.linear() * axis_direction.length() {
192        return Ok(());
193    }
194    let offset = axis_origin.z.abs() > tolerance.linear();
195    let a = Point2::new(axis_origin.x, axis_origin.y);
196    let (mut positive, mut negative, mut on_axis) = (false, false, false);
197    for p in rings.outer.iter().chain(rings.holes.iter().flatten()) {
198        if !(p.x.is_finite() && p.y.is_finite()) {
199            return Err(GeomError::InvalidInput(
200                "revolved profile must have finite vertices".to_owned(),
201            ));
202        }
203        match side_of_axis(a, axis_direction, *p) {
204            Sign::Positive => positive = true,
205            Sign::Negative => negative = true,
206            _ => on_axis = true,
207        }
208    }
209    if positive && negative {
210        return Err(GeomError::InvalidInput(
211            "revolved profile crosses the axis: its rings lie on both sides".to_owned(),
212        ));
213    }
214    if on_axis && !offset {
215        return Err(GeomError::UnsupportedInput {
216            backend: crate::BACKEND_ID,
217            operation: Operation::Sweep,
218            input: "revolution of a profile touching the axis",
219        });
220    }
221    Ok(())
222}
223
224/// Revolve a profile about an axis into a closed solid.
225///
226/// A full turn wraps its rings by index, so the seam shares vertices by
227/// construction rather than by two samplings agreeing numerically. That is
228/// the same structure `tessellate_primitive` uses for a cylinder, and it
229/// avoids the trim-based path recorded as broken in issue #2.
230///
231/// Every point of the surface the rings sweep lies within
232/// `tolerance.linear()` of the mesh (see the module notes for the proof);
233/// the rings' own distance from a curved profile is the caller's to add.
234/// A budget that needs more than 4096 steps round the axis is refused with
235/// `BudgetExceeded`. A profile with vertices on both sides of an in-plane
236/// axis is `InvalidInput`; one touching the axis is `UnsupportedInput`.
237pub fn revolve(
238    rings: &Rings,
239    axis_origin: Point3,
240    axis_direction: Vec3,
241    angle: Scalar,
242    tolerance: Tolerance,
243) -> GeomResult<TriMesh> {
244    if !angle.is_finite() || angle == 0.0 {
245        return Err(GeomError::InvalidInput(format!(
246            "revolution angle must be finite and non-zero, got {angle}"
247        )));
248    }
249    let len = axis_direction.length();
250    if !len.is_finite() || len <= 0.0 {
251        return Err(GeomError::InvalidInput(
252            "revolution axis must be a finite non-zero direction".to_owned(),
253        ));
254    }
255    check_axis_side(rings, axis_origin, axis_direction, tolerance)?;
256    let dir = axis_direction / len;
257    // Widest distance from the axis governs the angular step: a point at
258    // radius r traces a circle of that radius.
259    let mut max_r: Scalar = 0.0;
260    for p in rings.outer.iter().chain(rings.holes.iter().flatten()) {
261        let v = Point3::new(p.x, p.y, 0.0) - axis_origin;
262        max_r = max_r.max((v - dir * dir.dot(v)).length());
263    }
264    let full = (angle.abs() - core::f64::consts::TAU).abs() <= 1e-9;
265    let n = bounded_steps(rings, axis_origin, dir, angle, max_r, tolerance.linear())?;
266    // A full turn emits n stations and wraps onto the first; a partial turn
267    // emits n + 1 so both ends exist to be capped.
268    let count = if full { n } else { n + 1 };
269    let stations: Vec<crate::loft::Station> = (0..count)
270        .rev()
271        .map(|s| {
272            let t = angle * (s as Scalar) / (n as Scalar);
273            crate::loft::place(rings, |p| {
274                rotate(Point3::new(p.x, p.y, 0.0), axis_origin, dir, t)
275            })
276        })
277        .collect();
278    let mut mesh = crate::loft::loft(rings, &stations, full)?;
279    // The station order above (end of the sweep first) winds the walls
280    // outward for a positive angle about `dir`. A negative angle sweeps the
281    // other way round, so the same order winds them inward instead (#221):
282    // `angle` and `dir` only matter through their product (the axis-angle
283    // rotation vector), and `(dir, angle)` and `(-dir, -angle)` describe the
284    // identical rotation, so the fix cannot key off `angle`'s stored sign
285    // alone without also depending on `dir`'s. Settling it from the built
286    // mesh's own orientation sidesteps that: whichever combination produced
287    // it, a closed solid's sign is unambiguous.
288    if matches!(crate::extrude::outward_orientation(&mesh), Some(false)) {
289        for triangle in mesh.indices.as_chunks_mut::<3>().0 {
290            triangle.swap(1, 2);
291        }
292    }
293    Ok(mesh)
294}