Skip to main content

brep_geometry/geometry/
surface.rs

1use crate::curve::{
2    basis_derivatives_wide as basis_derivatives_into, basis_functions_wide as basis_functions_into,
3    knot_clamp, knot_domain, knot_find_span,
4    validate_knots, EVALUATOR_STACK_DEGREE as MAX_STACK_DEGREE,
5    EVALUATOR_STACK_ORDER as MAX_STACK_ORDER,
6};
7pub use crate::{KnotVector, NurbsCurve, Vec3, Vec4};
8use serde::{Deserialize, Serialize};
9
10#[path = "surface/extension.rs"]
11mod extension;
12#[path = "surface/trim_partials.rs"]
13mod trim_partials;
14#[path = "surface/refine.rs"]
15mod refine;
16pub use refine::{KnotDirection, KnotRefinementRefusal};
17pub use trim_partials::PreparedTrimPartials;
18pub use extension::{
19    ExtendRefusal, SurfaceSide, WeightSite, MAXIMUM_FOLD_ANGLE, MAXIMUM_GROWTH_RATIO,
20};
21
22const EPS: f64 = crate::tolerance::FP_FLOOR;
23/// A generatrix control point that is neither ON the axis of revolution nor
24/// this fraction of the generatrix's own radial extent clear of it is a fuzzy
25/// pole, and `make_revolution` refuses it (see the comment at the check).
26const NEAR_AXIS_RELATIVE_TOLERANCE: f64 = 1e-4;
27
28/// The widest tensor block [`NurbsSurface::deriv1_tensor_each`] will evaluate,
29/// per direction. The mass integrator reads a RATIONAL patch's cell at up to
30/// this many stations; `props::mass_properties::rule::MAX_ORDER` is DEFINED as
31/// this constant rather than repeating its value, because the block's arrays
32/// here and the station arrays there must agree and a drift between them is a
33/// hard failure, not a slow path (the callers propagate the refusal below
34/// rather than falling back). 8 was the fixed rule's own width; the arrays are
35/// stack-resident either way.
36pub const TENSOR_MAX_BLOCK: usize = 24;
37
38/// `BREP_SURFACE_TENSOR_FUSED` (default on): [`NurbsSurface::deriv1_tensor_each`]
39/// runs a patch of degrees 1 to 3 in each direction through its
40/// constant-degree loop, the same bits; `=0` keeps the run-time-degree loop,
41/// for a same-binary A/B.
42fn tensor_fused_on() -> bool {
43    switch!("BREP_SURFACE_TENSOR_FUSED", true)
44}
45
46/// A rational B-spline surface.
47///
48/// **Invariant: do not mutate the public fields after the surface has been
49/// evaluated.** The surface memoizes derived data (its analytic carrier, seam
50/// closure, projection grids, validation) the first time it is asked, and
51/// `Clone` copies those caches. Editing `control_points`, `knots_*` or a degree
52/// in place afterwards leaves every later query answering for the OLD
53/// geometry. Build a new value with [`NurbsSurface::new`] instead (lane K2
54/// audit 2026-10-16: no production path does this today; a test fixture did).
55#[derive(Clone, Debug, Deserialize, Serialize)]
56pub struct NurbsSurface {
57    pub degree_u: usize,
58    pub degree_v: usize,
59    pub knots_u: Vec<f64>,
60    pub knots_v: Vec<f64>,
61    pub control_points: Vec<Vec<Vec4>>,
62    /// Lazily recognized analytic carrier (plane/cylinder/cone/sphere/torus).
63    /// Purely an acceleration cache: never serialized, cloned with the
64    /// surface, and recomputed on demand after deserialization.
65    #[serde(skip, default)]
66    pub analytic: std::cell::OnceCell<Option<crate::AnalyticSurface>>,
67    /// Translation structure, queried independently of the classic analytic
68    /// enum so adding this carrier does not break exhaustive API matches.
69    #[serde(skip, default)]
70    linear_extrusion: std::cell::OnceCell<Option<crate::analytic_surface::ExtrusionStructure>>,
71    /// The extrusion's profile reduced across its direction, with its seed samples
72    /// (`BREP_EXTRUSION_HELD_PROFILE`); built from `linear_extrusion` on first use.
73    #[serde(skip, default)]
74    extrusion_profile: std::cell::OnceCell<Option<crate::analytic_surface::ReducedProfile>>,
75    /// Lazily recognized affine sphere (`geometry/affine_sphere.rs`), read
76    /// only under `BREP_AFFINE_SPHERE` and only when no analytic carrier was
77    /// recognized; an acceleration cache like `analytic`.
78    #[serde(skip, default)]
79    affine_sphere: std::cell::OnceCell<Option<crate::affine_sphere::AffineSphere>>,
80    /// One-time validation cache (see `NurbsCurve::ensure_valid`).
81    #[serde(skip, default)]
82    validated: std::cell::Cell<bool>,
83    /// Cached (closed_u, closed_v) seam test — a pure function of the
84    /// immutable geometry, recomputed on demand after deserialization.
85    #[serde(skip, default)]
86    closed_directions: std::cell::OnceCell<(bool, bool)>,
87    /// Cached Newton seed grid for general point projection (see
88    /// `projection.rs`) — (u, v, point) samples over the knot spans.
89    #[serde(skip, default)]
90    pub projection_grid: std::cell::OnceCell<crate::projection::SampleGrid>,
91    /// Cached dense fallback grid for degenerate general projection
92    /// (`projection.rs`) — (u, v, point) samples at fixed per-surface
93    /// parameters, so the ~1.7M-call metre-mm fallback reuses the evals.
94    #[serde(skip, default)]
95    pub projection_dense_grid: std::cell::OnceCell<crate::projection::SampleGrid>,
96    /// Cached boundary-ring sample points for the degenerate projection
97    /// fallback (`projection.rs`), flattened as 4 sides × 22 exponents ×
98    /// 33 indices of evaluated surface points at fixed per-surface params.
99    #[serde(skip, default)]
100    pub projection_ring_grid: std::cell::OnceCell<Vec<Vec3>>,
101    /// Cached convex-hull enclosure of every projection lattice cell
102    /// (`projection.rs`'s global stage), built on the first query the local
103    /// answer does not already settle. `None` when the net cannot be refined.
104    #[serde(skip, default)]
105    pub projection_cells: std::cell::OnceCell<Option<crate::projection::ProjectionCells>>,
106    /// Cached Bézier patches and their hull boxes for the curve-clear proof
107    /// (`intersect/curve_clear.rs`), built on its first query of this surface.
108    #[serde(skip, default)]
109    pub(crate) bezier_patches: std::cell::OnceCell<Option<std::sync::Arc<crate::curve_clear::SurfacePatches>>>,
110}
111
112impl NurbsSurface {
113    pub fn new(
114        degree_u: usize,
115        degree_v: usize,
116        knots_u: Vec<f64>,
117        knots_v: Vec<f64>,
118        control_points: Vec<Vec<Vec4>>,
119    ) -> Result<Self, String> {
120        let surface = Self {
121            degree_u,
122            degree_v,
123            knots_u,
124            knots_v,
125            control_points,
126            analytic: std::cell::OnceCell::new(),
127            linear_extrusion: std::cell::OnceCell::new(),
128            extrusion_profile: std::cell::OnceCell::new(),
129            affine_sphere: std::cell::OnceCell::new(),
130            validated: std::cell::Cell::new(false),
131            closed_directions: std::cell::OnceCell::new(),
132            projection_grid: std::cell::OnceCell::new(),
133            projection_dense_grid: std::cell::OnceCell::new(),
134            projection_ring_grid: std::cell::OnceCell::new(),
135            projection_cells: std::cell::OnceCell::new(),
136            bezier_patches: std::cell::OnceCell::new(),
137        };
138        surface.ensure_valid()?;
139        Ok(surface)
140    }
141
142    /// Whether the surface joins itself along u (first) and v (second):
143    /// opposite domain edges coincide at three sampled fractions. The 1e-6
144    /// threshold matches the historical `LINEAR_TOLERANCE * 10` used by the
145    /// projection and curve×surface intersection modules.
146    pub fn closed_directions(&self) -> Result<(bool, bool), String> {
147        if let Some(&cached) = self.closed_directions.get() {
148            return Ok(cached);
149        }
150        const CLOSED_SEAM_TOLERANCE: f64 = 1e-6;
151        let [u0, u1] = self.domain_u()?;
152        let [v0, v1] = self.domain_v()?;
153        let closed_along = |direction_u: bool| -> Result<bool, String> {
154            // A direction whose two boundary rows coincide is closed only if
155            // the surface TRAVELS between them: a sliver patch narrower than
156            // the seam tolerance (a 7.24e-7-wide plane our own STL→STEP writer
157            // emits for a degenerate facet, 2026-09-26) has coincident rows
158            // too, and reading it as periodic wraps its far edge onto its near
159            // one — `evaluate_extended` then images a trim on that edge a
160            // whole patch width away.
161            let mut travels = false;
162            for fraction in [0.17, 0.5, 0.83] {
163                let (a, b, middle) = if direction_u {
164                    let v = v0 + (v1 - v0) * fraction;
165                    (
166                        self.evaluate(u0, v)?,
167                        self.evaluate(u1, v)?,
168                        self.evaluate(0.5 * (u0 + u1), v)?,
169                    )
170                } else {
171                    let u = u0 + (u1 - u0) * fraction;
172                    (
173                        self.evaluate(u, v0)?,
174                        self.evaluate(u, v1)?,
175                        self.evaluate(u, 0.5 * (v0 + v1))?,
176                    )
177                };
178                if a.sub(b).length() > CLOSED_SEAM_TOLERANCE {
179                    return Ok(false);
180                }
181                if middle.sub(a).length() > CLOSED_SEAM_TOLERANCE {
182                    travels = true;
183                }
184            }
185            Ok(travels)
186        };
187        let value = (closed_along(true)?, closed_along(false)?);
188        Ok(*self.closed_directions.get_or_init(|| value))
189    }
190
191    /// The full construction-time checks, run at most once per instance.
192    fn ensure_valid(&self) -> Result<(), String> {
193        if self.validated.get() {
194            return Ok(());
195        }
196        validate_knots(&self.knots_u, self.degree_u)?;
197        validate_knots(&self.knots_v, self.degree_v)?;
198        let rows = self.knots_u.len() - self.degree_u - 1;
199        let columns = self.knots_v.len() - self.degree_v - 1;
200        if self.control_points.len() != rows {
201            return Err(format!(
202                "NurbsSurface: u knot vector implies {} rows, got {}",
203                rows,
204                self.control_points.len()
205            ));
206        }
207        for row in &self.control_points {
208            if row.len() != columns {
209                return Err(format!(
210                    "NurbsSurface: v knot vector implies {} columns, got {}",
211                    columns,
212                    row.len()
213                ));
214            }
215            if row.iter().any(|point| {
216                point.w <= EPS
217                    || ![point.x, point.y, point.z, point.w]
218                        .iter()
219                        .all(|value| value.is_finite())
220            }) {
221                return Err(
222                    "NurbsSurface: control points must be finite with positive weights".into(),
223                );
224            }
225        }
226        self.validated.set(true);
227        Ok(())
228    }
229
230    pub fn domain_u(&self) -> Result<[f64; 2], String> {
231        self.ensure_valid()?;
232        Ok(knot_domain(&self.knots_u, self.degree_u))
233    }
234
235    pub fn domain_v(&self) -> Result<[f64; 2], String> {
236        self.ensure_valid()?;
237        Ok(knot_domain(&self.knots_v, self.degree_v))
238    }
239
240    /// Exact affine translation structure in this surface's own chart.
241    pub fn linear_extrusion(&self) -> Option<&crate::analytic_surface::ExtrusionStructure> {
242        self.linear_extrusion.get_or_init(|| crate::analytic_surface::extrusion_structure(self)).as_ref()
243    }
244
245    /// The held reduced profile of `extrusion` when it is this surface's own recognized
246    /// structure (`Some(None)` when it cannot be reduced); `None` for any other structure.
247    pub(crate) fn held_extrusion_profile(&self, extrusion: &crate::analytic_surface::ExtrusionStructure) -> Option<Option<&crate::analytic_surface::ReducedProfile>> {
248        let own = self.linear_extrusion.get().and_then(Option::as_ref).is_some_and(|e| std::ptr::eq(e, extrusion));
249        own.then(|| self.extrusion_profile.get_or_init(|| extrusion.reduce(true)).as_ref())
250    }
251
252    /// The recognized analytic carrier, if this exact rational patch is a
253    /// plane or a full revolution quadric/torus. Computed once per instance.
254    pub fn analytic(&self) -> Option<&crate::AnalyticSurface> {
255        self.analytic
256            .get_or_init(|| crate::analytic_surface::recognize(self))
257            .as_ref()
258    }
259
260    /// The recognized affine sphere (an ellipsoid), under `BREP_AFFINE_SPHERE`
261    /// and only when this net is not an analytic carrier; `None` otherwise.
262    pub fn affine_sphere(&self) -> Option<&crate::affine_sphere::AffineSphere> {
263        self.affine_sphere
264            .get_or_init(|| {
265                if !crate::affine_sphere::affine_sphere_enabled() || self.analytic().is_some() {
266                    None
267                } else {
268                    crate::affine_sphere::recognize(self)
269                }
270            })
271            .as_ref()
272    }
273
274    /// The names of this surface's caches that hold a value, in declaration
275    /// order. For the boolean's operand-state instrument
276    /// (`BREP_DEBUG_OPERAND_STATE`), which reads which caches arrive warm.
277    pub fn warm_caches(&self) -> Vec<&'static str> {
278        let mut warm = Vec::new();
279        let cells = [
280            ("analytic", self.analytic.get().is_some()),
281            ("linear_extrusion", self.linear_extrusion.get().is_some()),
282            ("extrusion_profile", self.extrusion_profile.get().is_some()),
283            ("affine_sphere", self.affine_sphere.get().is_some()),
284            ("validated", self.validated.get()),
285            ("closed", self.closed_directions.get().is_some()),
286            ("grid", self.projection_grid.get().is_some()),
287            ("dense", self.projection_dense_grid.get().is_some()),
288            ("ring", self.projection_ring_grid.get().is_some()),
289            ("cells", self.projection_cells.get().is_some()),
290            ("bezier", self.bezier_patches.get().is_some()),
291        ];
292        for (name, held) in cells {
293            if held {
294                warm.push(name);
295            }
296        }
297        warm
298    }
299
300    /// Empties the named caches (`warm_caches`' names; `all` for every one),
301    /// or, with `from`, sets each to `from`'s value. For the operand-state
302    /// instrument only: a cache that decides an answer is a defect, and this
303    /// is how the bisect finds it.
304    pub fn exchange_caches(&mut self, names: &[&str], from: Option<&Self>) {
305        let wants = |name: &str| names.iter().any(|&n| n == name || n == "all");
306        if wants("analytic") {
307            self.analytic = from.map(|f| f.analytic.clone()).unwrap_or_default();
308        }
309        // the held profile is built from the structure, so it goes wherever the structure goes
310        if wants("linear_extrusion") || wants("extrusion_profile") {
311            self.linear_extrusion = from.map(|f|f.linear_extrusion.clone()).unwrap_or_default();
312            self.extrusion_profile = from.map(|f| f.extrusion_profile.clone()).unwrap_or_default();
313        }
314        if wants("affine_sphere") {
315            self.affine_sphere = from.map(|f| f.affine_sphere.clone()).unwrap_or_default();
316        }
317        if wants("validated") {
318            self.validated = std::cell::Cell::new(from.is_some_and(|f| f.validated.get()));
319        }
320        if wants("closed") {
321            self.closed_directions = from.map(|f| f.closed_directions.clone()).unwrap_or_default();
322        }
323        if wants("grid") {
324            self.projection_grid = from.map(|f| f.projection_grid.clone()).unwrap_or_default();
325        }
326        if wants("dense") {
327            self.projection_dense_grid = from.map(|f| f.projection_dense_grid.clone()).unwrap_or_default();
328        }
329        if wants("ring") {
330            self.projection_ring_grid = from.map(|f| f.projection_ring_grid.clone()).unwrap_or_default();
331        }
332        if wants("cells") {
333            self.projection_cells = from.map(|f| f.projection_cells.clone()).unwrap_or_default();
334        }
335        if wants("bezier") {
336            self.bezier_patches = from.map(|f| f.bezier_patches.clone()).unwrap_or_default();
337        }
338    }
339
340    fn knot_vectors(&self) -> Result<(KnotVector, KnotVector), String> {
341        Ok((
342            KnotVector::new(self.knots_u.clone(), self.degree_u)?,
343            KnotVector::new(self.knots_v.clone(), self.degree_v)?,
344        ))
345    }
346
347    #[cfg_attr(feature = "profile-wall", track_caller)]
348    pub fn evaluate_homogeneous(&self, u: f64, v: f64) -> Result<Vec4, String> {
349        let _reader = crate::reader_profile::Point::open(crate::reader_profile::SURFACE, std::panic::Location::caller());
350    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
351        crate::projection_profile::count(crate::projection_profile::LANE_EVALUATE, self);
352        self.ensure_valid()?;
353        if self.degree_u > MAX_STACK_DEGREE || self.degree_v > MAX_STACK_DEGREE {
354            return self.evaluate_homogeneous_heap(u, v);
355        }
356        let u = knot_clamp(&self.knots_u, self.degree_u, u);
357        let v = knot_clamp(&self.knots_v, self.degree_v, v);
358        let span_u = knot_find_span(&self.knots_u, self.degree_u, u);
359        let span_v = knot_find_span(&self.knots_v, self.degree_v, v);
360        // Recognition evaluates points itself. Inspect only an initialized cache:
361        // asking analytic() here would recursively initialize that same cache.
362        if analytic_point_on() && matches!((self.degree_u, self.degree_v), (1, 1) | (2, 1) | (1, 2) | (2, 2))
363            && matches!(self.analytic.get().and_then(|carrier| carrier.as_ref()),
364                Some(crate::AnalyticSurface::Plane { .. } | crate::AnalyticSurface::RuledRevolution { .. }
365                    | crate::AnalyticSurface::Sphere { .. } | crate::AnalyticSurface::Torus { .. })) {
366            return Ok(match (self.degree_u, self.degree_v) {
367                (1, 1) => self.analytic_point_small::<1, 1>(u, v, span_u, span_v),
368                (2, 1) => self.analytic_point_small::<2, 1>(u, v, span_u, span_v),
369                (1, 2) => self.analytic_point_small::<1, 2>(u, v, span_u, span_v),
370                (2, 2) => self.analytic_point_small::<2, 2>(u, v, span_u, span_v),
371                _ => unreachable!(),
372            });
373        }
374        let mut basis_u = [0.0f64; MAX_STACK_ORDER];
375        let mut basis_v = [0.0f64; MAX_STACK_ORDER];
376        basis_functions_into(&self.knots_u, self.degree_u, span_u, u, &mut basis_u);
377        basis_functions_into(&self.knots_v, self.degree_v, span_v, v, &mut basis_v);
378        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
379        let mut point = Vec4 {
380            x: 0.0,
381            y: 0.0,
382            z: 0.0,
383            w: 0.0,
384        };
385        for (i, value_u) in basis_u[..=self.degree_u].iter().enumerate() {
386            let row = &self.control_points[span_u - self.degree_u + i];
387            for (j, value_v) in basis_v[..=self.degree_v].iter().enumerate() {
388                point = point.add(row[span_v - self.degree_v + j].scale(value_u * value_v));
389            }
390        }
391        Ok(point)
392    }
393
394    /// The stored rational net, with the general evaluator's arithmetic order.
395    /// Const degrees shrink the scratch arrays and specialize the short loops;
396    /// this is not a trigonometric replacement of the rational parameterization.
397    fn analytic_point_small<const DU: usize, const DV: usize>(&self, u: f64, v: f64, span_u: usize, span_v: usize) -> Vec4 {
398        fn basis<const D: usize>(knots: &[f64], span: usize, parameter: f64) -> [f64; 3] {
399        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::BASIS);
400            let mut values = [0.0; 3];
401            let mut left = [0.0; 3];
402            let mut right = [0.0; 3];
403            values[0] = 1.0;
404            for j in 1..=D {
405                left[j] = parameter - knots[span + 1 - j];
406                right[j] = knots[span + j] - parameter;
407                let mut saved = 0.0;
408                for r in 0..j {
409                    let denominator = right[r + 1] + left[j - r];
410                    let temporary = if denominator.abs() <= EPS { 0.0 } else { values[r] / denominator };
411                    values[r] = saved + right[r + 1] * temporary;
412                    saved = left[j - r] * temporary;
413                }
414                values[j] = saved;
415            }
416            values
417        }
418        let basis_u = basis::<DU>(&self.knots_u, span_u, u);
419        let basis_v = basis::<DV>(&self.knots_v, span_v, v);
420        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
421        let mut point = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
422        for (i, value_u) in basis_u[..=DU].iter().enumerate() {
423            let row = &self.control_points[span_u - DU + i];
424            for (j, value_v) in basis_v[..=DV].iter().enumerate() {
425                point = point.add(row[span_v - DV + j].scale(value_u * value_v));
426            }
427        }
428        point
429    }
430
431    fn evaluate_homogeneous_heap(&self, u: f64, v: f64) -> Result<Vec4, String> {
432        let (knot_u, knot_v) = self.knot_vectors()?;
433        let u = knot_u.clamp_param(u);
434        let v = knot_v.clamp_param(v);
435        let span_u = knot_u.find_span(u);
436        let span_v = knot_v.find_span(v);
437        let basis_u = knot_u.basis_functions(span_u, u);
438        let basis_v = knot_v.basis_functions(span_v, v);
439        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
440        let mut point = Vec4 {
441            x: 0.0,
442            y: 0.0,
443            z: 0.0,
444            w: 0.0,
445        };
446        for (i, value_u) in basis_u.iter().enumerate() {
447            let row = &self.control_points[span_u - self.degree_u + i];
448            for (j, value_v) in basis_v.iter().enumerate() {
449                point = point.add(row[span_v - self.degree_v + j].scale(value_u * value_v));
450            }
451        }
452        Ok(point)
453    }
454
455    #[cfg_attr(feature = "profile-wall", track_caller)]
456    pub fn evaluate(&self, u: f64, v: f64) -> Result<Vec3, String> {
457        let _reader = crate::reader_profile::Point::open(crate::reader_profile::SURFACE, std::panic::Location::caller());
458    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
459        self.evaluate_homogeneous(u, v)?.point()
460    }
461
462    /// Value beyond the domain (Golovanov §3.15): closed directions wrap
463    /// cyclically; open directions extend along the boundary tangent
464    /// plane, with the bilinear corner form when both parameters are
465    /// outside.  Intersection and projection algorithms probe outside the
466    /// domain, so this is a required capability of every surface.
467    #[cfg_attr(feature = "profile-wall", track_caller)]
468    pub fn evaluate_extended(&self, u: f64, v: f64) -> Result<Vec3, String> {
469        let _reader = crate::reader_profile::Point::open(crate::reader_profile::SURFACE, std::panic::Location::caller());
470    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
471        if small_derivatives_enabled() {
472            return Ok(self.derivatives_extended_small(u, v, 0)?[0][0]);
473        }
474        Ok(self.derivatives_extended(u, v, 0)?[0][0])
475    }
476
477    /// Allocation-free twin of [`Self::derivatives_extended`] for
478    /// `derivative_count <= 2` (lane O row 20): the same wrap, anchor and
479    /// bilinear extension, over [`Self::derivatives_small`], which is the
480    /// byte-faithful stack copy of [`Self::derivatives`]. Entries outside
481    /// `k + l <= derivative_count` stay `Vec3::default()`, as the Vec form
482    /// leaves them.
483    pub fn derivatives_extended_small(
484        &self,
485        u: f64,
486        v: f64,
487        derivative_count: usize,
488    ) -> Result<[[Vec3; 3]; 3], String> {
489        debug_assert!(derivative_count <= 2);
490        let [u0, u1] = self.domain_u()?;
491        let [v0, v1] = self.domain_v()?;
492        let (closed_u, closed_v) = self.closed_directions()?;
493        let mut uu = u;
494        let mut vv = v;
495        if closed_u && (u < u0 || u > u1) {
496            uu = u0 + (u - u0).rem_euclid(u1 - u0);
497        }
498        if closed_v && (v < v0 || v > v1) {
499            vv = v0 + (v - v0).rem_euclid(v1 - v0);
500        }
501        let du_out = if uu < u0 { uu - u0 } else if uu > u1 { uu - u1 } else { 0.0 };
502        let dv_out = if vv < v0 { vv - v0 } else if vv > v1 { vv - v1 } else { 0.0 };
503        if du_out == 0.0 && dv_out == 0.0 {
504            return self.derivatives_small(uu, vv, derivative_count);
505        }
506        let anchor_u = uu - du_out;
507        let anchor_v = vv - dv_out;
508        let base = self.derivatives_small(anchor_u, anchor_v, 2)?;
509        let mut result = [[Vec3::default(); 3]; 3];
510        result[0][0] = base[0][0]
511            .add(base[1][0].scale(du_out))
512            .add(base[0][1].scale(dv_out))
513            .add(base[1][1].scale(du_out * dv_out));
514        if derivative_count >= 1 {
515            result[1][0] = base[1][0].add(base[1][1].scale(dv_out));
516            result[0][1] = base[0][1].add(base[1][1].scale(du_out));
517            result[1][1] = base[1][1];
518        }
519        if derivative_count >= 2 {
520            if du_out == 0.0 {
521                result[2][0] = base[2][0];
522            }
523            if dv_out == 0.0 {
524                result[0][2] = base[0][2];
525            }
526        }
527        Ok(result)
528    }
529
530    /// Derivatives beyond the domain (§3.15).  The extension is C¹: first
531    /// derivatives follow the ruled/bilinear extension, second derivatives
532    /// are taken at the boundary anchor (zero across an extended
533    /// direction).
534    pub fn derivatives_extended(
535        &self,
536        u: f64,
537        v: f64,
538        derivative_count: usize,
539    ) -> Result<Vec<Vec<Vec3>>, String> {
540        if derivative_count <= 2 && small_derivatives_enabled() {
541            let small = self.derivatives_extended_small(u, v, derivative_count)?;
542            let order = derivative_count + 1;
543            return Ok((0..order).map(|k| (0..order).map(|l| small[k][l]).collect()).collect());
544        }
545        let [u0, u1] = self.domain_u()?;
546        let [v0, v1] = self.domain_v()?;
547        let (closed_u, closed_v) = self.closed_directions()?;
548        let mut uu = u;
549        let mut vv = v;
550        if closed_u && (u < u0 || u > u1) {
551            uu = u0 + (u - u0).rem_euclid(u1 - u0);
552        }
553        if closed_v && (v < v0 || v > v1) {
554            vv = v0 + (v - v0).rem_euclid(v1 - v0);
555        }
556        let du_out = if uu < u0 {
557            uu - u0
558        } else if uu > u1 {
559            uu - u1
560        } else {
561            0.0
562        };
563        let dv_out = if vv < v0 {
564            vv - v0
565        } else if vv > v1 {
566            vv - v1
567        } else {
568            0.0
569        };
570        if du_out == 0.0 && dv_out == 0.0 {
571            return self.derivatives(uu, vv, derivative_count);
572        }
573        let anchor_u = uu - du_out;
574        let anchor_v = vv - dv_out;
575        let base = self.derivatives(anchor_u, anchor_v, derivative_count.max(2))?;
576        let order = derivative_count + 1;
577        let mut result = vec![vec![Vec3::default(); order]; order];
578        // Bilinear extension: S = A00 + du·A10 + dv·A01 + du·dv·A11
579        // (reduces to the ruled tangent-plane extension when only one
580        // parameter is outside).
581        result[0][0] = base[0][0]
582            .add(base[1][0].scale(du_out))
583            .add(base[0][1].scale(dv_out))
584            .add(base[1][1].scale(du_out * dv_out));
585        if derivative_count >= 1 {
586            result[1][0] = base[1][0].add(base[1][1].scale(dv_out));
587            result[0][1] = base[0][1].add(base[1][1].scale(du_out));
588            result[1][1] = base[1][1];
589        }
590        if derivative_count >= 2 {
591            let second = self.derivatives(anchor_u, anchor_v, 2)?;
592            if du_out == 0.0 {
593                result[2][0] = second[2][0];
594            }
595            if dv_out == 0.0 {
596                result[0][2] = second[0][2];
597            }
598        }
599        Ok(result)
600    }
601
602    pub fn derivatives(
603        &self,
604        u: f64,
605        v: f64,
606        derivative_count: usize,
607    ) -> Result<Vec<Vec<Vec3>>, String> {
608        crate::projection_profile::count(crate::projection_profile::LANE_DERIVATIVES, self);
609        self.ensure_valid()?;
610        let du = derivative_count.min(self.degree_u);
611        let dv = derivative_count.min(self.degree_v);
612        let stride = derivative_count + 1;
613        // Flat (k, l) grid: one allocation instead of nested per-row Vecs.
614        let zero = Vec4 {
615            x: 0.0,
616            y: 0.0,
617            z: 0.0,
618            w: 0.0,
619        };
620        let mut homogeneous = vec![zero; stride * stride];
621        if self.degree_u <= MAX_STACK_DEGREE && self.degree_v <= MAX_STACK_DEGREE {
622            let u = knot_clamp(&self.knots_u, self.degree_u, u);
623            let v = knot_clamp(&self.knots_v, self.degree_v, v);
624            let span_u = knot_find_span(&self.knots_u, self.degree_u, u);
625            let span_v = knot_find_span(&self.knots_v, self.degree_v, v);
626            // `derivative_count` reaches the degree here (blends ask for third
627            // partials), so the rows retain the full stack order.
628            let mut basis_u = [[0.0f64; MAX_STACK_ORDER]; MAX_STACK_ORDER];
629            let mut basis_v = [[0.0f64; MAX_STACK_ORDER]; MAX_STACK_ORDER];
630            basis_derivatives_into(
631                &self.knots_u,
632                self.degree_u,
633                span_u,
634                u,
635                du,
636                &mut basis_u[..=du],
637            );
638            basis_derivatives_into(
639                &self.knots_v,
640                self.degree_v,
641                span_v,
642                v,
643                dv,
644                &mut basis_v[..=dv],
645            );
646            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
647            for k in 0..=du {
648                for l in 0..=dv {
649                    if k + l > derivative_count {
650                        continue;
651                    }
652                    let mut point = zero;
653                    for i in 0..=self.degree_u {
654                        let row = &self.control_points[span_u - self.degree_u + i];
655                        for j in 0..=self.degree_v {
656                            point = point.add(
657                                row[span_v - self.degree_v + j]
658                                    .scale(basis_u[k][i] * basis_v[l][j]),
659                            );
660                        }
661                    }
662                    homogeneous[k * stride + l] = point;
663                }
664            }
665        } else {
666            let (knot_u, knot_v) = self.knot_vectors()?;
667            let u = knot_u.clamp_param(u);
668            let v = knot_v.clamp_param(v);
669            let span_u = knot_u.find_span(u);
670            let span_v = knot_v.find_span(v);
671            let basis_u = knot_u.basis_derivatives(span_u, u, du);
672            let basis_v = knot_v.basis_derivatives(span_v, v, dv);
673            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
674            for k in 0..=du {
675                for l in 0..=dv {
676                    if k + l > derivative_count {
677                        continue;
678                    }
679                    let mut point = zero;
680                    for i in 0..=self.degree_u {
681                        let row = &self.control_points[span_u - self.degree_u + i];
682                        for j in 0..=self.degree_v {
683                            point = point.add(
684                                row[span_v - self.degree_v + j]
685                                    .scale(basis_u[k][i] * basis_v[l][j]),
686                            );
687                        }
688                    }
689                    homogeneous[k * stride + l] = point;
690                }
691            }
692        }
693
694        let mut result = vec![vec![Vec3::default(); derivative_count + 1]; derivative_count + 1];
695        let weight = homogeneous[0].w;
696        if weight.abs() <= EPS {
697            return Err("NurbsSurface: zero evaluated weight".into());
698        }
699        for k in 0..=derivative_count {
700            for l in 0..=derivative_count - k {
701                if k > du || l > dv {
702                    continue;
703                }
704                let at = |row: usize, column: usize| homogeneous[row * stride + column];
705                let mut value = Vec3::new(at(k, l).x, at(k, l).y, at(k, l).z);
706                for j in 1..=l {
707                    value = value.sub(result[k][l - j].scale(binomial(l, j) * at(0, j).w));
708                }
709                for i in 1..=k {
710                    value = value.sub(result[k - i][l].scale(binomial(k, i) * at(i, 0).w));
711                    let mut mixed = Vec3::default();
712                    for j in 1..=l {
713                        mixed = mixed.add(result[k - i][l - j].scale(binomial(l, j) * at(i, j).w));
714                    }
715                    value = value.sub(mixed.scale(binomial(k, i)));
716                }
717                result[k][l] = value.scale(1.0 / weight);
718            }
719        }
720        Ok(result)
721    }
722
723    /// Allocation-free twin of [`Self::derivatives`] for the hot
724    /// `derivative_count <= 2` path (point, first, and second partials).
725    ///
726    /// This is a byte-for-byte faithful copy of the arithmetic in
727    /// [`Self::derivatives`]: identical basis evaluation, identical summation
728    /// order (control-point row `i` outer, column `j` inner, `scale`-then-`add`),
729    /// and the identical rational `A(u,v)/w(u,v)` de-homogenization recurrence.
730    /// Only the storage differs — fixed-size stack arrays (`[Vec4; 9]` for the
731    /// `(count+1)²` homogeneous grid, `[[Vec3; 3]; 3]` for the result) replace
732    /// the heap `Vec<Vec4>` / `Vec<Vec<Vec3>>`. Grid entries outside
733    /// `k + l <= derivative_count` (and outside `k <= du`, `l <= dv`) stay
734    /// `Vec3::default()`, exactly as the heap version leaves them, so callers may
735    /// index `[k][l]` for any `k + l <= 2` and read the same value the Vec API
736    /// would have produced.
737    pub fn derivatives_small(
738        &self,
739        u: f64,
740        v: f64,
741        derivative_count: usize,
742    ) -> Result<[[Vec3; 3]; 3], String> {
743        match derivative_count {
744            0 => self.derivatives_small_count::<0>(u, v),
745            1 => self.derivatives_small_count::<1>(u, v),
746            2 => self.derivatives_small_count::<2>(u, v),
747            _ => self.derivatives_small_degrees::<{usize::MAX}, {usize::MAX}, {usize::MAX}>(u, v, derivative_count),
748        }
749    }
750
751    fn derivatives_small_count<const COUNT: usize>(&self, u: f64, v: f64) -> Result<[[Vec3; 3]; 3], String> {
752        match (self.degree_u, self.degree_v) {
753            (3, 9) => self.derivatives_small_degrees::<3, 9, COUNT>(u, v, COUNT),
754            (5, 9) => self.derivatives_small_degrees::<5, 9, COUNT>(u, v, COUNT),
755            _ => self.derivatives_small_degrees::<{usize::MAX}, {usize::MAX}, COUNT>(u, v, COUNT),
756        }
757    }
758
759    // The same recurrence and control-point order, with partial count and common
760    // screw-wall degrees fixed so bounds and loop trips can fold. MAX retains
761    // the runtime argument for the generic path and its bitwise comparison.
762    fn derivatives_small_degrees<const U: usize, const V: usize, const COUNT: usize>(
763        &self, u: f64, v: f64, derivative_count: usize,
764    ) -> Result<[[Vec3; 3]; 3], String> {
765        let degree_u = if U == usize::MAX { self.degree_u } else { U };
766        let degree_v = if V == usize::MAX { self.degree_v } else { V };
767        let derivative_count = if COUNT == usize::MAX { derivative_count } else { COUNT };
768        // Row zero of the derivative basis has the value recurrence's exact
769        // arithmetic. Keep its row-major sum and reciprocal multiplication,
770        // but avoid the derivative scratch grids for a point-only request.
771        // The experimental analytic evaluator is a separate policy: retain
772        // the original derivative path whenever that policy is enabled.
773        if derivative_count == 0 && switch!("BREP_SURFACE_POINT_ONLY", false)
774            && u.is_finite() && v.is_finite()
775            && degree_u <= MAX_STACK_DEGREE && degree_v <= MAX_STACK_DEGREE
776            && !analytic_point_on() {
777            let point = self.evaluate_homogeneous(u, v)?;
778            if point.w.abs() <= EPS {
779                return Err("NurbsSurface: zero evaluated weight".into());
780            }
781            let mut result = [[Vec3::default(); 3]; 3];
782            result[0][0] = Vec3::new(point.x, point.y, point.z).scale(1.0 / point.w);
783            return Ok(result);
784        }
785        debug_assert!(derivative_count <= 2);
786        self.ensure_valid()?;
787        let du = derivative_count.min(degree_u);
788        let dv = derivative_count.min(degree_v);
789        let stride = derivative_count + 1;
790        let zero = Vec4 {
791            x: 0.0,
792            y: 0.0,
793            z: 0.0,
794            w: 0.0,
795        };
796        let mut homogeneous = [zero; 9];
797        if degree_u <= MAX_STACK_DEGREE && degree_v <= MAX_STACK_DEGREE {
798            let u = knot_clamp(&self.knots_u, degree_u, u);
799            let v = knot_clamp(&self.knots_v, degree_v, v);
800            let span_u = knot_find_span(&self.knots_u, degree_u, u);
801            let span_v = knot_find_span(&self.knots_v, degree_v, v);
802            // Rows `..=du` / `..=dv` (at most three) are the only ones written
803            // or read; the eight-row fill was a measurable share of a sign
804            // reading's surface station (2026-11-02).
805            let mut basis_u = [[0.0f64; MAX_STACK_ORDER]; 3];
806            let mut basis_v = [[0.0f64; MAX_STACK_ORDER]; 3];
807            basis_derivatives_into(
808                &self.knots_u,
809                degree_u,
810                span_u,
811                u,
812                du,
813                &mut basis_u[..=du],
814            );
815            basis_derivatives_into(
816                &self.knots_v,
817                degree_v,
818                span_v,
819                v,
820                dv,
821                &mut basis_v[..=dv],
822            );
823            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
824            for k in 0..=du {
825                for l in 0..=dv {
826                    if k + l > derivative_count {
827                        continue;
828                    }
829                    let mut point = zero;
830                    for i in 0..=degree_u {
831                        let row = &self.control_points[span_u - degree_u + i][span_v - degree_v..=span_v];
832                        for j in 0..=degree_v {
833                            point = point.add(
834                                row[j]
835                                    .scale(basis_u[k][i] * basis_v[l][j]),
836                            );
837                        }
838                    }
839                    homogeneous[k * stride + l] = point;
840                }
841            }
842        } else {
843            let (knot_u, knot_v) = self.knot_vectors()?;
844            let u = knot_u.clamp_param(u);
845            let v = knot_v.clamp_param(v);
846            let span_u = knot_u.find_span(u);
847            let span_v = knot_v.find_span(v);
848            let basis_u = knot_u.basis_derivatives(span_u, u, du);
849            let basis_v = knot_v.basis_derivatives(span_v, v, dv);
850            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
851            for k in 0..=du {
852                for l in 0..=dv {
853                    if k + l > derivative_count {
854                        continue;
855                    }
856                    let mut point = zero;
857                    for i in 0..=degree_u {
858                        let row = &self.control_points[span_u - degree_u + i];
859                        for j in 0..=degree_v {
860                            point = point.add(
861                                row[span_v - degree_v + j]
862                                    .scale(basis_u[k][i] * basis_v[l][j]),
863                            );
864                        }
865                    }
866                    homogeneous[k * stride + l] = point;
867                }
868            }
869        }
870
871        let mut result = [[Vec3::default(); 3]; 3];
872        let weight = homogeneous[0].w;
873        if weight.abs() <= EPS {
874            return Err("NurbsSurface: zero evaluated weight".into());
875        }
876        for k in 0..=derivative_count {
877            for l in 0..=derivative_count - k {
878                if k > du || l > dv {
879                    continue;
880                }
881                let at = |row: usize, column: usize| homogeneous[row * stride + column];
882                let mut value = Vec3::new(at(k, l).x, at(k, l).y, at(k, l).z);
883                for j in 1..=l {
884                    value = value.sub(result[k][l - j].scale(binomial(l, j) * at(0, j).w));
885                }
886                for i in 1..=k {
887                    value = value.sub(result[k - i][l].scale(binomial(k, i) * at(i, 0).w));
888                    let mut mixed = Vec3::default();
889                    for j in 1..=l {
890                        mixed = mixed.add(result[k - i][l - j].scale(binomial(l, j) * at(i, j).w));
891                    }
892                    value = value.sub(mixed.scale(binomial(k, i)));
893                }
894                result[k][l] = value.scale(1.0 / weight);
895            }
896        }
897        Ok(result)
898    }
899
900    /// Whether [`Self::deriv1_tensor_each`] can drive this patch: the stack
901    /// basis tables only reach `MAX_STACK_DEGREE`, and a higher-degree patch
902    /// must be evaluated station by station through [`Self::deriv1`].
903    #[inline]
904    pub fn deriv1_tensor_supported(&self) -> bool {
905        self.degree_u <= MAX_STACK_DEGREE && self.degree_v <= MAX_STACK_DEGREE
906    }
907
908    /// `(S, S_u, S_v)` at every station of the TENSOR BLOCK `us x vs`, handed
909    /// to `f` as `(u index, v index, S, S_u, S_v)` with `us` outer and `vs`
910    /// inner.
911    ///
912    /// Bit-identical to calling [`Self::deriv1`] at each pair, and that is the
913    /// whole point of it: the block's `us.len() + vs.len()` spans and basis
914    /// rows are evaluated ONCE each instead of once per station, which is
915    /// where a fixed tensor-Gauss cell spends most of its time (the basis
916    /// recurrence carries a division per knot per derivative order, and an
917    /// 8x8 cell asks for the same 8 u rows and 8 v rows sixty-four times).
918    /// Nothing else changes: `knot_clamp` / `knot_find_span` /
919    /// `basis_derivatives_into` see the same arguments and so return the same
920    /// floats, the control-point sum runs in the same row-outer/column-inner
921    /// order from the same zero `Vec4`, and the rational de-homogenization is
922    /// [`Self::derivatives_small`]'s recurrence written out for
923    /// `derivative_count == 1`.
924    ///
925    /// Two steps of that recurrence are elided because they are exact no-ops
926    /// at this order: `binomial(1, 1)` is exactly `1.0`, and the mixed term it
927    /// scales is the zero vector, whose subtraction leaves every component
928    /// (including a negative zero) bit-unchanged.
929    pub fn deriv1_tensor_each<F>(
930        &self,
931        us: &[f64],
932        vs: &[f64],
933        mut f: F,
934    ) -> Result<(), String>
935    where
936        F: FnMut(usize, usize, Vec3, Vec3, Vec3) -> Result<(), String>,
937    {
938        self.ensure_valid()?;
939        // Width and rationale: `TENSOR_MAX_BLOCK` at the top of this module.
940        const MAX_BLOCK: usize = TENSOR_MAX_BLOCK;
941        if !self.deriv1_tensor_supported() || us.len() > MAX_BLOCK || vs.len() > MAX_BLOCK {
942            return Err("NurbsSurface: tensor block outside the stack evaluator".into());
943        }
944        let du = 1usize.min(self.degree_u);
945        let dv = 1usize.min(self.degree_v);
946        let mut span_u = [0usize; MAX_BLOCK];
947        let mut span_v = [0usize; MAX_BLOCK];
948        let mut basis_u = [[[0.0f64; MAX_STACK_ORDER]; 2]; MAX_BLOCK];
949        let mut basis_v = [[[0.0f64; MAX_STACK_ORDER]; 2]; MAX_BLOCK];
950        for (index, &value) in us.iter().enumerate() {
951            let value = knot_clamp(&self.knots_u, self.degree_u, value);
952            span_u[index] = knot_find_span(&self.knots_u, self.degree_u, value);
953            basis_derivatives_into(
954                &self.knots_u,
955                self.degree_u,
956                span_u[index],
957                value,
958                du,
959                &mut basis_u[index][..=du],
960            );
961        }
962        for (index, &value) in vs.iter().enumerate() {
963            let value = knot_clamp(&self.knots_v, self.degree_v, value);
964            span_v[index] = knot_find_span(&self.knots_v, self.degree_v, value);
965            basis_derivatives_into(
966                &self.knots_v,
967                self.degree_v,
968                span_v[index],
969                value,
970                dv,
971                &mut basis_v[index][..=dv],
972            );
973        }
974        if tensor_fused_on() {
975            let (count_u, count_v) = (us.len(), vs.len());
976            let tables = (&span_u, &span_v, &basis_u, &basis_v);
977            match (self.degree_u, self.degree_v) {
978                (1, 1) => return self.deriv1_tensor_fused::<1, 1, F>(count_u, count_v, tables, &mut f),
979                (1, 2) => return self.deriv1_tensor_fused::<1, 2, F>(count_u, count_v, tables, &mut f),
980                (1, 3) => return self.deriv1_tensor_fused::<1, 3, F>(count_u, count_v, tables, &mut f),
981                (2, 1) => return self.deriv1_tensor_fused::<2, 1, F>(count_u, count_v, tables, &mut f),
982                (2, 2) => return self.deriv1_tensor_fused::<2, 2, F>(count_u, count_v, tables, &mut f),
983                (2, 3) => return self.deriv1_tensor_fused::<2, 3, F>(count_u, count_v, tables, &mut f),
984                (3, 1) => return self.deriv1_tensor_fused::<3, 1, F>(count_u, count_v, tables, &mut f),
985                (3, 2) => return self.deriv1_tensor_fused::<3, 2, F>(count_u, count_v, tables, &mut f),
986                (3, 3) => return self.deriv1_tensor_fused::<3, 3, F>(count_u, count_v, tables, &mut f),
987                _ => {}
988            }
989        }
990        let zero = Vec4 {
991            x: 0.0,
992            y: 0.0,
993            z: 0.0,
994            w: 0.0,
995        };
996        for i in 0..us.len() {
997            let rows = &self.control_points[span_u[i] - self.degree_u..];
998            for j in 0..vs.len() {
999                let column = span_v[j] - self.degree_v;
1000                // The (k, l) homogeneous grid `derivatives_small` builds for
1001                // `derivative_count == 1`: (0,0) always, (0,1) when dv >= 1,
1002                // (1,0) when du >= 1.
1003                let sum = |k: usize, l: usize| {
1004                    let mut point = zero;
1005                    for row_index in 0..=self.degree_u {
1006                        let row = &rows[row_index];
1007                        for column_index in 0..=self.degree_v {
1008                            point = point.add(
1009                                row[column + column_index]
1010                                    .scale(basis_u[i][k][row_index] * basis_v[j][l][column_index]),
1011                            );
1012                        }
1013                    }
1014                    point
1015                };
1016                let h00 = sum(0, 0);
1017                let h01 = if dv >= 1 { sum(0, 1) } else { zero };
1018                let h10 = if du >= 1 { sum(1, 0) } else { zero };
1019                let weight = h00.w;
1020                if weight.abs() <= EPS {
1021                    return Err("NurbsSurface: zero evaluated weight".into());
1022                }
1023                let inverse = 1.0 / weight;
1024                let point = Vec3::new(h00.x, h00.y, h00.z).scale(inverse);
1025                let partial_v = if dv >= 1 {
1026                    Vec3::new(h01.x, h01.y, h01.z)
1027                        .sub(point.scale(h01.w))
1028                        .scale(inverse)
1029                } else {
1030                    Vec3::default()
1031                };
1032                let partial_u = if du >= 1 {
1033                    Vec3::new(h10.x, h10.y, h10.z)
1034                        .sub(point.scale(h10.w))
1035                        .scale(inverse)
1036                } else {
1037                    Vec3::default()
1038                };
1039                f(i, j, point, partial_u, partial_v)?;
1040            }
1041        }
1042        Ok(())
1043    }
1044
1045    /// [`Self::deriv1_tensor_each`]'s station loop for a patch of degrees
1046    /// `DEGREE_U × DEGREE_V`, both at least 1, from the block's span and basis
1047    /// tables. The same bits as the run-time-degree loop: each of the three
1048    /// homogeneous sums (`S`, `∂_v`, `∂_u`) gets the same products
1049    /// `basis_u · basis_v` of the same control points, scaled and then added in
1050    /// the same row-outer, column-inner order from the same zero `Vec4`, and
1051    /// the dehomogenization is that loop's line for line. What changes is only
1052    /// that the three sums share one walk over the control points, and the trip
1053    /// counts are constants the compiler unrolls. A mass integral's adaptive
1054    /// area reads spend most of their time here: on a fitted bicubic offset
1055    /// shell, about a billion stations for one solid.
1056    #[allow(clippy::type_complexity)]
1057    #[inline(always)]
1058    fn deriv1_tensor_fused<const DEGREE_U: usize, const DEGREE_V: usize, F>(
1059        &self,
1060        count_u: usize,
1061        count_v: usize,
1062        (span_u, span_v, basis_u, basis_v): (
1063            &[usize; TENSOR_MAX_BLOCK],
1064            &[usize; TENSOR_MAX_BLOCK],
1065            &[[[f64; MAX_STACK_ORDER]; 2]; TENSOR_MAX_BLOCK],
1066            &[[[f64; MAX_STACK_ORDER]; 2]; TENSOR_MAX_BLOCK],
1067        ),
1068        f: &mut F,
1069    ) -> Result<(), String>
1070    where
1071        F: FnMut(usize, usize, Vec3, Vec3, Vec3) -> Result<(), String>,
1072    {
1073        let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1074        for i in 0..count_u {
1075            let rows = &self.control_points[span_u[i] - DEGREE_U..=span_u[i]];
1076            let (value_u, slope_u) = (&basis_u[i][0], &basis_u[i][1]);
1077            for j in 0..count_v {
1078                let column = span_v[j] - DEGREE_V;
1079                let (value_v, slope_v) = (&basis_v[j][0], &basis_v[j][1]);
1080                let (mut h00, mut h01, mut h10) = (zero, zero, zero);
1081                for row_index in 0..=DEGREE_U {
1082                    let row = &rows[row_index][column..=column + DEGREE_V];
1083                    for column_index in 0..=DEGREE_V {
1084                        let control = row[column_index];
1085                        h00 = h00.add(control.scale(value_u[row_index] * value_v[column_index]));
1086                        h01 = h01.add(control.scale(value_u[row_index] * slope_v[column_index]));
1087                        h10 = h10.add(control.scale(slope_u[row_index] * value_v[column_index]));
1088                    }
1089                }
1090                let weight = h00.w;
1091                if weight.abs() <= EPS {
1092                    return Err("NurbsSurface: zero evaluated weight".into());
1093                }
1094                let inverse = 1.0 / weight;
1095                let point = Vec3::new(h00.x, h00.y, h00.z).scale(inverse);
1096                let partial_v = Vec3::new(h01.x, h01.y, h01.z).sub(point.scale(h01.w)).scale(inverse);
1097                let partial_u = Vec3::new(h10.x, h10.y, h10.z).sub(point.scale(h10.w)).scale(inverse);
1098                f(i, j, point, partial_u, partial_v)?;
1099            }
1100        }
1101        Ok(())
1102    }
1103
1104    /// Point and first partials `(S, S_u, S_v)` with zero heap allocation.
1105    /// Bit-identical to `derivatives(u, v, 1)` at `[0][0] / [1][0] / [0][1]`.
1106    #[inline]
1107    pub fn deriv1(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3), String> {
1108        // Degrees 1 and 2 in both directions (every carrier the kernel builds
1109        // and the fitted patches it blends with) take the first-order twin
1110        // with both degrees fixed at compile time; its arithmetic is
1111        // `derivatives_small`'s to the bit (`deriv1_small_fixed`), and the
1112        // mass sign reading's chord stations were a third `derivatives_small`
1113        // self time after the basis recurrence (2026-11-02).
1114        match (self.degree_u, self.degree_v) {
1115            (1, 1) => self.deriv1_small_fixed::<1, 1>(u, v),
1116            (2, 1) => self.deriv1_small_fixed::<2, 1>(u, v),
1117            (1, 2) => self.deriv1_small_fixed::<1, 2>(u, v),
1118            (2, 2) => self.deriv1_small_fixed::<2, 2>(u, v),
1119            (3, 9) => self.deriv1_small_fixed::<3, 9>(u, v),
1120            (5, 9) => self.deriv1_small_fixed::<5, 9>(u, v),
1121            _ => {
1122                let g = self.derivatives_small(u, v, 1)?;
1123                Ok((g[0][0], g[1][0], g[0][1]))
1124            }
1125        }
1126    }
1127
1128    /// First-order rational recurrence with only its three live sums, for a
1129    /// patch whose degrees are the const parameters. The clamp, span, basis
1130    /// rows, control summation (row outer, column inner, scale then add from
1131    /// the zero `Vec4`) and dehomogenization are `derivatives_small`'s in the
1132    /// same order; the two recurrence steps written out here that
1133    /// `derivatives_small` runs generically are exact no-ops at this order
1134    /// (`binomial(1, 1)` is exactly `1.0`; the mixed term is the zero vector,
1135    /// whose subtraction changes no bit). So the three results are the same
1136    /// bits as `derivatives_small(u, v, 1)` at `[0][0]`, `[1][0]`, `[0][1]`
1137    /// for ANY surface of these degrees, analytic or not
1138    /// (`deriv1_degree_dispatch_tests`). Caller retains the existing
1139    /// wrapping, extension and refusal paths.
1140    fn deriv1_small_fixed<const DEGREE_U: usize, const DEGREE_V: usize>(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3), String> {
1141        self.ensure_valid()?;
1142        let du = DEGREE_U.min(1);
1143        let dv = DEGREE_V.min(1);
1144        let u = knot_clamp(&self.knots_u, DEGREE_U, u);
1145        let v = knot_clamp(&self.knots_v, DEGREE_V, v);
1146        let span_u = knot_find_span(&self.knots_u, DEGREE_U, u);
1147        let span_v = knot_find_span(&self.knots_v, DEGREE_V, v);
1148        let mut basis_u = [[0.0; MAX_STACK_ORDER]; 2];
1149        let mut basis_v = [[0.0; MAX_STACK_ORDER]; 2];
1150        basis_derivatives_into(&self.knots_u, DEGREE_U, span_u, u, du, &mut basis_u[..=du]);
1151        basis_derivatives_into(&self.knots_v, DEGREE_V, span_v, v, dv, &mut basis_v[..=dv]);
1152        let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1153        let sum = |k: usize, l: usize| {
1154            let mut value = zero;
1155            for i in 0..=DEGREE_U {
1156                let row = &self.control_points[span_u - DEGREE_U + i][span_v - DEGREE_V..=span_v];
1157                for j in 0..=DEGREE_V {
1158                    value = value.add(row[j].scale(basis_u[k][i] * basis_v[l][j]));
1159                }
1160            }
1161            value
1162        };
1163        let h00 = sum(0, 0);
1164        let h01 = if dv == 1 { sum(0, 1) } else { zero };
1165        let h10 = if du == 1 { sum(1, 0) } else { zero };
1166        if h00.w.abs() <= EPS { return Err("NurbsSurface: zero evaluated weight".into()); }
1167        let inverse = 1.0 / h00.w;
1168        let point = Vec3::new(h00.x, h00.y, h00.z).scale(inverse);
1169        let partial_v = if dv == 1 {
1170            Vec3::new(h01.x, h01.y, h01.z).sub(point.scale(1.0 * h01.w)).scale(inverse)
1171        } else { Vec3::default() };
1172        let partial_u = if du == 1 {
1173            Vec3::new(h10.x, h10.y, h10.z).sub(point.scale(1.0 * h10.w))
1174                .sub(Vec3::default().scale(1.0)).scale(inverse)
1175        } else { Vec3::default() };
1176        Ok((point, partial_u, partial_v))
1177    }
1178
1179    /// The four anchor terms used by a first-order bilinear extension.
1180    /// Pure second partials do not feed these terms. Keep the control sums
1181    /// and rational recurrence in the generic evaluator's arithmetic order.
1182    fn extension_anchor_fixed<const U: usize, const V: usize>(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3, Vec3), String> {
1183        self.ensure_valid()?;
1184        let u = knot_clamp(&self.knots_u, U, u);
1185        let v = knot_clamp(&self.knots_v, V, v);
1186        let span_u = knot_find_span(&self.knots_u, U, u);
1187        let span_v = knot_find_span(&self.knots_v, V, v);
1188        let mut basis_u = [[0.0; MAX_STACK_ORDER]; 2];
1189        let mut basis_v = [[0.0; MAX_STACK_ORDER]; 2];
1190        basis_derivatives_into(&self.knots_u, U, span_u, u, 1, &mut basis_u);
1191        basis_derivatives_into(&self.knots_v, V, span_v, v, 1, &mut basis_v);
1192        let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1193        let sum = |k: usize, l: usize| {
1194            let mut value = zero;
1195            for i in 0..=U {
1196                let row = &self.control_points[span_u - U + i];
1197                for j in 0..=V {
1198                    value = value.add(row[span_v - V + j].scale(basis_u[k][i] * basis_v[l][j]));
1199                }
1200            }
1201            value
1202        };
1203        let (h00,h01,h10,h11) = (sum(0,0),sum(0,1),sum(1,0),sum(1,1));
1204        if h00.w.abs() <= EPS { return Err("NurbsSurface: zero evaluated weight".into()); }
1205        let inverse = 1.0 / h00.w;
1206        let point = Vec3::new(h00.x,h00.y,h00.z).scale(inverse);
1207        let sv = Vec3::new(h01.x,h01.y,h01.z).sub(point.scale(1.0*h01.w)).scale(inverse);
1208        let su = Vec3::new(h10.x,h10.y,h10.z).sub(point.scale(1.0*h10.w))
1209            .sub(Vec3::default().scale(1.0)).scale(inverse);
1210        let mixed = Vec3::default().add(point.scale(1.0*h11.w));
1211        let suv = Vec3::new(h11.x,h11.y,h11.z).sub(su.scale(1.0*h01.w))
1212            .sub(sv.scale(1.0*h10.w)).sub(mixed.scale(1.0)).scale(inverse);
1213        Ok((point,su,sv,suv))
1214    }
1215
1216    fn extension_anchor(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3, Vec3), String> {
1217        match (self.degree_u,self.degree_v) {
1218            (1,1) => self.extension_anchor_fixed::<1,1>(u,v),
1219            (1,2) => self.extension_anchor_fixed::<1,2>(u,v),
1220            (1,3) => self.extension_anchor_fixed::<1,3>(u,v),
1221            (2,1) => self.extension_anchor_fixed::<2,1>(u,v),
1222            (2,2) => self.extension_anchor_fixed::<2,2>(u,v),
1223            (2,3) => self.extension_anchor_fixed::<2,3>(u,v),
1224            (3,1) => self.extension_anchor_fixed::<3,1>(u,v),
1225            (3,2) => self.extension_anchor_fixed::<3,2>(u,v),
1226            (3,3) => self.extension_anchor_fixed::<3,3>(u,v),
1227            _ => { let g = self.derivatives_small(u,v,2)?; Ok((g[0][0],g[1][0],g[0][1],g[1][1])) }
1228        }
1229    }
1230
1231    /// First-order extension using only the anchor terms that it consumes.
1232    pub fn deriv1_extended_trim(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3), String> {
1233        self.deriv1_extended_impl(u,v,true)
1234    }
1235
1236    /// Allocation-free `(S, S_u, S_v)` twin of `derivatives_extended(u, v, 1)`.
1237    ///
1238    /// Mirrors the exact C¹ ruled/bilinear extension arithmetic of
1239    /// [`Self::derivatives_extended`] (only the count == 1 partials), but drives
1240    /// it from [`Self::derivatives_small`] so the in-domain and boundary-anchor
1241    /// evaluations allocate nothing. Bit-identical to
1242    /// `derivatives_extended(u, v, 1)` at `[0][0] / [1][0] / [0][1]`.
1243    pub fn deriv1_extended(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3), String> {
1244        self.deriv1_extended_impl(u,v,false)
1245    }
1246
1247    fn deriv1_extended_impl(&self, u: f64, v: f64, reduced_anchor: bool) -> Result<(Vec3, Vec3, Vec3), String> {
1248        let [u0, u1] = self.domain_u()?;
1249        let [v0, v1] = self.domain_v()?;
1250        let (closed_u, closed_v) = self.closed_directions()?;
1251        let mut uu = u;
1252        let mut vv = v;
1253        if closed_u && (u < u0 || u > u1) {
1254            uu = u0 + (u - u0).rem_euclid(u1 - u0);
1255        }
1256        if closed_v && (v < v0 || v > v1) {
1257            vv = v0 + (v - v0).rem_euclid(v1 - v0);
1258        }
1259        let du_out = if uu < u0 {
1260            uu - u0
1261        } else if uu > u1 {
1262            uu - u1
1263        } else {
1264            0.0
1265        };
1266        let dv_out = if vv < v0 {
1267            vv - v0
1268        } else if vv > v1 {
1269            vv - v1
1270        } else {
1271            0.0
1272        };
1273        if du_out == 0.0 && dv_out == 0.0 {
1274            if reduced_anchor {
1275                match (self.degree_u,self.degree_v) {
1276                    (3,1) => return self.deriv1_small_fixed::<3,1>(uu,vv),
1277                    (1,3) => return self.deriv1_small_fixed::<1,3>(uu,vv),
1278                    (3,2) => return self.deriv1_small_fixed::<3,2>(uu,vv),
1279                    (2,3) => return self.deriv1_small_fixed::<2,3>(uu,vv),
1280                    (3,3) => return self.deriv1_small_fixed::<3,3>(uu,vv),
1281                    _ => {}
1282                }
1283            }
1284            if analytic_deriv1_on() && matches!((self.degree_u, self.degree_v), (1, 1) | (2, 1) | (1, 2) | (2, 2))
1285                && matches!(self.analytic(), Some(crate::AnalyticSurface::Plane { .. }
1286                    | crate::AnalyticSurface::RuledRevolution { .. } | crate::AnalyticSurface::Sphere { .. }
1287                    | crate::AnalyticSurface::Torus { .. })) {
1288                return match (self.degree_u, self.degree_v) {
1289                    (1, 1) => self.deriv1_small_fixed::<1, 1>(uu, vv),
1290                    (2, 1) => self.deriv1_small_fixed::<2, 1>(uu, vv),
1291                    (1, 2) => self.deriv1_small_fixed::<1, 2>(uu, vv),
1292                    (2, 2) => self.deriv1_small_fixed::<2, 2>(uu, vv),
1293                    _ => unreachable!(),
1294                };
1295            }
1296            let g = self.derivatives_small(uu, vv, 1)?;
1297            return Ok((g[0][0], g[1][0], g[0][1]));
1298        }
1299        let anchor_u = uu - du_out;
1300        let anchor_v = vv - dv_out;
1301        let (a00,a10,a01,a11) = if reduced_anchor {
1302            self.extension_anchor(anchor_u,anchor_v)?
1303        } else {
1304            let base = self.derivatives_small(anchor_u,anchor_v,2)?;
1305            (base[0][0],base[1][0],base[0][1],base[1][1])
1306        };
1307        // Bilinear extension: S = A00 + du·A10 + dv·A01 + du·dv·A11.
1308        // The mixed anchor derivative has total order two, even when
1309        // the caller requests only the value or first partials.
1310        let s = a00.add(a10.scale(du_out)).add(a01.scale(dv_out)).add(a11.scale(du_out * dv_out));
1311        let su = a10.add(a11.scale(dv_out));
1312        let sv = a01.add(a11.scale(du_out));
1313        Ok((s, su, sv))
1314    }
1315
1316    /// One first partial at `(u, v)` (clamped into the domain), `S_u` when
1317    /// `along_u`, else `S_v`, evaluated from the DIFFERENCES of the control net
1318    /// rather than from the basis derivatives.
1319    ///
1320    /// [`Self::derivatives`] forms `S_u = (A_u − W_u·S) / W` from `A_u = Σ N′ᵢ·Hᵢ`,
1321    /// a sum of terms the size of the control points whose exact total may be
1322    /// zero. Its rounding is therefore ABSOLUTE, a few ulps of the point, and
1323    /// where the partial itself vanishes (an isoline on which the
1324    /// parameterization is stationary, as on an extrusion of a cubic with
1325    /// coincident end poles) the DIRECTION of what is left is that rounding:
1326    /// measured 2.7e-15 of `x` on a partial of 7.7e-5 along `y`, a normal tilted
1327    /// by 3.5e-11.
1328    ///
1329    /// The hodograph `A_u = Σ N_{i+1,p−1}·p·(H_{i+1} − H_i)/(ξ_{i+p+1} − ξ_{i+1})`
1330    /// (The NURBS Book eq. 3.4, per row) carries the same partial with rounding
1331    /// that scales with its own terms: coincident control points difference to
1332    /// an exact zero, and every other difference is weighted by a basis function
1333    /// that vanishes with the partial. The rational part subtracts
1334    /// `W_u·S` with `W_u` taken from the weight differences, which is an exact
1335    /// zero wherever neighbouring weights are equal.
1336    ///
1337    /// Not bit-identical to `derivatives`, so it is read only where the bare
1338    /// partial has lost its direction (`offset/point.rs`). Refuses above the
1339    /// stack basis tables' degree.
1340    pub fn partial_by_differences(
1341        &self,
1342        along_u: bool,
1343        u: f64,
1344        v: f64,
1345    ) -> Result<Vec3, String> {
1346        self.ensure_valid()?;
1347        if self.degree_u > crate::curve::MAX_STACK_DEGREE || self.degree_v > crate::curve::MAX_STACK_DEGREE {
1348            return Err("NurbsSurface: partial by differences exceeds the stack degree".into());
1349        }
1350        let (pu, pv) = (self.degree_u, self.degree_v);
1351        let u = knot_clamp(&self.knots_u, pu, u);
1352        let v = knot_clamp(&self.knots_v, pv, v);
1353        let span_u = knot_find_span(&self.knots_u, pu, u);
1354        let span_v = knot_find_span(&self.knots_v, pv, v);
1355        let mut full_u = [0.0f64; MAX_STACK_ORDER];
1356        let mut full_v = [0.0f64; MAX_STACK_ORDER];
1357        basis_functions_into(&self.knots_u, pu, span_u, u, &mut full_u);
1358        basis_functions_into(&self.knots_v, pv, span_v, v, &mut full_v);
1359        let zero = Vec4 {
1360            x: 0.0,
1361            y: 0.0,
1362            z: 0.0,
1363            w: 0.0,
1364        };
1365        let control = |i: usize, j: usize| self.control_points[span_u - pu + i][span_v - pv + j];
1366        let mut point = zero;
1367        for i in 0..=pu {
1368            for j in 0..=pv {
1369                point = point.add(control(i, j).scale(full_u[i] * full_v[j]));
1370            }
1371        }
1372        if point.w.abs() <= EPS {
1373            return Err("NurbsSurface: zero evaluated weight".into());
1374        }
1375        let source = Vec3::new(point.x, point.y, point.z).scale(1.0 / point.w);
1376        let (knots, degree, span, parameter) = if along_u {
1377            (&self.knots_u, pu, span_u, u)
1378        } else {
1379            (&self.knots_v, pv, span_v, v)
1380        };
1381        if degree == 0 {
1382            return Ok(Vec3::default());
1383        }
1384        let mut lowered = [0.0f64; MAX_STACK_ORDER];
1385        basis_functions_into(knots, degree - 1, span, parameter, &mut lowered);
1386        // The hodograph's homogeneous value, Σ over the (degree) differences of
1387        // the basis span times the other direction's full basis.
1388        let mut hodograph = zero;
1389        for r in 0..degree {
1390            // Difference r joins control indices (span − degree + r) and
1391            // (span − degree + r + 1); its lowered basis is N_{span−degree+r+1, degree−1}.
1392            let index = span - degree + r;
1393            let width = knots[index + degree + 1] - knots[index + 1];
1394            if width.abs() <= EPS {
1395                continue;
1396            }
1397            let factor = lowered[r] * degree as f64 / width;
1398            if along_u {
1399                for j in 0..=pv {
1400                    let difference = control(r + 1, j).add(control(r, j).scale(-1.0));
1401                    hodograph = hodograph.add(difference.scale(factor * full_v[j]));
1402                }
1403            } else {
1404                for i in 0..=pu {
1405                    let difference = control(i, r + 1).add(control(i, r).scale(-1.0));
1406                    hodograph = hodograph.add(difference.scale(factor * full_u[i]));
1407                }
1408            }
1409        }
1410        Ok(Vec3::new(hodograph.x, hodograph.y, hodograph.z)
1411            .sub(source.scale(hodograph.w))
1412            .scale(1.0 / point.w))
1413    }
1414
1415    pub fn normal(&self, u: f64, v: f64) -> Result<Vec3, String> {
1416        if small_derivatives_enabled() {
1417            let derivatives = self.derivatives_small(u, v, 1)?;
1418            return derivatives[1][0].cross(derivatives[0][1]).normalized();
1419        }
1420        let derivatives = self.derivatives(u, v, 1)?;
1421        derivatives[1][0].cross(derivatives[0][1]).normalized()
1422    }
1423
1424    /// Principal curvatures (κ_min, κ_max) at (u, v), signed with respect to
1425    /// the parametrization normal n = Su × Sv / |Su × Sv| via the shape
1426    /// operator I⁻¹·II.  Convention check: a cylinder of radius R whose normal
1427    /// points AWAY from the axis has κ = −1/R along the circular direction, so
1428    /// an offset's regularity factor 1 − d·κ vanishes exactly when an inward
1429    /// offset (d = −R) reaches the axis.
1430    pub fn principal_curvatures(&self, u: f64, v: f64) -> Result<(f64, f64), String> {
1431        self.principal_curvatures_and_tangents(u, v)
1432            .map(|(kappa_min, kappa_max, _, _)| (kappa_min, kappa_max))
1433    }
1434
1435    /// [`Self::principal_curvatures`] together with the first derivatives
1436    /// `Su` and `Sv` it was read from, so a caller can judge how well
1437    /// conditioned the reading is without evaluating the surface twice.
1438    pub fn principal_curvatures_and_tangents(&self, u: f64, v: f64) -> Result<(f64, f64, Vec3, Vec3), String> {
1439        let derivatives: [[Vec3; 3]; 3] = if small_derivatives_enabled() {
1440            self.derivatives_small(u, v, 2)?
1441        } else {
1442            let heap = self.derivatives(u, v, 2)?;
1443            [[heap[0][0], heap[0][1], heap[0][2]], [heap[1][0], heap[1][1], Vec3::default()], [heap[2][0], Vec3::default(), Vec3::default()]]
1444        };
1445        let su = derivatives[1][0];
1446        let sv = derivatives[0][1];
1447        let cross = su.cross(sv);
1448        let cross_length = cross.length();
1449        if cross_length <= 1e-12 {
1450            return Err(format!(
1451                "degenerate parametrization at (u={u:.4}, v={v:.4})"
1452            ));
1453        }
1454        let normal = cross.scale(1.0 / cross_length);
1455        let e1 = su.dot(su);
1456        let f1 = su.dot(sv);
1457        let g1 = sv.dot(sv);
1458        let l2 = derivatives[2][0].dot(normal);
1459        let m2 = derivatives[1][1].dot(normal);
1460        let n2 = derivatives[0][2].dot(normal);
1461        let denominator = e1 * g1 - f1 * f1;
1462        let mean_double = (l2 * g1 - 2.0 * m2 * f1 + n2 * e1) / denominator; // 2H
1463        let gauss = (l2 * n2 - m2 * m2) / denominator; // K
1464        let discriminant = (mean_double * mean_double * 0.25 - gauss).max(0.0).sqrt();
1465        Ok((
1466            mean_double * 0.5 - discriminant,
1467            mean_double * 0.5 + discriminant,
1468            su,
1469            sv,
1470        ))
1471    }
1472
1473    /// Whether this is a genuinely affine degree-1 by degree-1 patch.
1474    ///
1475    /// A tapered bilinear patch is planar but not affine, so degree alone is
1476    /// insufficient for exact inverse-parameter and integration shortcuts.
1477    pub fn is_affine(&self) -> Result<bool, String> {
1478        if self.degree_u != 1
1479            || self.degree_v != 1
1480            || self.control_points.len() != 2
1481            || self.control_points[0].len() != 2
1482            || self.control_points[1].len() != 2
1483        {
1484            return Ok(false);
1485        }
1486        let weight = self.control_points[0][0].w;
1487        if [
1488            self.control_points[0][1].w,
1489            self.control_points[1][0].w,
1490            self.control_points[1][1].w,
1491        ]
1492        .iter()
1493        .any(|other| (*other - weight).abs() > 1e-12 * other.abs().max(weight.abs()))
1494        {
1495            return Ok(false);
1496        }
1497        let p00 = self.control_points[0][0].point()?;
1498        let p01 = self.control_points[0][1].point()?;
1499        let p10 = self.control_points[1][0].point()?;
1500        let p11 = self.control_points[1][1].point()?;
1501        let gap = p11.sub(p10).sub(p01.sub(p00)).length();
1502        // The parallelogram defect measures the non-affine bilinear term.
1503        // Scale it by the patch extent, never its distance from the origin:
1504        // falsely accepting a translated warped patch also labels it a plane
1505        // and sends its pcurves and offsets through exact affine shortcuts.
1506        let extent = [
1507            p01.sub(p00),
1508            p10.sub(p00),
1509            p11.sub(p00),
1510            p10.sub(p01),
1511            p11.sub(p01),
1512            p11.sub(p10),
1513        ]
1514        .iter()
1515        .map(|delta| delta.length())
1516        .fold(0.0, f64::max);
1517        Ok(gap <= 1e-9 * (1.0 + extent))
1518    }
1519
1520    pub fn iso_curve_u(&self, u: f64) -> Result<NurbsCurve, String> {
1521        self.ensure_valid()?;
1522        let u = knot_clamp(&self.knots_u, self.degree_u, u);
1523        let span = knot_find_span(&self.knots_u, self.degree_u, u);
1524        let basis = if self.degree_u <= MAX_STACK_DEGREE {
1525            let mut stack = [0.0f64; MAX_STACK_ORDER];
1526            basis_functions_into(&self.knots_u, self.degree_u, span, u, &mut stack);
1527            stack[..=self.degree_u].to_vec()
1528        } else {
1529            KnotVector::new(self.knots_u.clone(), self.degree_u)?.basis_functions(span, u)
1530        };
1531        let mut points = Vec::with_capacity(self.control_points[0].len());
1532        for column in 0..self.control_points[0].len() {
1533            let mut point = Vec4 {
1534                x: 0.0,
1535                y: 0.0,
1536                z: 0.0,
1537                w: 0.0,
1538            };
1539            for (index, value) in basis.iter().enumerate() {
1540                point = point
1541                    .add(self.control_points[span - self.degree_u + index][column].scale(*value));
1542            }
1543            points.push(point);
1544        }
1545        NurbsCurve::new(self.degree_v, self.knots_v.clone(), points)
1546    }
1547
1548    pub fn iso_curve_v(&self, v: f64) -> Result<NurbsCurve, String> {
1549        self.ensure_valid()?;
1550        let v = knot_clamp(&self.knots_v, self.degree_v, v);
1551        let span = knot_find_span(&self.knots_v, self.degree_v, v);
1552        let basis = if self.degree_v <= MAX_STACK_DEGREE {
1553            let mut stack = [0.0f64; MAX_STACK_ORDER];
1554            basis_functions_into(&self.knots_v, self.degree_v, span, v, &mut stack);
1555            stack[..=self.degree_v].to_vec()
1556        } else {
1557            KnotVector::new(self.knots_v.clone(), self.degree_v)?.basis_functions(span, v)
1558        };
1559        let mut points = Vec::with_capacity(self.control_points.len());
1560        for row in &self.control_points {
1561            let mut point = Vec4 {
1562                x: 0.0,
1563                y: 0.0,
1564                z: 0.0,
1565                w: 0.0,
1566            };
1567            for (index, value) in basis.iter().enumerate() {
1568                point = point.add(row[span - self.degree_v + index].scale(*value));
1569            }
1570            points.push(point);
1571        }
1572        NurbsCurve::new(self.degree_u, self.knots_u.clone(), points)
1573    }
1574}
1575
1576pub fn make_plane(
1577    origin: Vec3,
1578    u_direction: Vec3,
1579    v_direction: Vec3,
1580    u_max: f64,
1581    v_max: f64,
1582) -> Result<NurbsSurface, String> {
1583    if u_max <= EPS || v_max <= EPS {
1584        return Err("makePlane: parameter extents must be positive".into());
1585    }
1586    let p10 = origin.add(u_direction.scale(u_max));
1587    let p01 = origin.add(v_direction.scale(v_max));
1588    let p11 = p10.add(v_direction.scale(v_max));
1589    NurbsSurface::new(
1590        1,
1591        1,
1592        vec![0.0, 0.0, u_max, u_max],
1593        vec![0.0, 0.0, v_max, v_max],
1594        vec![
1595            vec![Vec4::from_point(origin, 1.0), Vec4::from_point(p01, 1.0)],
1596            vec![Vec4::from_point(p10, 1.0), Vec4::from_point(p11, 1.0)],
1597        ],
1598    )
1599}
1600
1601pub fn make_extrusion(profile: &NurbsCurve, direction: Vec3) -> Result<NurbsSurface, String> {
1602    let rows = profile
1603        .control_points
1604        .iter()
1605        .map(|point| {
1606            vec![
1607                *point,
1608                Vec4 {
1609                    x: point.x + point.w * direction.x,
1610                    y: point.y + point.w * direction.y,
1611                    z: point.z + point.w * direction.z,
1612                    w: point.w,
1613                },
1614            ]
1615        })
1616        .collect();
1617    NurbsSurface::new(
1618        profile.degree,
1619        1,
1620        profile.knots.clone(),
1621        vec![0.0, 0.0, 1.0, 1.0],
1622        rows,
1623    )
1624}
1625
1626pub fn make_revolution(
1627    axis_point: Vec3,
1628    axis_direction: Vec3,
1629    generatrix: &NurbsCurve,
1630    theta: f64,
1631) -> Result<NurbsSurface, String> {
1632    revolution_in_spans(axis_point, axis_direction, generatrix, theta, None)
1633}
1634
1635/// [`make_revolution`] with the turn in ONE rational quadratic span (middle
1636/// weight cos(theta/2)) for `theta` under 180 degrees, where
1637/// `make_revolution` splits past 90. Its circles then run at the parameter of
1638/// a one-conic arc of the same turn, so an edge built that way lies on an
1639/// iso line of it. Up to 90 degrees the two are the same surface.
1640pub fn make_revolution_one_span(
1641    axis_point: Vec3,
1642    axis_direction: Vec3,
1643    generatrix: &NurbsCurve,
1644    theta: f64,
1645) -> Result<NurbsSurface, String> {
1646    if !(theta < std::f64::consts::PI - 1e-6) {
1647        return Err("makeRevolution: one span needs theta under PI".into());
1648    }
1649    revolution_in_spans(axis_point, axis_direction, generatrix, theta, Some(1))
1650}
1651
1652fn revolution_in_spans(
1653    axis_point: Vec3,
1654    axis_direction: Vec3,
1655    generatrix: &NurbsCurve,
1656    theta: f64,
1657    spans: Option<usize>,
1658) -> Result<NurbsSurface, String> {
1659    if theta <= EPS || theta > std::f64::consts::TAU + EPS {
1660        return Err("makeRevolution: theta must be in (0, 2*PI]".into());
1661    }
1662    let theta = theta.min(std::f64::consts::TAU);
1663    let axis = axis_direction.normalized()?;
1664    let arc_count = spans.unwrap_or_else(|| ((theta / std::f64::consts::FRAC_PI_2 - EPS).ceil() as usize).clamp(1, 4));
1665    let arc_angle = theta / arc_count as f64;
1666    let middle_weight = (arc_angle / 2.0).cos();
1667    let mut knots_u = vec![0.0, 0.0, 0.0];
1668    for index in 1..arc_count {
1669        let knot = index as f64 / arc_count as f64;
1670        knots_u.extend([knot, knot]);
1671    }
1672    knots_u.extend([1.0, 1.0, 1.0]);
1673    let mut rows = vec![
1674        vec![
1675            Vec4 {
1676                x: 0.0,
1677                y: 0.0,
1678                z: 0.0,
1679                w: 1.0,
1680            };
1681            generatrix.control_points.len()
1682        ];
1683        2 * arc_count + 1
1684    ];
1685
1686    // How far the generatrix reaches from the axis — the scale every "is this
1687    // control point on the axis?" question below is measured against.
1688    let mut radial_extent: f64 = 0.0;
1689    for control_point in &generatrix.control_points {
1690        let point = control_point.point()?;
1691        let offset = point.sub(axis_point);
1692        radial_extent = radial_extent.max(offset.sub(axis.scale(offset.dot(axis))).length());
1693    }
1694
1695    for (column, control_point) in generatrix.control_points.iter().enumerate() {
1696        let point = control_point.point()?;
1697        let weight = control_point.w;
1698        let axis_origin = axis_point.add(axis.scale(point.sub(axis_point).dot(axis)));
1699        let radial_vector = point.sub(axis_origin);
1700        // On-axis classification must be RELATIVE like the fuzzy band below:
1701        // the absolute EPS floor alone broke when the importer's mm conversion
1702        // scaled vendor pole noise (1.5e-13 m -> 1.5e-10 mm) past it, hard-
1703        // rejecting files whose poles are intended on-axis. 1e-8 of the radial
1704        // extent snaps that noise to an EXACT pole (radius 0, so every
1705        // downstream `radius <= EPS` branch takes the degenerate path):
1706        // corpus vendor noise measures up to ~2e-9 relative, and the
1707        // 1e-6-relative nudge the fuzzy-pole test rejects stays two decades
1708        // above the snap.
1709        let measured_radius = radial_vector.length();
1710        let pole_tolerance = EPS.max(1e-8 * radial_extent);
1711        let radius = if measured_radius <= pole_tolerance {
1712            0.0
1713        } else {
1714            measured_radius
1715        };
1716        let (x_axis, y_axis) = if radius <= EPS {
1717            (Vec3::default(), Vec3::default())
1718        } else {
1719            // A control point is either ON the axis — the degenerate pole row
1720            // above, whose rotation is a fixed point — or clearly off it. In
1721            // between the revolution carries a fuzzy PINCH where a pole was
1722            // meant to be, which downstream code (analytic recognition, pair
1723            // classification, the imprint) reads as an ordinary tiny circle:
1724            // refuse it here instead. This refusal used to fall out of the
1725            // parallel-tangent guard below, whose ABSOLUTE floor made it
1726            // "radius <= 1e-3" — which on a metre-unit STEP file rejected every
1727            // healthy 1.524e-4 cylinder in the part. Relative to the
1728            // generatrix's own radial extent it catches the fuzzy pole at any
1729            // model scale and lets real geometry through at any size.
1730            if radius <= NEAR_AXIS_RELATIVE_TOLERANCE * radial_extent {
1731                return Err(format!(
1732                    "makeRevolution: generatrix control point {column} sits {radius:e} from the \
1733                     axis, neither on it nor clear of it against the generatrix's {radial_extent:e} \
1734                     radial extent (a fuzzy pole)"
1735                ));
1736            }
1737            let x_axis = radial_vector.scale(1.0 / radius);
1738            (x_axis, axis.cross(x_axis))
1739        };
1740        rows[0][column] = Vec4::from_point(point, weight);
1741        let mut start_point = point;
1742        let mut start_tangent = y_axis.scale(radius);
1743        let mut angle = 0.0;
1744        for arc in 1..=arc_count {
1745            angle += arc_angle;
1746            let end_point = if radius <= EPS {
1747                point
1748            } else {
1749                axis_origin
1750                    .add(x_axis.scale(radius * angle.cos()))
1751                    .add(y_axis.scale(radius * angle.sin()))
1752            };
1753            let end_tangent = if radius <= EPS {
1754                Vec3::default()
1755            } else {
1756                x_axis
1757                    .scale(-radius * angle.sin())
1758                    .add(y_axis.scale(radius * angle.cos()))
1759            };
1760            let row = 2 * (arc - 1);
1761            if radius <= EPS {
1762                rows[row + 1][column] = Vec4::from_point(point, weight * middle_weight);
1763            } else {
1764                let cross = start_tangent.cross(end_tangent);
1765                let denominator = cross.length_squared();
1766                // Both tangents have length `radius`, so `denominator` is
1767                // radius^4 * sin^2(arc_angle) and an ABSOLUTE floor here reads
1768                // as "radius <= 1e-3", conflating a small part with a
1769                // degenerate sweep. Parallel tangents are purely an ANGULAR
1770                // condition, so scale the floor by the tangent lengths: the
1771                // test becomes sin^2(arc_angle) <= EPS, exactly what make_arc
1772                // applies to its already-unit tangents. Near-axis control
1773                // points are the near-axis check's business, above.
1774                let tangent_scale = start_tangent.length_squared() * end_tangent.length_squared();
1775                if denominator <= EPS * tangent_scale {
1776                    return Err("makeRevolution: arc tangents are parallel".into());
1777                }
1778                let distance =
1779                    end_point.sub(start_point).cross(end_tangent).dot(cross) / denominator;
1780                let middle = start_point.add(start_tangent.scale(distance));
1781                rows[row + 1][column] = Vec4::from_point(middle, weight * middle_weight);
1782            }
1783            rows[row + 2][column] = Vec4::from_point(end_point, weight);
1784            start_point = end_point;
1785            start_tangent = end_tangent;
1786        }
1787    }
1788    NurbsSurface::new(
1789        2,
1790        generatrix.degree,
1791        knots_u,
1792        generatrix.knots.clone(),
1793        rows,
1794    )
1795}
1796
1797pub fn make_cylinder_surface(
1798    base: Vec3,
1799    axis_direction: Vec3,
1800    radius: f64,
1801    height: f64,
1802) -> Result<NurbsSurface, String> {
1803    if radius <= EPS || height <= EPS {
1804        return Err("makeCylinder: radius and height must be positive".into());
1805    }
1806    let axis = axis_direction.normalized()?;
1807    let x_axis = axis.perpendicular()?;
1808    let start = base.add(x_axis.scale(radius));
1809    let end = start.add(axis.scale(height));
1810    let generatrix = crate::make_line(start, end)?;
1811    make_revolution(base, axis, &generatrix, std::f64::consts::TAU)
1812}
1813
1814pub fn make_cone_surface(
1815    base: Vec3,
1816    axis_direction: Vec3,
1817    radius_bottom: f64,
1818    radius_top: f64,
1819    height: f64,
1820) -> Result<NurbsSurface, String> {
1821    if radius_bottom <= EPS || radius_top < 0.0 || height <= EPS {
1822        return Err("makeCone: invalid radius or height".into());
1823    }
1824    let axis = axis_direction.normalized()?;
1825    let x_axis = axis.perpendicular()?;
1826    let start = base.add(x_axis.scale(radius_bottom));
1827    let end = base.add(axis.scale(height)).add(x_axis.scale(radius_top));
1828    let generatrix = crate::make_line(start, end)?;
1829    make_revolution(base, axis, &generatrix, std::f64::consts::TAU)
1830}
1831
1832pub fn make_sphere_surface(
1833    center: Vec3,
1834    radius: f64,
1835    polar_axis: Vec3,
1836) -> Result<NurbsSurface, String> {
1837    make_sphere_surface_framed(center, radius, polar_axis, None)
1838}
1839
1840/// A sphere with BOTH halves of its frame chosen: the polar axis (where the two
1841/// degenerate poles sit) and the SEAM direction (where the `u = 0` meridian
1842/// runs). `seam_direction` is Gram-Schmidt'd against the axis; `None` — and a
1843/// seam parallel to the axis, which names no meridian — falls back to
1844/// [`Vec3::perpendicular`], i.e. exactly what [`make_sphere_surface`] builds.
1845///
1846/// A caller that KNOWS where the sphere will be trimmed uses this to park the
1847/// poles and the seam inside the region the trim removes, so the surviving face
1848/// carries neither. `feature_pipeline::features::tube` does that for its joint
1849/// balls: a seam that survives into the result is an edge bordering ONE face,
1850/// which is a real edge in the topology and a visible line on the model.
1851pub fn make_sphere_surface_framed(
1852    center: Vec3,
1853    radius: f64,
1854    polar_axis: Vec3,
1855    seam_direction: Option<Vec3>,
1856) -> Result<NurbsSurface, String> {
1857    if radius <= EPS {
1858        return Err("makeSphere: radius must be positive".into());
1859    }
1860    let axis = polar_axis.normalized()?;
1861    let x_axis = match seam_direction {
1862        Some(seam) => {
1863            let planar = seam.sub(axis.scale(seam.dot(axis)));
1864            match planar.normalized() {
1865                Ok(unit) if planar.length() > EPS => unit,
1866                _ => axis.perpendicular()?,
1867            }
1868        }
1869        None => axis.perpendicular()?,
1870    };
1871    let meridian = crate::make_arc(
1872        center,
1873        x_axis,
1874        axis,
1875        radius,
1876        -std::f64::consts::FRAC_PI_2,
1877        std::f64::consts::FRAC_PI_2,
1878    )?;
1879    make_revolution(center, axis, &meridian, std::f64::consts::TAU)
1880}
1881
1882pub fn make_torus_surface(
1883    center: Vec3,
1884    axis_direction: Vec3,
1885    major_radius: f64,
1886    minor_radius: f64,
1887) -> Result<NurbsSurface, String> {
1888    if minor_radius <= EPS || major_radius <= minor_radius {
1889        return Err("makeTorus: requires positive minorRadius < majorRadius".into());
1890    }
1891    let axis = axis_direction.normalized()?;
1892    let x_axis = axis.perpendicular()?;
1893    let tube_center = center.add(x_axis.scale(major_radius));
1894    let tube = crate::make_arc(
1895        tube_center,
1896        x_axis,
1897        axis,
1898        minor_radius,
1899        0.0,
1900        std::f64::consts::TAU,
1901    )?;
1902    make_revolution(center, axis, &tube, std::f64::consts::TAU)
1903}
1904
1905fn binomial(n: usize, k: usize) -> f64 {
1906    if k > n {
1907        return 0.0;
1908    }
1909    let k = k.min(n - k);
1910    (1..=k).fold(1.0, |value, index| {
1911        value * (n - k + index) as f64 / index as f64
1912    })
1913}
1914
1915
1916
1917/// Diagnostic "carrier preview" patch (§3.15 applied to display): re-express
1918/// the surface over an INFLATED domain so an inspector can show where the
1919/// carrier continues beyond the face's trim. Open directions inflate about
1920/// the domain centre by `inflate` (a factor; 1 = unchanged), evaluated
1921/// through `evaluate_extended` — exact linear extension for affine carriers,
1922/// ruled/tangent extension generally. CLOSED (periodic) directions keep the
1923/// stored full period instead of inflating — wrapping further would overlap
1924/// the surface onto itself. A torus (closed both ways) returns unchanged.
1925///
1926/// Affine carriers rebuild EXACTLY from four extended corners; everything
1927/// else is a preview-quality degree-3 interpolation over a 33-sample grid.
1928pub fn carrier_preview_patch(surface: &NurbsSurface, inflate: f64) -> Result<NurbsSurface, String> {
1929    let inflate = if inflate.is_finite() {
1930        inflate.clamp(1.0, 16.0)
1931    } else {
1932        2.0
1933    };
1934    let (closed_u, closed_v) = surface.closed_directions()?;
1935    let [u0, u1] = surface.domain_u()?;
1936    let [v0, v1] = surface.domain_v()?;
1937    let stretch = |d0: f64, d1: f64, closed: bool| -> (f64, f64) {
1938        if closed || inflate <= 1.0 {
1939            (d0, d1)
1940        } else {
1941            let centre = 0.5 * (d0 + d1);
1942            let half = 0.5 * (d1 - d0) * inflate;
1943            (centre - half, centre + half)
1944        }
1945    };
1946    let (nu0, nu1) = stretch(u0, u1, closed_u);
1947    let (nv0, nv1) = stretch(v0, v1, closed_v);
1948    if (nu0, nu1) == (u0, u1) && (nv0, nv1) == (v0, v1) {
1949        return Ok(surface.clone());
1950    }
1951    if surface.is_affine()? {
1952        // Exact: the linear extension of an affine patch is the same affine
1953        // map over the larger rectangle.
1954        let corners = [
1955            surface.evaluate_extended(nu0, nv0)?,
1956            surface.evaluate_extended(nu1, nv0)?,
1957            surface.evaluate_extended(nu0, nv1)?,
1958            surface.evaluate_extended(nu1, nv1)?,
1959        ];
1960        return NurbsSurface::new(
1961            1,
1962            1,
1963            vec![nu0, nu0, nu1, nu1],
1964            vec![nv0, nv0, nv1, nv1],
1965            vec![
1966                vec![
1967                    Vec4::from_point(corners[0], 1.0),
1968                    Vec4::from_point(corners[2], 1.0),
1969                ],
1970                vec![
1971                    Vec4::from_point(corners[1], 1.0),
1972                    Vec4::from_point(corners[3], 1.0),
1973                ],
1974            ],
1975        );
1976    }
1977    const SAMPLES: usize = 32;
1978    let u_params: Vec<f64> = (0..=SAMPLES)
1979        .map(|index| nu0 + (nu1 - nu0) * index as f64 / SAMPLES as f64)
1980        .collect();
1981    let v_params: Vec<f64> = (0..=SAMPLES)
1982        .map(|index| nv0 + (nv1 - nv0) * index as f64 / SAMPLES as f64)
1983        .collect();
1984    // Two-pass grid interpolation: fit each v-column, then fit the resulting
1985    // control rows across u, sharing knots per pass (identical parameters).
1986    let mut column_curves = Vec::with_capacity(u_params.len());
1987    for &u in &u_params {
1988        let column: Vec<Vec3> = v_params
1989            .iter()
1990            .map(|&v| surface.evaluate_extended(u, v))
1991            .collect::<Result<_, _>>()?;
1992        column_curves.push(crate::interpolate_curve(
1993            &column,
1994            3,
1995            &normalized(&v_params),
1996        )?);
1997    }
1998    let v_knots = column_curves[0].knots.clone();
1999    let control_rows = column_curves[0].control_points.len();
2000    let mut grid: Vec<Vec<Vec4>> = Vec::with_capacity(u_params.len());
2001    let mut u_knots = Vec::new();
2002    for row_index in 0..control_rows {
2003        let row: Vec<Vec3> = column_curves
2004            .iter()
2005            .map(|curve| curve.control_points[row_index].point())
2006            .collect::<Result<_, _>>()?;
2007        let fitted = crate::interpolate_curve(&row, 3, &normalized(&u_params))?;
2008        u_knots = fitted.knots.clone();
2009        for (u_index, control) in fitted.control_points.iter().enumerate() {
2010            if grid.len() <= u_index {
2011                grid.push(Vec::new());
2012            }
2013            grid[u_index].push(*control);
2014        }
2015    }
2016    // Re-scale the normalized fit knots back onto the inflated domains so the
2017    // preview's parameter space lines up with the original surface's.
2018    let rescale = |knots: &[f64], d0: f64, d1: f64| -> Vec<f64> {
2019        knots.iter().map(|k| d0 + (d1 - d0) * k).collect()
2020    };
2021    NurbsSurface::new(
2022        3,
2023        3,
2024        rescale(&u_knots, nu0, nu1),
2025        rescale(&v_knots, nv0, nv1),
2026        grid,
2027    )
2028}
2029
2030fn normalized(parameters: &[f64]) -> Vec<f64> {
2031    let first = parameters[0];
2032    let last = parameters[parameters.len() - 1];
2033    parameters
2034        .iter()
2035        .map(|p| (p - first) / (last - first))
2036        .collect()
2037}
2038
2039
2040
2041
2042
2043fn analytic_deriv1_on() -> bool {
2044    switch!("BREP_ANALYTIC_DERIV1", true)
2045}
2046
2047
2048/// Default-off until the evaluator's bitwise and complete-body gates qualify it.
2049fn analytic_point_on() -> bool {
2050    switch!("BREP_ANALYTIC_POINT", false)
2051}
2052
2053/// SMALL DERIVATIVES (lane O row 20, 2026-10-29; on by default since the batch 5
2054/// promotion, `BREP_SURFACE_SMALL_DERIVATIVES=0` reads the heap grid): `evaluate_extended`, `derivatives_extended` up to second order,
2055/// `normal` and `principal_curvatures` read the stack twin
2056/// [`NurbsSurface::derivatives_small`] instead of the heap grid. A third of the
2057/// D2 outward shell's heap allocations were `NurbsSurface::derivatives` (a
2058/// sampled-backtrace allocation census); the values are the same bits.
2059pub fn small_derivatives_enabled() -> bool {
2060    switch!("BREP_SURFACE_SMALL_DERIVATIVES", true)
2061}
2062
2063
2064
2065
2066
2067