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