Skip to main content

brep_geometry/geometry/
analytic_surface.rs

1//! Analytic carrier recognition and closed-form geometry for the exact
2//! rational-NURBS surfaces the kernel builds by revolution.
3//!
4//! Every analytic surface in this kernel *is* an exact rational NURBS patch
5//! (built by `make_plane` / `make_revolution`), so recognition never changes
6//! geometry — it only unlocks closed-form fast paths (projection now, exact
7//! intersection curves next) that bypass grid seeding and Newton marching.
8//! Recognition is by exact reconstruction: candidate parameters are extracted
9//! from the control net, the surface is rebuilt with the same constructor,
10//! and every knot/control/weight must match to a scale-relative tolerance.
11//! A surface that fails reconstruction is simply not analytic — there are no
12//! partial matches and no approximation.
13
14pub use crate::{make_arc, make_revolution, NurbsCurve, NurbsSurface, SurfaceProjection, Vec3};
15
16const RECOGNITION_TOLERANCE: f64 = 1e-9;
17
18#[derive(Clone, Debug)]
19pub struct RevolutionFrame {
20    /// A point on the revolution axis.
21    pub origin: Vec3,
22    /// Unit axis direction; positive rotation follows the right-hand rule.
23    pub axis: Vec3,
24    /// Unit radial direction of the u = 0 meridian.
25    pub x_axis: Vec3,
26    /// axis × x_axis, so azimuth θ = atan2(d·y_axis, d·x_axis).
27    pub y_axis: Vec3,
28}
29
30impl RevolutionFrame {
31    /// Azimuth of `point` about the axis in [0, 2π), plus its radial
32    /// distance and signed axial coordinate relative to `origin`.
33    /// Returns `None` for the azimuth when the point lies on the axis.
34    fn cylindrical(&self, point: Vec3) -> (Option<f64>, f64, f64) {
35        let d = point.sub(self.origin);
36        let axial = d.dot(self.axis);
37        let radial_vector = d.sub(self.axis.scale(axial));
38        let radius = radial_vector.length();
39        if radius <= 1e-14 * (1.0 + axial.abs()) {
40            return (None, radius, axial);
41        }
42        let mut theta = radial_vector
43            .dot(self.y_axis)
44            .atan2(radial_vector.dot(self.x_axis));
45        if theta < 0.0 {
46            theta += std::f64::consts::TAU;
47        }
48        (Some(theta), radius, axial)
49    }
50}
51
52#[derive(Clone, Debug)]
53pub enum AnalyticSurface {
54    /// Affine patch: S(u,v) = origin + u·u_dir + v·v_dir over the knot domain.
55    Plane {
56        origin: Vec3,
57        u_dir: Vec3,
58        v_dir: Vec3,
59        u_domain: [f64; 2],
60        v_domain: [f64; 2],
61    },
62    /// Full revolution of a straight generatrix: cylinders (rho0 == rho1)
63    /// and cones/frusta, with v linear along the generatrix over [0, 1].
64    RuledRevolution {
65        frame: RevolutionFrame,
66        rho0: f64,
67        rho1: f64,
68        height: f64,
69    },
70    /// Full revolution of a -π/2..π/2 polar meridian arc (two 90° spans).
71    Sphere { frame: RevolutionFrame, radius: f64 },
72    /// Full revolution of a full tube circle (four 90° spans in v).
73    Torus {
74        frame: RevolutionFrame,
75        major_radius: f64,
76        minor_radius: f64,
77    },
78    /// GENERAL revolution (full or partial sweep) of an arbitrary
79    /// generatrix — every other `make_revolution` product the classic
80    /// quadric variants above do not cover.  The closest surface point to
81    /// a query lies in the query's meridian half-plane, so projection
82    /// reduces exactly to a 1D projection onto the generatrix (rotated
83    /// rigidly about the axis); out-of-sweep queries compare the two
84    /// boundary meridians instead (Golovanov §4.13: prefer analytic
85    /// constructions — this was the unrecognized carrier that sent
86    /// tangent glue pairs into the marcher).
87    Revolution {
88        frame: RevolutionFrame,
89        spans: usize,
90        sweep: f64,
91        generatrix: NurbsCurve,
92    },
93}
94
95impl AnalyticSurface {
96    /// A short, human-readable classification of this analytic carrier for the
97    /// Properties Info panel: `"Plane"`, `"Cylinder"`, `"Cone"`, `"Sphere"`,
98    /// `"Torus"`, or `"Surface of revolution"`. A `RuledRevolution` is a
99    /// cylinder when its two generatrix radii match (relative tolerance, same
100    /// style as recognition) and a cone otherwise — a zero end-radius apex is
101    /// still a cone, no special case needed. A partial-sweep revolve of a
102    /// straight profile recognizes as the general `Revolution` (not
103    /// `RuledRevolution`), so it reads "Surface of revolution" rather than
104    /// "Cylinder"/"Cone".
105    pub fn kind_label(&self) -> &'static str {
106        match self {
107            AnalyticSurface::Plane { .. } => "Plane",
108            AnalyticSurface::RuledRevolution { rho0, rho1, .. } => {
109                let scale = rho0.abs().max(rho1.abs()).max(1.0);
110                if (rho0 - rho1).abs() <= RECOGNITION_TOLERANCE * scale {
111                    "Cylinder"
112                } else {
113                    "Cone"
114                }
115            }
116            AnalyticSurface::Sphere { .. } => "Sphere",
117            AnalyticSurface::Torus { .. } => "Torus",
118            AnalyticSurface::Revolution { .. } => "Surface of revolution",
119        }
120    }
121}
122
123/// Parameter of the standard tangent-intersection rational quadratic arc
124/// construction (`make_arc` / `make_revolution`): a sweep split uniformly
125/// into `spans` segments, each with middle weight cos(segment/2).  Maps an
126/// angle in [0, sweep] to the curve parameter in [0, 1] exactly.
127pub fn circle_angle_to_parameter(spans: usize, sweep: f64, angle: f64) -> f64 {
128    let segment = sweep / spans as f64;
129    let clamped = angle.clamp(0.0, sweep);
130    let mut span = (clamped / segment).floor() as usize;
131    if span >= spans {
132        span = spans - 1;
133    }
134    let local = clamped - span as f64 * segment;
135    // Derived from tan(θ/2) = t·sin(α/2) / (1 − t + t·cos(α/2)) for the
136    // symmetric rational quadratic arc of sweep α: exact, monotone, and
137    // singularity-free for α ≤ π/2.
138    let half = (0.5 * local).tan();
139    let s = (0.5 * segment).sin();
140    let c = (0.5 * segment).cos();
141    let t = half / (s + half * (1.0 - c));
142    (span as f64 + t.clamp(0.0, 1.0)) / spans as f64
143}
144
145#[path = "analytic_surface/recognition.rs"]
146mod recognition;
147#[path = "analytic_surface/intersect.rs"]
148mod intersect;
149#[path = "analytic_surface/sphere_cylinder_tangent.rs"]
150mod sphere_cylinder_tangent;
151#[path = "analytic_surface/revolution.rs"]
152mod revolution;
153
154pub use intersect::{intersect_analytic_pair, plane_ruled_section_arc};
155pub use intersect::{intersect_analytic_pair_with, ruled_gate, ruled_gate_census, RuledGate};
156pub use recognition::recognize;
157#[path = "analytic_surface/extrusion.rs"]
158mod extrusion;
159pub use extrusion::{extrusion_structure, plane_extrusion_section, parallel_extrusion_sections, ExtrusionStructure};
160pub(crate) use extrusion::ReducedProfile;
161pub use revolution::{revolution_structure, RevolutionStructure};
162pub use revolution::circumcenter;
163pub use recognition::generatrix_is_meridional_half_ray;
164
165/// `BREP_REVOLUTION_HELD_GENERATRIX` (default on; `=0` reads the generatrix
166/// afresh every call): a general revolution's closed form projects onto the
167/// generatrix held on its surface ([`NurbsSurface::held_revolution_generatrix`])
168/// with its seed samples, for the same answer, bit for bit, as projecting onto
169/// the bare curve, which hashes the curve's content into the seed cache on
170/// every call. The meridional test the closed form needs is held with it.
171fn held_generatrix_enabled() -> bool {
172    crate::switch!("BREP_REVOLUTION_HELD_GENERATRIX", true)
173}
174
175impl AnalyticSurface {
176    /// Closed-form point projection in the surface's own parameterization.
177    /// Returns the exact nearest parameter; the caller evaluates the NURBS at
178    /// that parameter so results stay bit-consistent with the carrier.
179    pub fn project(&self, surface: &NurbsSurface, point: Vec3) -> Option<SurfaceProjection> {
180        let (u, v) = match self {
181            AnalyticSurface::Plane {
182                origin,
183                u_dir,
184                v_dir,
185                u_domain,
186                v_domain,
187            } => {
188                // Least-squares foot on the (possibly non-orthogonal) affine
189                // patch, clamped to the trimmed domain.
190                let d = point.sub(*origin);
191                let a = u_dir.dot(*u_dir);
192                let b = u_dir.dot(*v_dir);
193                let c = v_dir.dot(*v_dir);
194                let determinant = a * c - b * b;
195                if determinant.abs() <= 1e-16 * (a * c).max(1.0) {
196                    return None;
197                }
198                let fu = u_dir.dot(d);
199                let fv = v_dir.dot(d);
200                let u =
201                    ((fu * c - fv * b) / determinant + u_domain[0]).clamp(u_domain[0], u_domain[1]);
202                let v =
203                    ((fv * a - fu * b) / determinant + v_domain[0]).clamp(v_domain[0], v_domain[1]);
204                (u, v)
205            }
206            AnalyticSurface::RuledRevolution {
207                frame,
208                rho0,
209                rho1,
210                height,
211            } => {
212                let (theta, rho, z) = frame.cylindrical(point);
213                let u = theta
214                    .map(|angle| circle_angle_to_parameter(4, std::f64::consts::TAU, angle))
215                    .unwrap_or(0.0);
216                // 2D meridian problem: project (rho, z) onto the generatrix
217                // segment (rho0, 0) -> (rho1, height).
218                let delta_rho = rho1 - rho0;
219                let length_squared = delta_rho * delta_rho + height * height;
220                let t = (((rho - rho0) * delta_rho + z * height) / length_squared).clamp(0.0, 1.0);
221                (u, t)
222            }
223            AnalyticSurface::Sphere { frame, radius: _ } => {
224                let (theta, rho, z) = frame.cylindrical(point);
225                let u = theta
226                    .map(|angle| circle_angle_to_parameter(4, std::f64::consts::TAU, angle))
227                    .unwrap_or(0.0);
228                // Polar angle from the south pole: β ∈ [0, π] over two spans.
229                let beta = rho.atan2(-z);
230                let v = circle_angle_to_parameter(2, std::f64::consts::PI, beta);
231                (u, v)
232            }
233            AnalyticSurface::Torus {
234                frame,
235                major_radius,
236                minor_radius: _,
237            } => {
238                let (theta, rho, z) = frame.cylindrical(point);
239                let u = theta
240                    .map(|angle| circle_angle_to_parameter(4, std::f64::consts::TAU, angle))
241                    .unwrap_or(0.0);
242                let mut psi = z.atan2(rho - major_radius);
243                if psi < 0.0 {
244                    psi += std::f64::consts::TAU;
245                }
246                let v = circle_angle_to_parameter(4, std::f64::consts::TAU, psi);
247                (u, v)
248            }
249            AnalyticSurface::Revolution {
250                frame,
251                spans,
252                sweep,
253                generatrix,
254            } => {
255                // The surface's own revolution projects through its held generatrix:
256                // the same seed samples, read without hashing the curve on every call.
257                let held = if held_generatrix_enabled() { surface.held_revolution_generatrix(self) } else { None };
258                let held = match held {
259                    Some(held) => Some(held?),
260                    None if !generatrix_is_meridional_half_ray(generatrix, frame) => return None,
261                    None => None,
262                };
263                let (theta, rho, z) = frame.cylindrical(point);
264                let full = *sweep >= std::f64::consts::TAU - 1e-9;
265                // Rotating the query rigidly about the axis to a meridian
266                // preserves its distance to that meridian's generatrix copy,
267                // so each candidate reduces to a 1D curve projection.
268                let point_at_angle = |angle: f64| {
269                    let radial = frame
270                        .x_axis
271                        .scale(angle.cos())
272                        .add(frame.y_axis.scale(angle.sin()));
273                    frame.origin.add(radial.scale(rho)).add(frame.axis.scale(z))
274                };
275                let mut candidates: Vec<(f64, Vec3)> = Vec::with_capacity(2);
276                match theta {
277                    None => candidates.push((0.0, point)),
278                    Some(angle) if full || angle <= *sweep => {
279                        // Rotate the query to the generatrix meridian (angle 0).
280                        candidates.push((
281                            circle_angle_to_parameter(*spans, *sweep, angle),
282                            point_at_angle(0.0),
283                        ));
284                    }
285                    Some(angle) => {
286                        // Outside the sweep: the minimizer sits on one of the
287                        // two boundary meridians; compare both.  The start
288                        // meridian IS the generatrix, so the original point
289                        // projects onto it directly; the end meridian maps to
290                        // the generatrix by a rigid rotation of the query.
291                        candidates.push((0.0, point));
292                        candidates.push((1.0, point_at_angle(angle - *sweep)));
293                    }
294                }
295                let mut best: Option<(f64, f64, f64)> = None;
296                for (u, query) in candidates {
297                    let projection = match held {
298                        Some(held) => held.project(query),
299                        None => crate::project_point_to_curve(generatrix, query),
300                    };
301                    let Ok(projection) = projection else {
302                        return None;
303                    };
304                    if best
305                        .map(|(_, _, distance)| projection.distance < distance)
306                        .unwrap_or(true)
307                    {
308                        best = Some((u, projection.u, projection.distance));
309                    }
310                }
311                let (u, v, _) = best?;
312                (u, v)
313            }
314        };
315        let projected = surface.evaluate(u, v).ok()?;
316        Some(SurfaceProjection {
317            u,
318            v,
319            point: projected,
320            distance: projected.sub(point).length(),
321        })
322    }
323
324    /// True when the closed-form projection is the exact global minimizer
325    /// (everywhere except on-axis queries, where any meridian ties).
326    pub fn frame(&self) -> Option<&RevolutionFrame> {
327        match self {
328            AnalyticSurface::Plane { .. } => None,
329            AnalyticSurface::RuledRevolution { frame, .. }
330            | AnalyticSurface::Sphere { frame, .. }
331            | AnalyticSurface::Torus { frame, .. }
332            | AnalyticSurface::Revolution { frame, .. } => Some(frame),
333        }
334    }
335}
336
337pub use recognition::curve_scale;
338
339/// Circumcenter in a plane, with a scale-relative degeneracy guard.
340pub fn circumcenter_2d(a: [f64; 2], b: [f64; 2], c: [f64; 2]) -> Option<[f64; 2]> {
341    let scale = (b[0] - a[0]).abs().max((b[1] - a[1]).abs())
342        .max((c[0] - a[0]).abs()).max((c[1] - a[1]).abs());
343    let d = 2.0 * (a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]));
344    if !d.is_finite() || d.abs() <= 1e-12 * scale * scale { return None; }
345    let aa = a[0] * a[0] + a[1] * a[1];
346    let bb = b[0] * b[0] + b[1] * b[1];
347    let cc = c[0] * c[0] + c[1] * c[1];
348    Some([
349        (aa * (b[1] - c[1]) + bb * (c[1] - a[1]) + cc * (a[1] - b[1])) / d,
350        (aa * (c[0] - b[0]) + bb * (a[0] - c[0]) + cc * (b[0] - a[0])) / d,
351    ])
352}
353
354#[derive(Clone, Copy, Debug)]
355pub struct RecognizedCircle {
356    pub centre: Vec3,
357    pub axis: Vec3,
358    pub radius: f64,
359    /// Largest sampled radial or planar residual in model units.
360    pub worst: f64,
361}
362
363/// Sampled circle recognition; this does not certify exact NURBS equivalence.
364pub fn recognize_circle(curve: &NurbsCurve, t0: f64, t1: f64, tolerance: f64) -> Option<RecognizedCircle> {
365    if !(tolerance >= 0.0) || !t0.is_finite() || !t1.is_finite() || t0 == t1 {
366        return None;
367    }
368    let a = curve.evaluate(t0).ok()?;
369    let b = curve.evaluate(t0 + (t1 - t0) / 3.0).ok()?;
370    let c = curve.evaluate(t0 + 2.0 * (t1 - t0) / 3.0).ok()?;
371    let centre = circumcenter(a, b, c)?;
372    let normal = b.sub(a).cross(c.sub(a));
373    let axis = normal.scale(1.0 / normal.length());
374    let radius = a.sub(centre).length();
375    if !(radius > 0.0) || !radius.is_finite() { return None; }
376    let mut worst = 0.0_f64;
377    for i in 0..=64 {
378        let d = curve.evaluate(t0 + (t1 - t0) * i as f64 / 64.0).ok()?.sub(centre);
379        let error = (d.length() - radius).abs().max(d.dot(axis).abs());
380        if !error.is_finite() || error > tolerance { return None; }
381        worst = worst.max(error);
382    }
383    Some(RecognizedCircle { centre, axis, radius, worst })
384}
385