Skip to main content

brep_kernel/geometry/
surface.rs

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