Skip to main content

brep_surface_offset/offset/
offset.rs

1use crate::{KernelRefusal, KernelStage, OrRefuse};
2use crate::fit::{solve_dense, solve_dense_shared};
3pub use crate::topology::{BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, VertexRecord};
4pub use crate::{
5    interpolate_curve, measure_edge_against_pcurve_image,
6    measure_surface_fit_against_pointwise_offset, offset_construction_band, solid_model_scale,
7    vertex_endpoint_gap, vertex_tolerance_from_edges, KnotVector, MeasuredTolerance, NurbsCurve,
8    NurbsSurface, OffsetEvaluator, OffsetNormal, Vec2, Vec3, Vec4,
9};
10use rustc_hash::FxHashMap as HashMap;
11use serde::Serialize;
12
13fn domains(surface: &NurbsSurface) -> Result<([f64; 2], [f64; 2]), KernelRefusal> {
14    Ok((
15        KnotVector::new(surface.knots_u.clone(), surface.degree_u).or_refuse(KernelStage::Refine, "new")?.domain(),
16        KnotVector::new(surface.knots_v.clone(), surface.degree_v).or_refuse(KernelStage::Refine, "new")?.domain(),
17    ))
18}
19
20/// The normal `offset_surface` offsets along: the face's oriented normal with
21/// the singular-row recovery, i.e. the shared evaluator's
22/// [`OffsetNormal::FaceStable`] lane, whose body this function used to be.
23fn stable_face_normal(face: &FaceRecord, u: f64, v: f64) -> Result<Vec3, KernelRefusal> {
24    OffsetEvaluator::new(
25        "offset_surface",
26        &face.surface,
27        OffsetNormal::FaceStable {
28            same_sense: face.same_sense,
29        },
30    )
31    .normal(u, v)
32    .or_refuse(KernelStage::Refine, "normal")
33}
34
35pub fn greville_parameters(knots: &KnotVector) -> Vec<f64> {
36    let mut parameters = (0..knots.control_point_count())
37        .map(|index| {
38            knots.knots[index + 1..=index + knots.degree]
39                .iter()
40                .sum::<f64>()
41                / knots.degree as f64
42        })
43        .collect::<Vec<_>>();
44    let domain = knots.domain();
45    parameters[0] = domain[0];
46    *parameters.last_mut().unwrap() = domain[1];
47    parameters
48}
49
50/// Rational collocation matrix: rows are the rational basis functions
51/// R_i(t) = N_i(t)·w_i / Σ_k N_k(t)·w_k evaluated at each parameter. With
52/// uniform weights this reduces to the ordinary B-spline collocation matrix.
53fn collocation_matrix(knots: &KnotVector, parameters: &[f64], weights: &[f64]) -> Vec<Vec<f64>> {
54    parameters
55        .iter()
56        .map(|parameter| {
57            let mut row = vec![0.0; knots.control_point_count()];
58            let span = knots.find_span(*parameter);
59            for (offset, value) in knots
60                .basis_functions(span, *parameter)
61                .into_iter()
62                .enumerate()
63            {
64                let index = span - knots.degree + offset;
65                row[index] = value * weights[index];
66            }
67            let denominator: f64 = row.iter().sum();
68            if denominator.abs() > 0.0 {
69                for value in &mut row {
70                    *value /= denominator;
71                }
72            }
73            row
74        })
75        .collect()
76}
77
78/// Split the weight grid into per-direction factors when it is separable
79/// (w_ij = a_i·b_j), which covers every tensor surface built from rational
80/// profile/rail curves (cylinders, cones, spheres, tori, revolves).
81fn separable_weights(weights: &[Vec<f64>]) -> Option<(Vec<f64>, Vec<f64>)> {
82    let first_row = weights.first()?;
83    let anchor = *first_row.first()?;
84    if anchor.abs() <= 1e-12 {
85        return None;
86    }
87    let a: Vec<f64> = weights.iter().map(|row| row[0]).collect();
88    let b: Vec<f64> = first_row.iter().map(|w| w / anchor).collect();
89    for (i, row) in weights.iter().enumerate() {
90        for (j, &w) in row.iter().enumerate() {
91            if (w - a[i] * b[j]).abs() > 1e-10 * (1.0 + w.abs()) {
92                return None;
93            }
94        }
95    }
96    Some((a, b))
97}
98
99/// Interpolate the sample grid in the SOURCE surface's rational basis (same
100/// knots and weights). When the true offset is representable in that basis —
101/// planes, cylinders, cones, spheres, tori — collocation at the Greville grid
102/// recovers it EXACTLY, so offset carriers stay real analytic surfaces
103/// instead of non-rational approximations with span-scale wobble.
104pub fn interpolate_tensor(
105    knot_u: &KnotVector,
106    knot_v: &KnotVector,
107    parameters_u: &[f64],
108    parameters_v: &[f64],
109    samples: &[Vec<Vec3>],
110    weights: &[Vec<f64>],
111) -> Result<Vec<Vec<Vec4>>, KernelRefusal> {
112    let count_u = parameters_u.len();
113    let count_v = parameters_v.len();
114    if let Some((weights_u, weights_v)) = separable_weights(weights) {
115        let matrix_u = collocation_matrix(knot_u, parameters_u, &weights_u);
116        let matrix_v = collocation_matrix(knot_v, parameters_v, &weights_v);
117        // Each column's three coordinates share one elimination
118        // (`solve_dense_shared`, the bits of three `solve_dense` calls on
119        // clones). The collocation matrix is banded, and the dense solve spent
120        // `n^3` on products with zero: ABC 00027566 offsets 82 extruded cubics
121        // whose fit refines to 1239 x 2, 13.7 s a face, and the STEP import
122        // never finished (2026-11-10).
123        let mut intermediate = vec![vec![Vec3::default(); count_v]; count_u];
124        for column in 0..count_v {
125            let side = |axis: fn(Vec3) -> f64| samples.iter().map(|row| axis(row[column])).collect::<Vec<_>>();
126            let [x, y, z] = solve_dense_shared(matrix_u.clone(), [side(|point| point.x), side(|point| point.y), side(|point| point.z)])
127                .or_refuse(KernelStage::Refine, "solve_axis")?;
128            for row in 0..count_u {
129                intermediate[row][column] = Vec3::new(x[row], y[row], z[row]);
130            }
131        }
132        let mut controls = vec![vec![Vec4::from_point(Vec3::default(), 1.0); count_v]; count_u];
133        for row in 0..count_u {
134            let side = |axis: fn(Vec3) -> f64| intermediate[row].iter().copied().map(axis).collect::<Vec<_>>();
135            let [x, y, z] = solve_dense_shared(matrix_v.clone(), [side(|point| point.x), side(|point| point.y), side(|point| point.z)])
136                .or_refuse(KernelStage::Refine, "solve_axis")?;
137            for column in 0..count_v {
138                controls[row][column] = Vec4::from_point(
139                    Vec3::new(x[column], y[column], z[column]),
140                    weights[row][column],
141                );
142            }
143        }
144        return Ok(controls);
145    }
146
147    // Non-separable weights: solve the full tensor collocation system with
148    // the exact 2D rational basis. Nets are small in practice.
149    let unknowns = count_u * count_v;
150    let mut matrix = vec![vec![0.0; unknowns]; unknowns];
151    for (k, &u) in parameters_u.iter().enumerate() {
152        let span_u = knot_u.find_span(u);
153        let basis_u = knot_u.basis_functions(span_u, u);
154        for (l, &v) in parameters_v.iter().enumerate() {
155            let span_v = knot_v.find_span(v);
156            let basis_v = knot_v.basis_functions(span_v, v);
157            let row = &mut matrix[k * count_v + l];
158            let mut denominator = 0.0;
159            for (du, value_u) in basis_u.iter().enumerate() {
160                let i = span_u - knot_u.degree + du;
161                for (dv, value_v) in basis_v.iter().enumerate() {
162                    let j = span_v - knot_v.degree + dv;
163                    let entry = value_u * value_v * weights[i][j];
164                    row[i * count_v + j] = entry;
165                    denominator += entry;
166                }
167            }
168            if denominator.abs() > 0.0 {
169                for value in row.iter_mut() {
170                    *value /= denominator;
171                }
172            }
173        }
174    }
175    let solve_axis = |axis: fn(Vec3) -> f64| {
176        solve_dense(
177            matrix.clone(),
178            samples
179                .iter()
180                .flat_map(|row| row.iter().copied().map(axis))
181                .collect(),
182        )
183    };
184    let x = solve_axis(|point| point.x).or_refuse(KernelStage::Refine, "solve_axis")?;
185    let y = solve_axis(|point| point.y).or_refuse(KernelStage::Refine, "solve_axis")?;
186    let z = solve_axis(|point| point.z).or_refuse(KernelStage::Refine, "solve_axis")?;
187    let mut controls = vec![vec![Vec4::from_point(Vec3::default(), 1.0); count_v]; count_u];
188    for row in 0..count_u {
189        for column in 0..count_v {
190            let index = row * count_v + column;
191            controls[row][column] = Vec4::from_point(
192                Vec3::new(x[index], y[index], z[index]),
193                weights[row][column],
194            );
195        }
196    }
197    Ok(controls)
198}
199
200/// Which branch of [`offset_surface`] built a carrier — and, with it, whether
201/// comparing that carrier against the pointwise offset at the same `(u, v)` is
202/// even the right question.
203///
204/// Recorded rather than inferred, in the pattern `offset/reintersect.rs`
205/// established for its own two lanes: two of this function's three branches
206/// deliberately move the result off the pointwise offset, and a measurement that
207/// did not know which branch ran would report a designed divergence as a fit
208/// error.
209#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
210pub enum OffsetSurfaceLane {
211    /// A rigid control-net shift of an affine (plane-like) carrier. The normal
212    /// is constant, so the shifted net IS the pointwise offset — exact by
213    /// construction, with no fit to measure.
214    Affine,
215    /// A CLOSED-FORM offset built from the source's recognized analytic shape
216    /// rather than sampled: a sphere's concentric mate, whose net is the
217    /// source's scaled about the centre. Exact like `Affine`, but derived from
218    /// geometry the recognizer proved rather than from a constant normal, so
219    /// `offset_surface_measured_sided` measures it instead of declaring it.
220    Analytic,
221    /// Greville collocation of the pointwise offset. `S_fit(u, v)` is meant to
222    /// BE `offset(u, v)`, and the distance between them is the fit error this
223    /// slice measures.
224    #[default]
225    Fit,
226    /// The result was deliberately moved off the pointwise offset: the planar /
227    /// ruled EXTENSION (which grows the carrier past its source rim, so the same
228    /// `(u, v)` names a different point) or the apex-cone PINCH RETRIM (which
229    /// pulls the crossed sample row back to the offset cone's own apex). Both
230    /// are correct and intended; neither is comparable pointwise.
231    Reparameterised,
232}
233
234/// A fitted offset carrier together with what its construction measured about
235/// itself.
236#[derive(Clone, Debug)]
237pub struct MeasuredOffsetSurface {
238    pub surface: NurbsSurface,
239    pub lane: OffsetSurfaceLane,
240    /// `max ‖S_fit(u, v) − offset(u, v)‖` over
241    /// [`crate::measure_surface_fit_against_pointwise_offset`]'s grid, against
242    /// the band it was judged with. When the RULED EXTENSION fired, the offset
243    /// compared against is the offset of the source EXTENDED ALONG ITS RULINGS —
244    /// the surface the carrier is the pointwise offset of — not of `face.surface`.
245    ///
246    /// `None` for [`OffsetSurfaceLane::Reparameterised`] — see that variant.
247    pub fit: Option<MeasuredTolerance>,
248}
249
250/// How far an offset carrier's TRIM grows past the source face at each of
251/// its four parametric sides, in world units.
252///
253/// A carrier is trimmed by the parametric IMAGE of the source loops, so the
254/// growth is realised by reshaping the carrier surface's net while the cloned
255/// pcurves stay put: an affine plane's 2x2 net slides along the plane, a ruled
256/// (linear-v) net stretches each sampled ruling. Both are solved so that the
257/// trim's own uv bounding box moves by exactly these amounts — a trim that
258/// occupies a sub-range of its surface's domain (every booleaned or
259/// blend-trimmed face) grows by the same distance as one that spans it. The
260/// legacy `planar_extension: f64` entry points are the uniform case.
261#[derive(Clone, Copy, Debug, PartialEq)]
262pub struct CarrierExtension {
263    pub u_min: f64,
264    pub u_max: f64,
265    pub v_min: f64,
266    pub v_max: f64,
267}
268
269impl CarrierExtension {
270    pub const NONE: CarrierExtension = CarrierExtension {
271        u_min: 0.0,
272        u_max: 0.0,
273        v_min: 0.0,
274        v_max: 0.0,
275    };
276
277    pub fn uniform(amount: f64) -> CarrierExtension {
278        CarrierExtension {
279            u_min: amount,
280            u_max: amount,
281            v_min: amount,
282            v_max: amount,
283        }
284    }
285
286    pub fn is_active(&self) -> bool {
287        self.u_min > 0.0 || self.u_max > 0.0 || self.v_min > 0.0 || self.v_max > 0.0
288    }
289
290    fn extends_v(&self) -> bool {
291        self.v_min > 0.0 || self.v_max > 0.0
292    }
293}
294
295/// Golden-section steps [`refine_trim_extreme`] takes: the bracket shrinks to
296/// 0.618^64 ≈ 4e-14 of two sample spacings, past where the extreme's value
297/// can still move (it is quadratic in the parameter there).
298const TRIM_EXTREME_STEPS: usize = 64;
299
300/// The extreme of `sign · uv[axis]` (`axis` 0 is u, 1 is v) over one pcurve,
301/// returned as the coordinate itself. Bracketed by the pcurve's best sample
302/// and that sample's two neighbours, and closed by a golden-section search of
303/// a fixed [`TRIM_EXTREME_STEPS`] steps; never worse than the best sample.
304/// On an arc the bracketed piece is unimodal, so this is its true extreme.
305/// A line's extremes are its ends, which are samples, so the caller does not
306/// search one (an interior read of a straight trim can land an ulp past its
307/// end).
308fn refine_trim_extreme(
309    pcurve: &NurbsCurve,
310    samples: &[(f64, Vec3)],
311    axis: usize,
312    sign: f64,
313) -> Result<f64, KernelRefusal> {
314    let read = |uv: Vec3| sign * if axis == 0 { uv.x } else { uv.y };
315    let at = |parameter: f64| -> Result<f64, KernelRefusal> {
316        Ok(read(pcurve.evaluate(parameter).or_refuse(KernelStage::Refine, "evaluate")?))
317    };
318    let best = (0..samples.len())
319        .max_by(|&a, &b| read(samples[a].1).total_cmp(&read(samples[b].1)))
320        .expect("a pcurve has samples");
321    let mut found = read(samples[best].1);
322    let (mut a, mut b) = (samples[best.saturating_sub(1)].0, samples[(best + 1).min(samples.len() - 1)].0);
323    const GOLDEN: f64 = 0.618_033_988_749_894_9;
324    let mut c = b - GOLDEN * (b - a);
325    let mut d = a + GOLDEN * (b - a);
326    let (mut fc, mut fd) = (at(c)?, at(d)?);
327    for _ in 0..TRIM_EXTREME_STEPS {
328        found = found.max(fc).max(fd);
329        if fc >= fd {
330            (b, d, fd) = (d, c, fc);
331            c = b - GOLDEN * (b - a);
332            fc = at(c)?;
333        } else {
334            (a, c, fc) = (c, d, fd);
335            d = a + GOLDEN * (b - a);
336            fd = at(d)?;
337        }
338    }
339    Ok(sign * found.max(fc).max(fd))
340}
341
342/// The trim's uv bounding box as FRACTIONS of the surface domain:
343/// `([ta_u, tb_u], [ta_v, tb_v])`, each in `[0, 1]`. Sampled over every
344/// coedge pcurve of every loop, and closed on the pcurves' true extremes
345/// (lane R2 row 9, 2026-10-19: the slide is solved for that box, so a box
346/// short of the trim slides the net unevenly).
347fn trim_domain_fractions(
348    face: &FaceRecord,
349    [u0, u1]: [f64; 2],
350    [v0, v1]: [f64; 2],
351) -> Result<([f64; 2], [f64; 2]), KernelRefusal> {
352    let mut low = Vec2 {
353        x: f64::INFINITY,
354        y: f64::INFINITY,
355    };
356    let mut high = Vec2 {
357        x: f64::NEG_INFINITY,
358        y: f64::NEG_INFINITY,
359    };
360    for coedge in face
361        .loops
362        .iter()
363        .flat_map(|loop_record| &loop_record.coedges)
364    {
365        let [p0, p1] = coedge.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
366        let mut samples = Vec::with_capacity(25);
367        for sample in 0..=24 {
368            let parameter = p0 + (p1 - p0) * sample as f64 / 24.0;
369            let uv = coedge
370                .pcurve
371                .evaluate(parameter).or_refuse(KernelStage::Refine, "evaluate")?;
372            low.x = low.x.min(uv.x);
373            low.y = low.y.min(uv.y);
374            high.x = high.x.max(uv.x);
375            high.y = high.y.max(uv.y);
376            samples.push((parameter, uv));
377        }
378        if coedge.pcurve.degree > 1 {
379            low.x = low.x.min(refine_trim_extreme(&coedge.pcurve, &samples, 0, -1.0)?);
380            high.x = high.x.max(refine_trim_extreme(&coedge.pcurve, &samples, 0, 1.0)?);
381            low.y = low.y.min(refine_trim_extreme(&coedge.pcurve, &samples, 1, -1.0)?);
382            high.y = high.y.max(refine_trim_extreme(&coedge.pcurve, &samples, 1, 1.0)?);
383        }
384    }
385    let fraction = |value: f64, start: f64, end: f64| {
386        let span = end - start;
387        if span.abs() <= f64::EPSILON || !value.is_finite() {
388            return None;
389        }
390        Some(((value - start) / span).clamp(0.0, 1.0))
391    };
392    let u = match (fraction(low.x, u0, u1), fraction(high.x, u0, u1)) {
393        (Some(a), Some(b)) if b - a > 1e-6 => [a, b],
394        _ => [0.0, 1.0],
395    };
396    let v = match (fraction(low.y, v0, v1), fraction(high.y, v0, v1)) {
397        (Some(a), Some(b)) if b - a > 1e-6 => [a, b],
398        _ => [0.0, 1.0],
399    };
400    Ok((u, v))
401}
402
403/// How far the surface's domain ENDS must move (`(back, forward)`: the start
404/// end backwards, the far end forwards, world units) so that a trim occupying
405/// the domain fractions `[ta, tb]` grows by exactly `grow_min` at its start and
406/// `grow_max` at its end when its pcurves are left untouched. A point at
407/// fraction `t` of a linearly re-mapped domain moves by
408/// `-(1 - t)·back + t·forward`; solving that at `ta` and `tb` gives the pair
409/// below. It reduces to `(grow_min, grow_max)` for a full-domain trim, and
410/// never shrinks either end (both results are non-negative for non-negative
411/// inputs).
412fn domain_end_moves(grow_min: f64, grow_max: f64, [ta, tb]: [f64; 2]) -> (f64, f64) {
413    let span = tb - ta;
414    if span <= 1e-6 {
415        return (grow_min, grow_max);
416    }
417    let rate = (grow_min + grow_max) / span;
418    let back = grow_min + ta * rate;
419    let forward = (1.0 - ta) * rate - grow_min;
420    (back.max(0.0), forward.max(0.0))
421}
422
423/// Construct the same fitted offset carrier surface as the reference shell
424/// implementation. Positive distance follows its convention and moves
425/// opposite the face's outward normal.
426pub fn offset_surface(
427    face: &FaceRecord,
428    distance: f64,
429    planar_extension: f64,
430) -> Result<NurbsSurface, KernelRefusal> {
431    offset_surface_with_lane(face, distance, &CarrierExtension::uniform(planar_extension))
432        .map(|(surface, _)| surface)
433}
434
435thread_local! {
436    pub static IMPORT_OFFSET_PRECISION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
437}
438
439/// Import needs the pointwise offset carrier, without the construction-fit
440/// floor becoming an accuracy limit for downstream surface integrals. Elevate
441/// the rational basis exactly before collocation: increasing approximation
442/// order resolves the normal field without a quadratic net's excessive span
443/// growth. The ordinary construction budget and acceptance gate still apply.
444pub fn offset_surface_for_import(face: &FaceRecord, distance: f64) -> Result<NurbsSurface, KernelRefusal> {
445    if face.surface.analytic().is_some() || face.surface.is_affine().or_refuse(KernelStage::Refine, "is_affine")? {
446        return offset_surface(face, distance, 0.0);
447    }
448    let source = &face.surface;
449    let mut rows = Vec::new();
450    let mut knots_v = source.knots_v.clone();
451    for row in &source.control_points {
452        let curve = NurbsCurve::new(source.degree_v, source.knots_v.clone(), row.clone()).or_refuse(KernelStage::Refine, "new")?;
453        let raised = crate::coons::compat::elevate_degree(&curve, source.degree_v.max(5)).or_refuse(KernelStage::Refine, "elevate_degree")?;
454        knots_v = raised.knots.clone();
455        rows.push(raised.control_points);
456    }
457    let mut columns = Vec::new();
458    let mut knots_u = source.knots_u.clone();
459    for column in 0..rows[0].len() {
460        let curve = NurbsCurve::new(source.degree_u, source.knots_u.clone(), rows.iter().map(|row| row[column]).collect()).or_refuse(KernelStage::Refine, "new")?;
461        let raised = crate::coons::compat::elevate_degree(&curve, source.degree_u.max(5)).or_refuse(KernelStage::Refine, "elevate_degree")?;
462        knots_u = raised.knots.clone();
463        columns.push(raised.control_points);
464    }
465    let controls = (0..columns[0].len()).map(|row| columns.iter().map(|column| column[row]).collect()).collect();
466    let mut elevated = face.clone();
467    elevated.surface = NurbsSurface::new(source.degree_u.max(5), source.degree_v.max(5), knots_u, knots_v, controls).or_refuse(KernelStage::Refine, "new")?;
468    // The normal differentiates the carrier once: a C^k source generally
469    // has a C^(k-1) offset field. Exact knot insertion leaves the source
470    // unchanged but lets collocation represent that lower continuity.
471    let interior = |knots: &[f64], degree: usize| {
472        let low = knots[degree];
473        let high = knots[knots.len() - degree - 1];
474        let mut values: Vec<f64> = knots.iter().copied().filter(|k| *k > low && *k < high).collect();
475        values.dedup();
476        values
477    };
478    elevated.surface = insert_offset_fit_knots(&elevated.surface,
479        &interior(&source.knots_u, source.degree_u),
480        &interior(&source.knots_v, source.degree_v))?;
481    struct Restore(bool);
482    impl Drop for Restore {
483        fn drop(&mut self) { IMPORT_OFFSET_PRECISION.with(|state| state.set(self.0)); }
484    }
485    let _restore = Restore(IMPORT_OFFSET_PRECISION.with(|state| state.replace(true)));
486    offset_surface(&elevated, distance, 0.0)
487}
488
489/// [`offset_surface`], plus the deviation MEASURED between the carrier it built
490/// and the pointwise offset that carrier approximates.
491///
492/// The surface is bit-identical to [`offset_surface`]'s — this calls the same
493/// body and adds a read-only pass afterwards. Nothing here can change the
494/// carrier: measuring the deviation AFTER the carrier is built records what
495/// happened; the size-derived band stays the floor and the bar it is judged
496/// against. A measurement never widens a band.
497pub fn offset_surface_measured(
498    face: &FaceRecord,
499    distance: f64,
500    planar_extension: f64,
501    band: f64,
502) -> Result<MeasuredOffsetSurface, KernelRefusal> {
503    offset_surface_measured_sided(
504        face,
505        distance,
506        &CarrierExtension::uniform(planar_extension),
507        band,
508    )
509}
510
511/// [`offset_surface_measured`] with a per-side [`CarrierExtension`].
512pub fn offset_surface_measured_sided(
513    face: &FaceRecord,
514    distance: f64,
515    extension: &CarrierExtension,
516    band: f64,
517) -> Result<MeasuredOffsetSurface, KernelRefusal> {
518    offset_surface_measured_sided_mode(face, distance, extension, band,
519        std::env::var("BREP_OFFSET_SPHERE_READING").map_or(true, |v| v != "0" && v != "off"))
520}
521
522fn offset_surface_measured_sided_mode(
523    face: &FaceRecord, distance: f64, extension: &CarrierExtension, band: f64, reuse: bool,
524) -> Result<MeasuredOffsetSurface, KernelRefusal> {
525    let mut sphere_reading = None;
526    let (surface, lane, extended) = offset_surface_constructed(face, distance, extension, &mut sphere_reading)?;
527    let fit = match lane {
528        OffsetSurfaceLane::Affine => Some(MeasuredTolerance::exact(band)),
529        // `Analytic` is exact by construction and already verified against the
530        // pointwise offset before it was returned — but it is measured here
531        // like a fit anyway, so the record carries the number instead of the
532        // claim. It reads ~1e-13 where `Fit` reads ~1e-6.
533        OffsetSurfaceLane::Analytic if reuse && sphere_reading.is_some() => {
534            // The construction already read this exact source/result pair on
535            // the same grid. Only the report band differs; it is not a grid
536            // input. Retain the measured deviation, never substitute zero.
537            if crate::profile::profile_enabled() {
538                profile_line!("offset.sphere_reading.profile reused=1");
539            }
540            Some(MeasuredTolerance::new(sphere_reading.unwrap(), band))
541        }
542        OffsetSurfaceLane::Analytic | OffsetSurfaceLane::Fit => {
543            Some(measure_surface_fit_against_pointwise_offset(
544                extended.as_ref().unwrap_or(&face.surface),
545                face.same_sense,
546                &surface,
547                distance,
548                band,
549            )?)
550        }
551        OffsetSurfaceLane::Reparameterised => None,
552    };
553    Ok(MeasuredOffsetSurface { surface, lane, fit })
554}
555
556/// The EXACT concentric offset of a sphere, or `None` for every other carrier.
557///
558/// A sphere's normal is radial, so its pointwise offset at distance `d` is the
559/// concentric sphere of radius `R' = R ± d`. A NURBS map is affine in its
560/// control points — `S = Σ N_i w_i P_i / Σ N_i w_i` — so scaling every control
561/// point about the centre by `R'/R` scales the whole image by that factor about
562/// that point, and the result IS that sphere to rounding. Knots, degrees and
563/// weights are untouched, so the same `(u, v)` still names the corresponding
564/// point: the trims `offset_face_carrier_impl` clones onto this carrier
565/// verbatim land exactly where they did on the source.
566///
567/// The Greville fit below reaches the same surface only to its collocation
568/// error. On `offset-shell-box-bore-dished-face` that error put the dished
569/// face's volume contribution 4.69e-3 away from the closed form — the larger
570/// share of the case's 3.9435e-3 deficit.
571///
572/// Everything here is COMPUTED, never claimed. The offset radius comes from the
573/// same [`OffsetEvaluator`] the fit lane samples, so this lane cannot invent a
574/// sign convention; the guards below reject a centre the recognizer got wrong
575/// or a sphere turned inside out by an inward offset deeper than its radius;
576/// and the finished net is checked against that evaluator on a grid before it
577/// is returned. Every refusal falls through to the fit, which is what built
578/// these carriers before.
579///
580/// A sphere the recognizer does not recognize — a FITTED patch that merely
581/// looks spherical — stays on the fit lane, unchanged. This lane widens nothing
582/// on its own: cylinders, cones and tori want a scaling about an axis or a
583/// spine rather than a point, which is a different construction.
584fn sphere_offset_surface(face: &FaceRecord, distance: f64, reading: &mut Option<f64>) -> Result<Option<NurbsSurface>, KernelRefusal> {
585    // Escape hatch, the same shape as `BREP_NO_SPHERE_CHARTS`: it makes the
586    // closed form and the collocation fit two cells of one binary, so a
587    // measurement can separate this lane's effect from everything else.
588    if std::env::var_os("BREP_NO_ANALYTIC_OFFSET").is_some() {
589        return Ok(None);
590    }
591    let source = &face.surface;
592    let Some((centre, radius)) = source.analytic().and_then(|shape| shape.sphere_geometry()) else {
593        return Ok(None);
594    };
595    let ([u0, u1], [v0, v1]) = domains(source)?;
596    // `offset_surface`'s positive distance moves OPPOSITE the face normal while
597    // the evaluator's moves ALONG it; the negation is the fit's own, reused
598    // here rather than re-derived (audit §4.1's hand negations get no new one).
599    // A normal this lane cannot read is a DECLINE, not an error: the fit below
600    // samples the same evaluator across the whole Greville grid and has its own
601    // singular-row recovery, so anything that offset before must still offset.
602    let Ok(sample) = OffsetEvaluator::new(
603        "offset_surface",
604        source,
605        OffsetNormal::FaceStable {
606            same_sense: face.same_sense,
607        },
608    )
609    .at((u0 + u1) / 2.0, (v0 + v1) / 2.0, -distance)
610    else {
611        return Ok(None);
612    };
613    let source_radial = sample.source.sub(centre);
614    let offset_radial = sample.point.sub(centre);
615    let offset_radius = offset_radial.length();
616    let scale = radius.max(1.0);
617    if radius <= 1e-12
618        || offset_radius <= 1e-9 * scale
619        // Offset through the centre and out the far side: the concentric mate
620        // is a sphere turned inside out, not this construction's answer.
621        || offset_radial.dot(source_radial) <= 0.0
622        // The move must be radial and exactly |d| long. A recognized centre
623        // that is not the real one fails here before it can scale anything.
624        || ((offset_radius - radius).abs() - distance.abs()).abs() > 1e-9 * scale
625    {
626        return Ok(None);
627    }
628    let factor = offset_radius / radius;
629    // A zero-weight control has no Euclidean point to scale. The fit lane never
630    // asks one for a position, so declining keeps this lane strictly additive.
631    let Ok(controls) = source
632        .control_points
633        .iter()
634        .map(|row| {
635            row.iter()
636                .map(|control| {
637                    Ok(Vec4::from_point(
638                        centre.add(control.point().or_refuse(KernelStage::Refine, "point")?.sub(centre).scale(factor)),
639                        control.w,
640                    ))
641                })
642                .collect::<Result<Vec<_>, KernelRefusal>>()
643        })
644        .collect::<Result<Vec<Vec<_>>, KernelRefusal>>()
645    else {
646        return Ok(None);
647    };
648    let Ok(surface) = NurbsSurface::new(
649        source.degree_u,
650        source.degree_v,
651        source.knots_u.clone(),
652        source.knots_v.clone(),
653        controls,
654    ) else {
655        return Ok(None);
656    };
657    // The claim, tested. A net that does not land on the pointwise offset
658    // everywhere is not this lane's surface, whatever it was recognized as —
659    // and a measurement that could not be taken is not a pass.
660    match crate::offset_measure::sphere_fit_reading(
661        source,
662        face.same_sense,
663        &surface,
664        distance,
665        1e-9 * scale,
666    ) {
667        Ok(measured) if measured.within_band() => {
668            *reading = Some(measured.deviation());
669            Ok(Some(surface))
670        },
671        _ => Ok(None),
672    }
673}
674
675/// The EXACT offset of a surface of REVOLUTION whose generatrix is ONE CIRCLE
676/// ARC — a torus of any kind (ring, horn, spindle), over a full or a partial
677/// sweep — or `None` for every other carrier.
678///
679/// Why it is exact. A revolution's normal lies in the meridian plane and equals
680/// the generatrix's own in-plane normal there, so the offset surface IS the
681/// revolution of the offset generatrix, and the offset of a circle arc of
682/// radius `r` about `c` is the concentric arc of radius `r ± d`. On the net:
683/// row `i` of a revolution's control net is an AFFINE image `A_i` of the
684/// generatrix's controls — a rotation for the on-circle rows, but a rotation
685/// STRETCHED radially by `1/cos` of the half-span for the mid rows, which is
686/// not a similarity. Affine maps commute with scaling about a point, so scaling
687/// row `i` about `C_i = A_i(c)` by `(r ± d)/r` is exactly `A_i` applied to the
688/// offset circle's net; that commutation is the only reason the stretched rows
689/// come out right. `C_i` is found without reading `A_i` at all: `c` is an affine
690/// combination of three generatrix controls, and the same combination of row
691/// `i`'s controls is `A_i(c)`. Knots, degrees and weights are untouched, so the
692/// same `(u, v)` still names the corresponding point and cloned trims land
693/// where they did, as on [`sphere_offset_surface`].
694///
695/// Everything is computed and then tested, never claimed. The generatrix is
696/// row 0 of the net, and it must lie on one circle to rounding. The sign and
697/// size of the move come from the same [`OffsetEvaluator`] the fit samples,
698/// read at a generatrix point against the circle's centre: the move must be
699/// radial and exactly `|d|` long, and an offset through the centre (`r − d ≤
700/// 0`, where the offset circle turns inside out) declines. The finished net
701/// must land on the pointwise offset everywhere on the measurement grid, to
702/// `1e-9` of the model's scale. Every decline falls through to the fit.
703///
704/// Measured on the partial lemon (a 106° arc of radius 5 centred 3 off the
705/// axis) shelled inward by 1: the fitted carrier sat 1.4e-5 off the pointwise
706/// offset and its shell 3.6e-7 short of the Pappus form in volume.
707fn revolved_arc_offset_surface(
708    face: &FaceRecord,
709    distance: f64,
710) -> Result<Option<NurbsSurface>, KernelRefusal> {
711    if std::env::var_os("BREP_NO_ANALYTIC_OFFSET").is_some() {
712        return Ok(None);
713    }
714    let source = &face.surface;
715    match source.analytic() {
716        Some(crate::AnalyticSurface::Revolution { .. } | crate::AnalyticSurface::Torus { .. }) => {}
717        _ => return Ok(None),
718    }
719    let rows = &source.control_points;
720    let Some(first_row) = rows.first() else {
721        return Ok(None);
722    };
723    if rows.iter().flatten().any(|control| !(control.w > 0.0)) {
724        return Ok(None);
725    }
726    let Ok(generatrix) = NurbsCurve::new(source.degree_v, source.knots_v.clone(), first_row.clone())
727    else {
728        return Ok(None);
729    };
730    let [t0, t1] = generatrix.domain().or_refuse(KernelStage::Refine, "domain")?;
731    let at = |fraction: f64| generatrix.evaluate(t0 + (t1 - t0) * fraction);
732    // The circle through three generatrix points, then every sample held to it.
733    let (a, b, e) = (at(0.0).or_refuse(KernelStage::Refine, "at")?, at(1.0 / 3.0).or_refuse(KernelStage::Refine, "at")?, at(2.0 / 3.0).or_refuse(KernelStage::Refine, "at")?);
734    let (ab, ae) = (b.sub(a), e.sub(a));
735    let normal = ab.cross(ae);
736    let normal_length_squared = normal.dot(normal);
737    let Some(centre) = crate::circumcenter(a, b, e) else { return Ok(None); };
738    let radius = a.sub(centre).length();
739    let scale = (centre.length() + radius).max(1.0);
740    let band = 1e-9 * scale;
741    let unit_normal = normal.scale(1.0 / normal_length_squared.sqrt());
742    let samples = 16 * generatrix.control_points.len();
743    for index in 0..=samples {
744        let point = at(index as f64 / samples as f64).or_refuse(KernelStage::Refine, "at")?;
745        let radial = point.sub(centre);
746        if (radial.length() - radius).abs() > band || radial.dot(unit_normal).abs() > band {
747            return Ok(None);
748        }
749    }
750    // `centre` as an affine combination of three generatrix controls, the best
751    // conditioned pair against the first.
752    let controls = first_row
753        .iter()
754        .map(|control| control.point().or_refuse(KernelStage::Refine, "point"))
755        .collect::<Result<Vec<_>, KernelRefusal>>()?;
756    let origin = controls[0];
757    let mut best = (0usize, 0usize, 0.0f64);
758    for first in 1..controls.len() {
759        for second in first + 1..controls.len() {
760            let area = controls[first]
761                .sub(origin)
762                .cross(controls[second].sub(origin))
763                .length();
764            if area > best.2 {
765                best = (first, second, area);
766            }
767        }
768    }
769    let (first, second, area) = best;
770    if area <= 1e-9 * scale * scale {
771        return Ok(None);
772    }
773    let (along_first, along_second) = (controls[first].sub(origin), controls[second].sub(origin));
774    let offset_from_origin = centre.sub(origin);
775    let (g11, g12, g22) = (
776        along_first.dot(along_first),
777        along_first.dot(along_second),
778        along_second.dot(along_second),
779    );
780    let determinant = g11 * g22 - g12 * g12;
781    let (r1, r2) = (along_first.dot(offset_from_origin), along_second.dot(offset_from_origin));
782    let s = (r1 * g22 - r2 * g12) / determinant;
783    let t = (r2 * g11 - r1 * g12) / determinant;
784    if origin
785        .add(along_first.scale(s))
786        .add(along_second.scale(t))
787        .sub(centre)
788        .length()
789        > band
790    {
791        return Ok(None);
792    }
793    // The move, read off the shared evaluator on the generatrix row. The
794    // negation is the fit's own, as in `sphere_offset_surface`.
795    let ([u0, _], [v0, v1]) = domains(source)?;
796    let Ok(sample) = OffsetEvaluator::new(
797        "offset_surface",
798        source,
799        OffsetNormal::FaceStable {
800            same_sense: face.same_sense,
801        },
802    )
803    .at(u0, (v0 + v1) / 2.0, -distance)
804    else {
805        return Ok(None);
806    };
807    let source_radial = sample.source.sub(centre);
808    let offset_radial = sample.point.sub(centre);
809    let offset_radius = offset_radial.length();
810    if (source_radial.length() - radius).abs() > band
811        || offset_radius <= band
812        || offset_radial.dot(source_radial) <= 0.0
813        || ((offset_radius - radius).abs() - distance.abs()).abs() > band
814    {
815        return Ok(None);
816    }
817    let factor = offset_radius / radius;
818    let Ok(offset_rows) = rows
819        .iter()
820        .map(|row| {
821            let points = row.iter().map(|control| control.point().or_refuse(KernelStage::Refine, "point")).collect::<Result<Vec<_>, KernelRefusal>>()?;
822            let row_origin = points[0];
823            let row_centre = row_origin
824                .add(points[first].sub(row_origin).scale(s))
825                .add(points[second].sub(row_origin).scale(t));
826            Ok(points
827                .iter()
828                .zip(row)
829                .map(|(point, control)| {
830                    Vec4::from_point(row_centre.add(point.sub(row_centre).scale(factor)), control.w)
831                })
832                .collect::<Vec<_>>())
833        })
834        .collect::<Result<Vec<Vec<_>>, KernelRefusal>>()
835    else {
836        return Ok(None);
837    };
838    let Ok(surface) = NurbsSurface::new(
839        source.degree_u,
840        source.degree_v,
841        source.knots_u.clone(),
842        source.knots_v.clone(),
843        offset_rows,
844    ) else {
845        return Ok(None);
846    };
847    match measure_surface_fit_against_pointwise_offset(
848        source,
849        face.same_sense,
850        &surface,
851        distance,
852        band,
853    ) {
854        Ok(measured) if measured.within_band() => Ok(Some(surface)),
855        _ => Ok(None),
856    }
857}
858
859/// Lane O row 35's switch, default on since 2026-11-02 (batch 19; `0`/`off`
860/// restores the fit): a circular cylinder's offset carrier is built exactly
861/// ([`cylinder_offset_surface`]). The carve's certificate of the same factor
862/// is row 35a's own switch (`carriers.rs`).
863pub fn exact_cylinder_offsets_on() -> bool {
864    switch!("BREP_OFFSET_EXACT_CYLINDER", true)
865}
866
867
868/// The axis, radius and offset scale factor of a recognized CIRCULAR CYLINDER
869/// offset by `distance` (`offset_surface`'s sign: positive opposite the face
870/// normal), or `None` for every other carrier and for an offset through the
871/// axis. The move is read off the shared [`OffsetEvaluator`] at the middle of
872/// the domain, as in [`sphere_offset_surface`]: it must be radial and exactly
873/// `|d|` long, so this cannot invent a sign convention.
874pub fn cylinder_offset_factor(
875    surface: &NurbsSurface,
876    same_sense: bool,
877    distance: f64,
878) -> Result<Option<(Vec3, Vec3, f64, f64)>, KernelRefusal> {
879    if std::env::var_os("BREP_NO_ANALYTIC_OFFSET").is_some() {
880        return Ok(None);
881    }
882    let Some(crate::AnalyticSurface::RuledRevolution { frame, rho0, rho1, height }) = surface.analytic() else {
883        return Ok(None);
884    };
885    let radius = 0.5 * (rho0 + rho1);
886    if !(radius > 0.0) || (rho0 - rho1).abs() > 1e-9 * radius.max(1.0) {
887        return Ok(None);
888    }
889    let Ok(axis) = frame.axis.normalized() else {
890        return Ok(None);
891    };
892    let origin = frame.origin;
893    let band = 1e-9 * (origin.length() + radius + height.abs()).max(1.0);
894    let perpendicular = |point: Vec3| {
895        let along = point.sub(origin);
896        along.sub(axis.scale(along.dot(axis)))
897    };
898    let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
899    let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
900    let Ok(sample) = OffsetEvaluator::new("offset_surface", surface, OffsetNormal::FaceStable { same_sense })
901        .at((u0 + u1) * 0.5, (v0 + v1) * 0.5, -distance)
902    else {
903        return Ok(None);
904    };
905    let (source_radial, offset_radial) = (perpendicular(sample.source), perpendicular(sample.point));
906    let offset_radius = offset_radial.length();
907    if (source_radial.length() - radius).abs() > band
908        || offset_radius <= band
909        || offset_radial.dot(source_radial) <= 0.0
910        || ((offset_radius - radius).abs() - distance.abs()).abs() > band
911        || sample.point.sub(sample.source).dot(axis).abs() > band
912    {
913        return Ok(None);
914    }
915    Ok(Some((origin, axis, radius, offset_radius / radius)))
916}
917
918/// Lane O row 35: the EXACT offset of a circular cylinder, or `None`.
919///
920/// A cylinder's normal is radial and constant along each ruling, so its
921/// pointwise offset is the coaxial cylinder of radius `R ± d`. Every column
922/// of the net (a rational circle) is an affine image of one polygon in a
923/// plane normal to the axis, and scaling about the axis by `(R ± d)/R` maps
924/// it to the same image of the offset circle; the rulings stay parallel to
925/// the axis. Knots, degrees and weights are untouched, so the same `(u, v)`
926/// names the corresponding point and cloned trims land where they did. The
927/// finished net must land on the pointwise offset of `reference` everywhere
928/// on the measurement grid, to `1e-9` of the model's scale; every decline
929/// falls through to the fit.
930fn cylinder_offset_surface(
931    reference: &NurbsSurface,
932    same_sense: bool,
933    distance: f64,
934) -> Result<Option<NurbsSurface>, KernelRefusal> {
935    let Some((origin, axis, radius, factor)) = cylinder_offset_factor(reference, same_sense, distance)? else {
936        return Ok(None);
937    };
938    if reference.control_points.iter().flatten().any(|control| !(control.w > 0.0)) {
939        return Ok(None);
940    }
941    let Ok(rows) = reference
942        .control_points
943        .iter()
944        .map(|row| {
945            row.iter()
946                .map(|control| {
947                    let point = control.point()?;
948                    let foot = origin.add(axis.scale(point.sub(origin).dot(axis)));
949                    Ok(Vec4::from_point(foot.add(point.sub(foot).scale(factor)), control.w))
950                })
951                .collect::<Result<Vec<_>, String>>()
952        })
953        .collect::<Result<Vec<Vec<_>>, String>>()
954    else {
955        return Ok(None);
956    };
957    let Ok(surface) = NurbsSurface::new(
958        reference.degree_u,
959        reference.degree_v,
960        reference.knots_u.clone(),
961        reference.knots_v.clone(),
962        rows,
963    ) else {
964        return Ok(None);
965    };
966    // The construction is exact once the recognizer has proved the cylinder
967    // and the evaluator has fixed the move, so this reads the finished net at
968    // 5 × 3 stations, both domain ends included, against the pointwise offset:
969    // a check of the build, not a measurement. `offset_surface_measured_*`
970    // still takes its full grid reading of this carrier, as of any fit.
971    let band = 1e-9 * (origin.length() + radius * factor.max(1.0)).max(1.0);
972    let evaluator = OffsetEvaluator::new("offset_surface", reference, OffsetNormal::FaceStable { same_sense });
973    let [u0, u1] = reference.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
974    let [v0, v1] = reference.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
975    for i in 0..=4 {
976        for j in 0..=2 {
977            let (u, v) = (u0 + (u1 - u0) * i as f64 / 4.0, v0 + (v1 - v0) * j as f64 / 2.0);
978            let (Ok(want), Ok(got)) = (evaluator.at(u, v, -distance), surface.evaluate(u, v)) else {
979                return Ok(None);
980            };
981            if !(want.point.sub(got).length() <= band) {
982                return Ok(None);
983            }
984        }
985    }
986    Ok(Some(surface))
987}
988
989pub fn offset_surface_with_lane(
990    face: &FaceRecord,
991    distance: f64,
992    extension: &CarrierExtension,
993) -> Result<(NurbsSurface, OffsetSurfaceLane), KernelRefusal> {
994    offset_surface_constructed(face, distance, extension, &mut None).map(|(surface, lane, _)| (surface, lane))
995}
996
997/// [`offset_surface_with_lane`], plus the surface the carrier is the pointwise
998/// offset OF when that is not the face's own: the source extended along its
999/// rulings, for a ruled extension (see the RULED EXTENSION block).
1000pub fn transpose_offset_surface(surface: &NurbsSurface) -> Result<NurbsSurface, KernelRefusal> {
1001    let controls = (0..surface.control_points[0].len())
1002        .map(|column| surface.control_points.iter().map(|row| row[column]).collect())
1003        .collect();
1004    NurbsSurface::new(surface.degree_v, surface.degree_u, surface.knots_v.clone(),
1005        surface.knots_u.clone(), controls).or_refuse(KernelStage::Refine, "offset_transpose")
1006}
1007
1008/// `BREP_OFFSET_APEX_END_REACH` (default on; `=0` restores): see the RULED EXTENSION
1009/// block of `offset_surface_constructed`.
1010pub fn apex_end_reach_enabled() -> bool {
1011    switch!("BREP_OFFSET_APEX_END_REACH", true)
1012}
1013
1014
1015/// `BREP_OFFSET_POLE_COLLAPSE` (default on; =0 restores the fit as it was): a
1016/// fitted offset carrier closes on a point wherever its source does. A source
1017/// boundary row that is one point (a pole: a revolved meridian meeting its
1018/// axis) has a pointwise offset that is one point too (the pole moved along
1019/// the axis), but the fit leaves that row a small ring (a spheroid's inner
1020/// parallel surface: 3.2e-5 across at distance 1). The face's loop, a seam
1021/// alone, then bounds nothing on the carrier: the kernel's own integrals do
1022/// not notice, a STEP reader integrates the face to nothing. With the switch,
1023/// such a row (one within the bar under which an image collapses) whose source
1024/// row is one point to rounding AND whose exact offset image is one point to
1025/// rounding (one tangent plane; a cone's apex has a cone of directions, and
1026/// its image ring stays however small) closes on that exact image, weights
1027/// kept.
1028pub fn pole_collapse_enabled() -> bool {
1029    switch!("BREP_OFFSET_POLE_COLLAPSE", true)
1030}
1031
1032/// The fitted carrier with each boundary row the source closes on a point
1033/// closed on one point too (see [`pole_collapse_enabled`]); unchanged where
1034/// the domains differ (an extended carrier's rows are not the source's).
1035pub fn collapse_source_poles(face: &FaceRecord, fitted: NurbsSurface, distance: f64) -> NurbsSurface {
1036    let source = &face.surface;
1037    let same = |a: Result<[f64; 2], _>, b: Result<[f64; 2], _>| matches!((a, b), (Ok(a), Ok(b)) if (a[0] - b[0]).abs() <= 1e-12 && (a[1] - b[1]).abs() <= 1e-12);
1038    if !same(source.domain_u(), fitted.domain_u()) || !same(source.domain_v(), fitted.domain_v()) {
1039        return fitted;
1040    }
1041    let point = |w: &Vec4| Vec3::new(w.x / w.w, w.y / w.w, w.z / w.w);
1042    let spread = |points: &[Vec3]| points.iter().map(|q| q.sub(points[0]).length()).fold(0.0f64, f64::max);
1043    let ([u0, u1], [v0, v1]) = match (source.domain_u(), source.domain_v()) {
1044        (Ok(u), Ok(v)) => (u, v),
1045        _ => return fitted,
1046    };
1047    // A source pole is ONE point to rounding, not a short edge: within a few
1048    // ulps of its own coordinates (so a short edge on a long face is not
1049    // one) AND within 1e-9 of the surface's own size (so neither is a short
1050    // edge far from the origin, where an ulp is long). A true pole's copies of
1051    // one axis point pass both; one too far out to pass is left as fitted.
1052    let (mut low, mut high) = (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY));
1053    for q in source.control_points.iter().flatten().map(point) {
1054        low = Vec3::new(low.x.min(q.x), low.y.min(q.y), low.z.min(q.z));
1055        high = Vec3::new(high.x.max(q.x), high.y.max(q.y), high.z.max(q.z));
1056    }
1057    let extent = high.sub(low).length();
1058    let one_point = |points: &[Vec3]| {
1059        let magnitude = points.iter().map(|q| q.x.abs().max(q.y.abs()).max(q.z.abs())).fold(0.0f64, f64::max);
1060        let gap = spread(points);
1061        gap <= 64.0 * f64::EPSILON * (1.0 + magnitude) && gap <= 1e-9 * extent
1062    };
1063    // And the pole has ONE tangent plane, so its exact offset image (the pole
1064    // moved d along that plane's normal) is one point too. Read on the
1065    // source's own net, which is exact: the tangent directions at the pole are
1066    // the directions from it to the next row's control points (a rational
1067    // end's derivative points along them), and one tangent plane means they
1068    // are coplanar. A revolved meridian meeting its axis square has them all
1069    // in one plane, to rounding; a cone's apex has them on a cone, out of any
1070    // plane by the sine of its tilt (1.7e-5 for a cone of height tan(0.001
1071    // deg)), and its image is a ring however small, which stays.
1072    let one_tangent_plane = |pole: Vec3, next: &[Vec3]| -> Option<Vec3> {
1073        let directions: Vec<Vec3> = next.iter().filter_map(|q| q.sub(pole).normalized().ok()).collect();
1074        if directions.len() < 3 {
1075            return None;
1076        }
1077        let mut normal: Option<Vec3> = None;
1078        let mut widest = 0.0f64;
1079        for a in &directions {
1080            for b in &directions {
1081                let c = a.cross(*b);
1082                if c.length() > widest {
1083                    widest = c.length();
1084                    normal = c.normalized().ok();
1085                }
1086            }
1087        }
1088        // Directions too near parallel to read a plane from (a patch a
1089        // fraction of a degree wide) decline: the fit is left as it is.
1090        // The image of a cone's apex is a ring of radius |d| times its
1091        // directions' tilt out of the plane: the plane is the pole's own only
1092        // when that ring is below rounding of the offset itself, whatever the
1093        // surface's size (a cone 1e9 across and 0.1 high, offset 1e6, tilts
1094        // 2e-10 and its ring is 1e-4; a true pole tilts by rounding alone).
1095        let normal = normal.filter(|_| widest > 1e-3)?;
1096        let tilt = directions.iter().map(|d| d.dot(normal).abs()).fold(0.0f64, f64::max);
1097        (tilt <= 1e-9 && distance.abs() * tilt <= 1e-12 * (1.0 + distance.abs())).then_some(normal)
1098    };
1099    let collapse_bar = 1e-6f64.max(distance.abs() * 1e-2);
1100    let mut net = fitted.control_points.clone();
1101    let (rows, columns) = (net.len(), net.first().map_or(0, |row| row.len()));
1102    if rows < 2 || columns < 2 {
1103        return fitted;
1104    }
1105    // (source boundary, fitted boundary's cells) for the four boundaries.
1106    let row_of = |grid: &Vec<Vec<Vec4>>, r: usize| -> Vec<Vec4> { grid[r].clone() };
1107    let column_of = |grid: &Vec<Vec<Vec4>>, c: usize| -> Vec<Vec4> { grid.iter().map(|row| row[c]).collect() };
1108    let (source_rows, source_columns) = (source.control_points.len(), source.control_points[0].len());
1109    let boundaries: [(Vec<Vec4>, bool, usize, f64); 4] = [
1110        (row_of(&source.control_points, 0), true, 0, u0),
1111        (row_of(&source.control_points, source_rows - 1), true, rows - 1, u1),
1112        (column_of(&source.control_points, 0), false, 0, v0),
1113        (column_of(&source.control_points, source_columns - 1), false, columns - 1, v1),
1114    ];
1115    let mut collapsed = false;
1116    for (source_cells, is_row, index, _) in boundaries {
1117        let source_points: Vec<Vec3> = source_cells.iter().map(point).collect();
1118        let next: Vec<Vec3> = if is_row {
1119            let r = if index == 0 { 1 } else { source_rows - 2 };
1120            source.control_points[r].iter().map(point).collect()
1121        } else {
1122            let c = if index == 0 { 1 } else { source_columns - 2 };
1123            source.control_points.iter().map(|row| point(&row[c])).collect()
1124        };
1125        let Some(normal) = (if one_point(&source_points) { one_tangent_plane(source_points[0], &next) } else { None }) else {
1126            continue;
1127        };
1128        let cells = if is_row { row_of(&net, index) } else { column_of(&net, index) };
1129        let points: Vec<Vec3> = cells.iter().map(point).collect();
1130        let ring = spread(&points);
1131        if ring == 0.0 || !(ring <= collapse_bar) {
1132            continue;
1133        }
1134        // The row closes on the pole's exact image, the pole moved |d| along
1135        // its tangent plane's normal, on the side the fit offset to (the
1136        // image nearer the fitted ring's weighted centre); not on that centre,
1137        // which depends on how the ring's net is laid out (a duplicated seam
1138        // control pulls it off the axis).
1139        let total: f64 = cells.iter().map(|w| w.w).sum();
1140        let fitted_centre = cells.iter().fold(Vec3::new(0.0, 0.0, 0.0), |sum, w| sum.add(Vec3::new(w.x, w.y, w.z))).scale(1.0 / total);
1141        let pole = source_points[0];
1142        let images = [pole.add(normal.scale(distance.abs())), pole.sub(normal.scale(distance.abs()))];
1143        let centre = if images[0].sub(fitted_centre).length() <= images[1].sub(fitted_centre).length() { images[0] } else { images[1] };
1144        if !(centre.sub(fitted_centre).length() <= collapse_bar) {
1145            continue;
1146        }
1147        for k in 0..cells.len() {
1148            let w = cells[k].w;
1149            let cell = Vec4 { x: centre.x * w, y: centre.y * w, z: centre.z * w, w };
1150            if is_row { net[index][k] = cell; } else { net[k][index] = cell; }
1151        }
1152        collapsed = true;
1153    }
1154    if !collapsed {
1155        return fitted;
1156    }
1157    match NurbsSurface::new(fitted.degree_u, fitted.degree_v, fitted.knots_u.clone(), fitted.knots_v.clone(), net) {
1158        Ok(surface) => surface,
1159        Err(_) => fitted,
1160    }
1161}
1162
1163fn offset_surface_constructed(
1164    face: &FaceRecord,
1165    distance: f64,
1166    extension: &CarrierExtension,
1167    sphere_reading: &mut Option<f64>,
1168) -> Result<(NurbsSurface, OffsetSurfaceLane, Option<NurbsSurface>), KernelRefusal> {
1169    let (surface, lane, extended) = offset_surface_constructed_fitted(face, distance, extension, sphere_reading)?;
1170    if !pole_collapse_enabled() {
1171        return Ok((surface, lane, extended));
1172    }
1173    Ok((collapse_source_poles(face, surface, distance), lane, extended))
1174}
1175
1176fn offset_surface_constructed_fitted(
1177    face: &FaceRecord,
1178    distance: f64,
1179    extension: &CarrierExtension,
1180    sphere_reading: &mut Option<f64>,
1181) -> Result<(NurbsSurface, OffsetSurfaceLane, Option<NurbsSurface>), KernelRefusal> {
1182    let source = &face.surface;
1183    let extension_active = extension.is_active();
1184    // Imported cones can put the ruling in u. Normalize that chart for the
1185    // existing exact ruling/pinch construction, then restore the caller's UV.
1186    // Transposition reverses Su x Sv, so the face sense reverses with it.
1187    // The recognizer must prove a ruled revolution; arbitrary lofts keep
1188    // their existing evaluator and fit semantics.
1189    let normalize_ruling = std::env::var("BREP_OFFSET_FIT_RESIDUAL").as_deref() != Ok("0")
1190        && source.degree_u == 1 && source.control_points.len() == 2;
1191    let normalize_sphere = std::env::var("BREP_OFFSET_FOLD_CHART").as_deref() != Ok("0")
1192        && source.degree_u == 2 && source.degree_v == 2 && source.analytic().is_none();
1193    if normalize_ruling || normalize_sphere {
1194        let transposed = transpose_offset_surface(source)?;
1195        let ruled = normalize_ruling && matches!(transposed.analytic(), Some(crate::AnalyticSurface::RuledRevolution { .. }));
1196        let spherical = normalize_sphere && transposed.analytic().and_then(|shape| shape.sphere_geometry()).is_some();
1197        if ruled || spherical {
1198            let mut turned = face.clone();
1199            turned.surface = transposed;
1200            turned.same_sense = !turned.same_sense;
1201            for coedge in turned.loops.iter_mut().flat_map(|lp| &mut lp.coedges) {
1202                let controls = coedge.pcurve.control_points.iter().map(|point| {
1203                    let mut swapped = *point;
1204                    std::mem::swap(&mut swapped.x, &mut swapped.y);
1205                    swapped
1206                }).collect();
1207                coedge.pcurve = NurbsCurve::new(coedge.pcurve.degree,
1208                    coedge.pcurve.knots.clone(), controls).or_refuse(KernelStage::Refine, "offset_transpose_pcurve")?;
1209            }
1210            let turned_extension = CarrierExtension {
1211                u_min: extension.v_min, u_max: extension.v_max,
1212                v_min: extension.u_min, v_max: extension.u_max,
1213            };
1214            let (surface, lane, extended) = offset_surface_constructed(&turned, distance, &turned_extension, &mut None)?;
1215            return Ok((transpose_offset_surface(&surface)?, lane,
1216                extended.as_ref().map(transpose_offset_surface).transpose()?));
1217        }
1218    }
1219    if source.is_affine().or_refuse(KernelStage::Refine, "is_affine")? {
1220        let ([u0, u1], [v0, v1]) = domains(source)?;
1221        let normal = stable_face_normal(face, (u0 + u1) / 2.0, (v0 + v1) / 2.0)?;
1222        let shift = normal.scale(-distance);
1223        let mut points = source
1224            .control_points
1225            .iter()
1226            .map(|row| {
1227                row.iter()
1228                    .map(|control| Ok(control.point().or_refuse(KernelStage::Refine, "point")?.add(shift)))
1229                    .collect::<Result<Vec<_>, KernelRefusal>>()
1230            })
1231            .collect::<Result<Vec<_>, KernelRefusal>>()?;
1232        if extension_active {
1233            let p00 = points[0][0];
1234            let p01 = points[0][1];
1235            let p10 = points[1][0];
1236            let direction_u = p10.sub(p00).normalized().or_refuse(KernelStage::Refine, "normalized")?;
1237            let direction_v = p01.sub(p00).normalized().or_refuse(KernelStage::Refine, "normalized")?;
1238            // The net slides while the cloned pcurves stay put, so a trim
1239            // that spans only part of the domain would grow by less than
1240            // asked (a 20-wide face trimmed to [0,16] by a blend moved its
1241            // x=16 edge 0.6 for a 1.0 pad). Solve the slide for the TRIM's
1242            // own bounding box instead.
1243            let (trim_u, trim_v) = trim_domain_fractions(face, [u0, u1], [v0, v1])?;
1244            let (back_u, forward_u) = domain_end_moves(extension.u_min, extension.u_max, trim_u);
1245            let (back_v, forward_v) = domain_end_moves(extension.v_min, extension.v_max, trim_v);
1246            points[0][0] = p00
1247                .sub(direction_u.scale(back_u))
1248                .sub(direction_v.scale(back_v));
1249            points[0][1] = p01
1250                .sub(direction_u.scale(back_u))
1251                .add(direction_v.scale(forward_v));
1252            points[1][0] = p10
1253                .add(direction_u.scale(forward_u))
1254                .sub(direction_v.scale(back_v));
1255            points[1][1] = points[1][1]
1256                .add(direction_u.scale(forward_u))
1257                .add(direction_v.scale(forward_v));
1258        }
1259        let controls = points
1260            .into_iter()
1261            .enumerate()
1262            .map(|(row, points)| {
1263                points
1264                    .into_iter()
1265                    .enumerate()
1266                    .map(|(column, point)| {
1267                        Vec4::from_point(point, source.control_points[row][column].w)
1268                    })
1269                    .collect()
1270            })
1271            .collect();
1272        // The extension slides the control net along the plane, so the same
1273        // `(u, v)` no longer names the pointwise offset of the same source
1274        // point; without it the shift is rigid and exact.
1275        let lane = if extension_active {
1276            OffsetSurfaceLane::Reparameterised
1277        } else {
1278            OffsetSurfaceLane::Affine
1279        };
1280        return Ok((
1281            NurbsSurface::new(
1282                source.degree_u,
1283                source.degree_v,
1284                source.knots_u.clone(),
1285                source.knots_v.clone(),
1286                controls,
1287            ).or_refuse(KernelStage::Refine, "new")?,
1288            lane,
1289            None,
1290        ));
1291    }
1292
1293    // A recognized SPHERE has a closed-form concentric offset that needs no
1294    // collocation at all. Taken before the fit so the exact answer wins
1295    // wherever it exists; `sphere_offset_surface` declines on everything else,
1296    // and on a sphere whose construction it cannot verify.
1297    //
1298    // The extension cannot reach a sphere either way: both blocks below sit
1299    // under `parameters_v.len() == 2`, and a sphere's meridian is a degree-2
1300    // net of five controls. Taking this lane under an active extension keeps
1301    // exactly the behaviour the fit had — no growth — and only sharpens it.
1302    if let Some(surface) = sphere_offset_surface(face, distance, sphere_reading)? {
1303        return Ok((surface, OffsetSurfaceLane::Analytic, None));
1304    }
1305    // The same holds for a revolved ARC: its generatrix has three or more
1306    // controls, so no extension below could reach it.
1307    if let Some(surface) = revolved_arc_offset_surface(face, distance)? {
1308        return Ok((surface, OffsetSurfaceLane::Analytic, None));
1309    }
1310
1311    let knot_u = KnotVector::new(source.knots_u.clone(), source.degree_u).or_refuse(KernelStage::Refine, "new")?;
1312    let knot_v = KnotVector::new(source.knots_v.clone(), source.degree_v).or_refuse(KernelStage::Refine, "new")?;
1313    let parameters_u = greville_parameters(&knot_u);
1314    let parameters_v = greville_parameters(&knot_v);
1315    // The Greville sample grid IS a pointwise offset evaluation — this fit is
1316    // the shared evaluator's consumer, not its peer. `offset_surface`'s
1317    // positive distance moves OPPOSITE the face normal while the evaluator's
1318    // moves ALONG it, so the negation happens once, here, with a name on it
1319    // (audit §4.1's four hand negations get no fifth).
1320    let evaluator = OffsetEvaluator::new(
1321        "offset_surface",
1322        source,
1323        OffsetNormal::FaceStable {
1324            same_sense: face.same_sense,
1325        },
1326    );
1327    let mut samples = Vec::new();
1328    for &u in &parameters_u {
1329        let mut row = Vec::new();
1330        for &v in &parameters_v {
1331            row.push(evaluator.at(u, v, -distance).or_refuse(KernelStage::Refine, "at")?.point);
1332        }
1333        samples.push(row);
1334    }
1335    // APEX-CONE PINCH RETRIM: offsetting an apex cone INWARD moves each
1336    // ruling past the axis — the sampled far row becomes a ring on the far
1337    // side (radius d·cos half-angle, mirrored through the axis) and the
1338    // offset surface self-pinches inside the v-domain. The genuine cavity
1339    // ends AT the pinch (the offset cone's own apex). For a linear-v net
1340    // (two sample rows — every made/booleaned cone) the pinch lies on each
1341    // ruling at the fraction where the radial vector vanishes: detect the
1342    // inversion (far-row radials anti-parallel to near-row radials about the
1343    // row centroids) and pull the far row back to the pinch point, so the
1344    // fitted surface ends in a proper degenerate apex row instead of a
1345    // parasitic inverted tip ending in an unweldable ring.
1346    // Both blocks below move the sample grid OFF the pointwise offset on
1347    // purpose. Recording that is what lets `offset_surface_measured` decline to
1348    // report a designed divergence as a fit error.
1349    let mut reparameterised = false;
1350    let mut extended_source: Option<NurbsSurface> = None;
1351    // Two u samples are enough for both: a 2 × 2 bilinear net (a planar
1352    // trapezoid wall of a lofted square frustum, which the affine test above
1353    // rejects on its parallelogram defect) has straight rulings like any
1354    // other linear-v net, and without the extension its inward carrier
1355    // stopped 0.059 short of the opening the reach lane had measured
1356    // (2026-09-26, the SHARP rim corner fixture).
1357    if parameters_v.len() == 2 && parameters_u.len() >= 2 {
1358        let centroid = |column: usize| {
1359            let mut sum = Vec3::default();
1360            for row in &samples {
1361                sum = sum.add(row[column]);
1362            }
1363            sum.scale(1.0 / samples.len() as f64)
1364        };
1365        let near_centroid = centroid(0);
1366        let far_centroid = centroid(1);
1367        let mut inverted = true;
1368        let mut pinch_fraction = 0.0f64;
1369        let mut near_mean = 0.0f64;
1370        let mut far_mean = 0.0f64;
1371        for row in &samples {
1372            let near_radial = row[0].sub(near_centroid);
1373            let far_radial = row[1].sub(far_centroid);
1374            let near_len = near_radial.length();
1375            let far_len = far_radial.length();
1376            if near_len <= 1e-9 || far_len <= 1e-9 {
1377                inverted = false;
1378                break;
1379            }
1380            if near_radial.dot(far_radial) >= 0.0 {
1381                inverted = false;
1382                break;
1383            }
1384            pinch_fraction += near_len / (near_len + far_len) / samples.len() as f64;
1385            near_mean += near_len / samples.len() as f64;
1386            far_mean += far_len / samples.len() as f64;
1387        }
1388        if inverted {
1389            let retrim_far = match pinch_side_by_source(source, &parameters_u, &parameters_v, &samples, near_centroid, far_centroid)? {
1390                Some(far) => far,
1391                None => far_mean <= near_mean,
1392            };
1393            // WHOSE fold is it?  The retrim exists so a cavity that ends at the
1394            // offset cone's own apex ends there in the TOPOLOGY too, instead of
1395            // running past the pinch into a mirrored ring no weld can use.  It
1396            // pays for that by moving the sample grid off the pointwise offset,
1397            // and the price is the shared-basis identity every consumer rests
1398            // on: after it, the SAME `(u, v)` no longer names the offset of the
1399            // same source point.
1400            //
1401            // That price is only worth paying when the face's TRIM actually
1402            // reaches past the pinch.  A trim on a cone's wide half offsets
1403            // perfectly well; its carrier folds somewhere the face never goes,
1404            // and shearing its parameterization to tidy that away sheared the
1405            // trim's own pcurves with it — a 45° cone sheet trimmed to its wide
1406            // half shipped a slab 0.86 % off its Pappus volume, validating and
1407            // wrong (`thicken.rs`,
1408            // `a_re_parameterized_offset_carrier_keeps_the_pointwise_offset`).
1409            //
1410            // So read the trim, the way the extension below already does.  With
1411            // a linear v basis the pinch sits at the v FRACTION
1412            // `pinch_fraction`, and the folded side is whichever end the retrim
1413            // would have pulled.  A face with no loops still reports the whole
1414            // domain, which keeps every full-domain carrier on its exact
1415            // previous path.
1416            let (_, trim_v) = trim_domain_fractions(face, knot_u.domain(), knot_v.domain())?;
1417            let trim_reaches_the_pinch = if retrim_far {
1418                trim_v[1] > pinch_fraction + 1e-9
1419            } else {
1420                trim_v[0] < pinch_fraction - 1e-9
1421            };
1422            if trim_reaches_the_pinch {
1423                // Pull the crossed (smaller-ring, past-the-pinch) end back to
1424                // the pinch point on each ruling.
1425                reparameterised = true;
1426                for row in &mut samples {
1427                    let near = row[0];
1428                    let far = row[1];
1429                    let pinch = near.add(far.sub(near).scale(pinch_fraction));
1430                    if retrim_far {
1431                        row[1] = pinch;
1432                    } else {
1433                        row[0] = pinch;
1434                    }
1435                }
1436            }
1437        }
1438        // RULED EXTENSION: `planar_extension` is a no-op for curved carriers
1439        // above, but a cone/cylinder lateral joined at a reflex edge needs
1440        // its offset skin to GROW past the source rim exactly like a plane
1441        // (a cylinder piercing a cone: the two offsets only meet past both
1442        // cloned rims). The carrier's parameterization stays (knots/pcurves
1443        // untouched) while its world image — and with it the cloned trim's
1444        // image — inflates: the carrier is the pointwise offset of the SOURCE
1445        // EXTENDED ALONG ITS RULINGS, which a linear-v net does exactly.
1446        //
1447        // Stretching the sampled OFFSET rulings instead reaches the same
1448        // surface only where the source is DEVELOPABLE — its normal constant
1449        // along each ruling, as on a cylinder, a cone or an extruded wall —
1450        // because only there is the offset ruled too. A twisted loft is ruled
1451        // and not developable: its stretched offset rulings left the offset,
1452        // and an outward shell of one validated 0.235 short (1.0 %). So the
1453        // stretch is MEASURED against the extended source's pointwise offset,
1454        // at both ends and the middle of every sampled ruling, and kept only
1455        // within the fit contract; otherwise the extended source is sampled
1456        // pointwise, and either way the refinement reads the carrier against it.
1457        if extension.extends_v() && !inverted {
1458            // `BREP_OFFSET_APEX_END_REACH` (default on; `=0` restores): a sheaf whose apex
1459            // lies exactly ON an end row (a cone made to its point: the source
1460            // rows read apex_at = 1) is not a sheet folded inside its span; it
1461            // is grown away from the apex and not toward it. Without it the
1462            // whole sheet read unextendable, so a cone grown by 1 kept its
1463            // base ring at z = 0.6 above the grown base plane z = -1, the pair
1464            // was skipped on bounds and the ring stayed one-use
1465            // (brep-bench offset/cone-grown, non-integral genus).
1466            let apex_end_reach = apex_end_reach_enabled();
1467            let mut min_ruling = f64::MAX;
1468            let mut back_allowance = f64::MAX;
1469            let mut forward_allowance = f64::MAX;
1470            let mut extendable = true;
1471            for row in &samples {
1472                let ruling = row[1].sub(row[0]);
1473                let length = ruling.length();
1474                min_ruling = min_ruling.min(length);
1475                // Radii about the row centroids expose a converging (conic)
1476                // ruling sheaf; the extension must stop short of its apex or
1477                // the sheet folds through it.
1478                let near_radial = row[0].sub(near_centroid).length();
1479                let far_radial = row[1].sub(far_centroid).length();
1480                if (far_radial - near_radial).abs() > 1e-9 {
1481                    let apex_at = near_radial / (near_radial - far_radial);
1482                    if apex_end_reach && apex_at.abs() <= 1e-9 {
1483                        back_allowance = 0.0;
1484                        continue;
1485                    }
1486                    if apex_end_reach && (apex_at - 1.0).abs() <= 1e-9 {
1487                        forward_allowance = 0.0;
1488                        continue;
1489                    }
1490                    if (-1e-9..=1.0 + 1e-9).contains(&apex_at) {
1491                        // Apex inside the span: degenerate sheet, do not touch.
1492                        extendable = false;
1493                        break;
1494                    }
1495                    if apex_at < 0.0 {
1496                        back_allowance = back_allowance.min(0.9 * -apex_at);
1497                    } else {
1498                        forward_allowance = forward_allowance.min(0.9 * (apex_at - 1.0));
1499                    }
1500                }
1501            }
1502            // The allowances above are read off the OFFSET rows. The source's
1503            // own ruling sheaf converges at a different rate — an outward
1504            // offset moves a cone's apex FARTHER along the ruling — so a
1505            // growth the offset rows allow can still carry the EXTENDED SOURCE
1506            // through its own apex, and its pointwise offset would then be
1507            // taken on a surface folded back on itself. Read the same radial
1508            // ratio on the source rows and clamp by the tighter of the two.
1509            let mut source_back = f64::MAX;
1510            let mut source_forward = f64::MAX;
1511            if extendable {
1512                let source_centroid = |column: usize| {
1513                    let mut sum = Vec3::default();
1514                    for row in &source.control_points {
1515                        if let Ok(point) = row[column].point() {
1516                            sum = sum.add(point);
1517                        }
1518                    }
1519                    sum.scale(1.0 / source.control_points.len() as f64)
1520                };
1521                let (near_source, far_source) = (source_centroid(0), source_centroid(1));
1522                for row in &source.control_points {
1523                    let (near, far) = (row[0].point().or_refuse(KernelStage::Refine, "point")?, row[1].point().or_refuse(KernelStage::Refine, "point")?);
1524                    let near_radial = near.sub(near_source).length();
1525                    let far_radial = far.sub(far_source).length();
1526                    if (far_radial - near_radial).abs() > 1e-9 {
1527                        let apex_at = near_radial / (near_radial - far_radial);
1528                        if apex_end_reach && apex_at.abs() <= 1e-9 {
1529                            source_back = 0.0;
1530                            continue;
1531                        }
1532                        if apex_end_reach && (apex_at - 1.0).abs() <= 1e-9 {
1533                            source_forward = 0.0;
1534                            continue;
1535                        }
1536                        if (-1e-9..=1.0 + 1e-9).contains(&apex_at) {
1537                            extendable = false;
1538                            break;
1539                        }
1540                        if apex_at < 0.0 {
1541                            source_back = source_back.min(0.9 * -apex_at);
1542                        } else {
1543                            source_forward = source_forward.min(0.9 * (apex_at - 1.0));
1544                        }
1545                    }
1546                }
1547            }
1548            let (back_allowance, forward_allowance) =
1549                (back_allowance.min(source_back), forward_allowance.min(source_forward));
1550            if extendable && min_ruling > 1e-9 {
1551                // Solved for the TRIM's v-extent, not the domain's: a bore
1552                // face keeps its drill's full-height surface and is trimmed
1553                // to the part it pierces, so moving the surface's own ends
1554                // by |d| moved the trim's rims by only a fraction of that
1555                // (a 30-long ruling trimmed to 20 gave 0.667 for 1.0) — and
1556                // an outward shell's bore never reached the grown planes.
1557                let (_, trim_v) = trim_domain_fractions(face, knot_u.domain(), knot_v.domain())?;
1558                let (back_world, forward_world) =
1559                    domain_end_moves(extension.v_min, extension.v_max, trim_v);
1560                let (requested_back, requested_forward) = (back_world / min_ruling, forward_world / min_ruling);
1561                // APEX END: the 0.9 above keeps a growth from folding through an
1562                // apex it might not have located exactly. When the source is an
1563                // analytic cone the offset apex IS located exactly, and a reach
1564                // that would pass it ends AT it: the far row becomes the pole the
1565                // cavity really ends in. Stopping at 0.9 left a ring there (radius
1566                // 2.99e-3 on the d = 1 inward cone) that the carrier's rim
1567                // collapse then named a point, so the shipped edge was a point on
1568                // a trim that is a ring, and the shell was open over its disk —
1569                // 2.69e-5 of volume, all of it. Only while the SOURCE's own apex
1570                // lies beyond (its clamped allowance covers the reach), so the
1571                // extended source never folds; otherwise the clamp above stands.
1572                let apex_end = analytic_offset_apex(source, &samples, offset_fit_contract(source)).and_then(
1573                    |(at, apex)| {
1574                        if at > 1.0 && at - 1.0 <= requested_forward && at - 1.0 <= source_forward {
1575                            Some((false, at - 1.0, apex))
1576                        } else if at < 0.0 && -at <= requested_back && -at <= source_back {
1577                            Some((true, -at, apex))
1578                        } else {
1579                            None
1580                        }
1581                    },
1582                );
1583                let back = match apex_end {
1584                    Some((true, reach, _)) => reach,
1585                    _ => requested_back.min(back_allowance),
1586                };
1587                let forward = match apex_end {
1588                    Some((false, reach, _)) => reach,
1589                    _ => requested_forward.min(forward_allowance),
1590                };
1591                let stretched = samples
1592                    .iter()
1593                    .map(|row| {
1594                        let ruling = row[1].sub(row[0]);
1595                        let (near, far) = (row[0].sub(ruling.scale(back)), row[1].add(ruling.scale(forward)));
1596                        match apex_end {
1597                            Some((true, _, apex)) => vec![apex, far],
1598                            Some((false, _, apex)) => vec![near, apex],
1599                            None => vec![near, far],
1600                        }
1601                    })
1602                    .collect::<Vec<_>>();
1603                let extended = extend_along_rulings(source, back, forward)?;
1604                let extended_offsets = OffsetEvaluator::new(
1605                    "offset_surface",
1606                    &extended,
1607                    OffsetNormal::FaceStable {
1608                        same_sense: face.same_sense,
1609                    },
1610                );
1611                let [v0, v1] = knot_v.domain();
1612                let mut developability = 0.0f64;
1613                for (row, &u) in stretched.iter().zip(&parameters_u) {
1614                    for fraction in [0.0, 0.5, 1.0] {
1615                        let exact = extended_offsets.at(u, v0 + (v1 - v0) * fraction, -distance).or_refuse(KernelStage::Refine, "at")?.point;
1616                        let along = row[0].add(row[1].sub(row[0]).scale(fraction));
1617                        developability = developability.max(exact.sub(along).length());
1618                    }
1619                }
1620                let contract = offset_fit_contract(source);
1621                let stretch_kept = developability <= contract;
1622                samples = if stretch_kept {
1623                    stretched
1624                } else {
1625                    parameters_u
1626                        .iter()
1627                        .map(|&u| {
1628                            parameters_v
1629                                .iter()
1630                                .map(|&v| Ok(extended_offsets.at(u, v, -distance).or_refuse(KernelStage::Refine, "at")?.point))
1631                                .collect::<Result<Vec<_>, KernelRefusal>>()
1632                        })
1633                        .collect::<Result<Vec<_>, KernelRefusal>>()?
1634                };
1635                if let Ok(path) = std::env::var("BREP_OFFSET_FIT_TRACE") {
1636                    use std::io::Write;
1637                    let line = format!(
1638                        "extension deg=({},{}) net=({},{}) d={distance:.6} back={back:.6} forward={forward:.6} \
1639                         developability={developability:.3e} contract={contract:.3e} lane={} thread={} args={}\n",
1640                        source.degree_u,
1641                        source.degree_v,
1642                        source.control_points.len(),
1643                        source.control_points[0].len(),
1644                        if stretch_kept { "stretch" } else { "pointwise" },
1645                        std::thread::current().name().unwrap_or("-"),
1646                        std::env::args().skip(1).collect::<Vec<_>>().join(" "),
1647                    );
1648                    if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
1649                        let _ = file.write_all(line.as_bytes());
1650                    }
1651                }
1652                extended_source = Some(extended);
1653            }
1654        }
1655    }
1656    let reference = extended_source.as_ref().unwrap_or(source);
1657    // Lane O row 35 (`BREP_OFFSET_EXACT_CYLINDER`, default on): a CIRCULAR
1658    // CYLINDER's offset is the coaxial cylinder, built exactly from the
1659    // reference the extension above settled on (so every growth decision is
1660    // the fit's own) and measured before it is kept; any decline falls through
1661    // to the fit below, unchanged.
1662    if !reparameterised && exact_cylinder_offsets_on() {
1663        if let Some(surface) = cylinder_offset_surface(reference, face.same_sense, distance)? {
1664            return Ok((surface, OffsetSurfaceLane::Analytic, extended_source));
1665        }
1666    }
1667    let weights = reference
1668        .control_points
1669        .iter()
1670        .map(|row| row.iter().map(|point| point.w).collect::<Vec<_>>())
1671        .collect::<Vec<_>>();
1672    let fitted = NurbsSurface::new(
1673        source.degree_u,
1674        source.degree_v,
1675        source.knots_u.clone(),
1676        source.knots_v.clone(),
1677        interpolate_tensor(
1678            &knot_u,
1679            &knot_v,
1680            &parameters_u,
1681            &parameters_v,
1682            &samples,
1683            &weights,
1684        )?,
1685    ).or_refuse(KernelStage::Refine, "new")?;
1686    if reparameterised {
1687        return Ok((fitted, OffsetSurfaceLane::Reparameterised, None));
1688    }
1689    let reference_offsets = OffsetEvaluator::new(
1690        "offset_surface",
1691        reference,
1692        OffsetNormal::FaceStable {
1693            same_sense: face.same_sense,
1694        },
1695    );
1696    let refined = refine_offset_fit(reference, &reference_offsets, distance, fitted)?;
1697    if extended_source.is_none() && fit_over_trim_on() {
1698        // The cropped support is returned as the surface the carrier is the
1699        // offset of, so a measurement reads it over the crop, not past it.
1700        if let Some((cropped, support)) = offset_fit_over_trim(face, distance, &refined, &reference_offsets, sphere_reading)? {
1701            return Ok((cropped, OffsetSurfaceLane::Fit, Some(support)));
1702        }
1703    }
1704    Ok((refined, OffsetSurfaceLane::Fit, extended_source))
1705}
1706
1707/// `BREP_OFFSET_FIT_OVER_TRIM` (default on since the 2026-11-18 promotion;
1708/// `=0` keeps the whole-support fit): a free-form
1709/// carrier whose refined fit still misses the fit contract is fitted again
1710/// over the face's trim (with a margin), where that reads at least four times
1711/// closer ([`offset_fit_over_trim`]).
1712///
1713/// [`refine_offset_fit`] reads its deviation over the whole support, and one
1714/// spot it cannot improve ends its rounds for the whole surface ("stopped
1715/// improving"). A support can run far past its face: a fillet's rim strip
1716/// round a boss whose cylinder the boolean rejoined across its seam spans u in
1717/// [0, 1] with its face on [0.165, 0.861], and the strip's offset stalled at
1718/// 7e-5 to 1.1e-4 at u = 0.917, OFF the face, against a contract of 2e-6, at
1719/// every seam position of that kind. The shell then refused, or built off its
1720/// oracle. Over the trim the same offset fits to 5e-8.
1721pub fn fit_over_trim_on() -> bool {
1722    switch!("BREP_OFFSET_FIT_OVER_TRIM", true)
1723}
1724
1725thread_local! {
1726    /// Set while [`offset_fit_over_trim`] fits its cropped face: its own fit
1727    /// must not crop again.
1728    static FITTING_OVER_TRIM: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1729}
1730
1731/// The offset of `face`'s support restricted to its trim's parameter box
1732/// cropped halfway from the trim to the nearest stalled site on each side, when `refined`
1733/// misses the fit contract and the cropped fit reads at least four times
1734/// closer; `None` otherwise. The restriction is exact knot insertion, so the
1735/// same (u, v) names the same point and every pcurve on the face still holds.
1736fn offset_fit_over_trim(
1737    face: &FaceRecord,
1738    distance: f64,
1739    refined: &NurbsSurface,
1740    evaluator: &OffsetEvaluator,
1741    sphere_reading: &mut Option<f64>,
1742) -> Result<Option<(NurbsSurface, NurbsSurface)>, KernelRefusal> {
1743    if FITTING_OVER_TRIM.with(std::cell::Cell::get) {
1744        return Ok(None);
1745    }
1746    let source = &face.surface;
1747    let contract = offset_fit_contract(source);
1748    let Ok(whole) = offset_fit_deviation(refined, evaluator, distance) else {
1749        return Ok(None);
1750    };
1751    if whole.worst() <= contract {
1752        return Ok(None);
1753    }
1754    let [u0, u1] = source.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
1755    let [v0, v1] = source.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
1756    // Positive-weight pcurves lie in their control hull: the box cannot crop a
1757    // curved trim's extremum between stations.
1758    let mut bounds = [u1, u0, v1, v0];
1759    for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
1760        for control in &coedge.pcurve.control_points {
1761            let uv = control.point().or_refuse(KernelStage::Refine, "point")?;
1762            bounds[0] = bounds[0].min(uv.x);
1763            bounds[1] = bounds[1].max(uv.x);
1764            bounds[2] = bounds[2].min(uv.y);
1765            bounds[3] = bounds[3].max(uv.y);
1766        }
1767    }
1768    if !(bounds[0] < bounds[1] && bounds[2] < bounds[3]) {
1769        return Ok(None);
1770    }
1771    // Crop only where the STALL lies off the face: every site the fit misses
1772    // by a quarter of its worst or more (and past the contract) must sit
1773    // outside the trim's range (lesser misses on the face are the fit's own,
1774    // and the crop leaves them as they are), and each
1775    // crop edge goes halfway from the trim to the nearest such site on its
1776    // side (a side with none keeps the support's end). A stall on the face is
1777    // the fit's own business, and no crop answers it.
1778    // A site within a fiftieth of the trim's span of its edge is AT the edge:
1779    // a blend whose support changes continuity where its face ends stalls
1780    // there (the boss's rim strip: 6.6e-5 at u = 0.148 with its trim from
1781    // 0.1489), and the crop then sits on the edge itself.
1782    let crop = |sites: &[(f64, f64)], low: f64, high: f64, start: f64, end: f64| -> Option<(f64, f64)> {
1783        let bar = contract.max(0.25 * whole.worst());
1784        let edge = 0.02 * (high - low);
1785        let bad = sites.iter().filter(|(_, miss)| *miss > bar).map(|(at, _)| *at).collect::<Vec<_>>();
1786        if bad.iter().any(|&at| at > low + edge && at < high - edge) {
1787            return None;
1788        }
1789        let below = bad.iter().copied().filter(|&at| at <= low + edge).fold(f64::NEG_INFINITY, f64::max);
1790        let above = bad.iter().copied().filter(|&at| at >= high - edge).fold(f64::INFINITY, f64::min);
1791        let lower = if !below.is_finite() { start } else if below >= low - edge { low } else { 0.5 * (below + low) };
1792        let upper = if !above.is_finite() { end } else if above <= high + edge { high } else { 0.5 * (above + high) };
1793        Some((lower.max(start), upper.min(end)))
1794    };
1795    let Some((crop_u0, crop_u1)) = crop(&whole.u_sites, bounds[0], bounds[1], u0, u1) else {
1796        return Ok(None);
1797    };
1798    let Some((crop_v0, crop_v1)) = crop(&whole.v_sites, bounds[2], bounds[3], v0, v1) else {
1799        return Ok(None);
1800    };
1801    let bounds = [crop_u0, crop_u1, crop_v0, crop_v1];
1802    if bounds[1] - bounds[0] >= 0.95 * (u1 - u0) && bounds[3] - bounds[2] >= 0.95 * (v1 - v0) {
1803        return Ok(None);
1804    }
1805    let restrict = |mut curve: NurbsCurve, low: f64, high: f64| -> Result<NurbsCurve, KernelRefusal> {
1806        let [a, b] = curve.domain().or_refuse(KernelStage::Refine, "domain")?;
1807        // `split` wants its parameter clear of the ends by 1e-9 absolute.
1808        let band = ((b - a) * 1e-12).max(2e-9);
1809        if high < b - band {
1810            curve = curve.split(high.max(a)).or_refuse(KernelStage::Refine, "split")?.0;
1811        }
1812        if low > a + band {
1813            curve = curve.split(low.min(b)).or_refuse(KernelStage::Refine, "split")?.1;
1814        }
1815        Ok(curve)
1816    };
1817    let columns = (0..source.control_points[0].len())
1818        .map(|j| {
1819            let curve = NurbsCurve::new(source.degree_u, source.knots_u.clone(), source.control_points.iter().map(|row| row[j]).collect())
1820                .or_refuse(KernelStage::Refine, "new")?;
1821            restrict(curve, bounds[0], bounds[1])
1822        })
1823        .collect::<Result<Vec<_>, KernelRefusal>>();
1824    // A crop that cannot be cut keeps the whole-support fit: never a refusal.
1825    let Ok(columns) = columns else { return Ok(None) };
1826    let rows = (0..columns[0].control_points.len())
1827        .map(|i| {
1828            let curve = NurbsCurve::new(source.degree_v, source.knots_v.clone(), columns.iter().map(|column| column.control_points[i]).collect())
1829                .or_refuse(KernelStage::Refine, "new")?;
1830            restrict(curve, bounds[2], bounds[3])
1831        })
1832        .collect::<Result<Vec<_>, KernelRefusal>>();
1833    let Ok(rows) = rows else { return Ok(None) };
1834    let Ok(cropped_surface) = NurbsSurface::new(
1835        source.degree_u,
1836        source.degree_v,
1837        columns[0].knots.clone(),
1838        rows[0].knots.clone(),
1839        rows.into_iter().map(|row| row.control_points).collect(),
1840    ) else {
1841        return Ok(None);
1842    };
1843    let mut cropped = face.clone();
1844    cropped.surface = cropped_surface;
1845    struct Release;
1846    impl Drop for Release {
1847        fn drop(&mut self) {
1848            FITTING_OVER_TRIM.with(|cell| cell.set(false));
1849        }
1850    }
1851    FITTING_OVER_TRIM.with(|cell| cell.set(true));
1852    let _release = Release;
1853    let (fitted, lane, extended) = match offset_surface_constructed(&cropped, distance, &CarrierExtension::uniform(0.0), sphere_reading) {
1854        Ok(built) => built,
1855        Err(_) => return Ok(None),
1856    };
1857    if !matches!(lane, OffsetSurfaceLane::Fit) || extended.is_some() {
1858        return Ok(None);
1859    }
1860    let cropped_evaluator = OffsetEvaluator::new("offset_surface", &cropped.surface, OffsetNormal::FaceStable { same_sense: face.same_sense });
1861    let Ok(trimmed) = offset_fit_deviation(&fitted, &cropped_evaluator, distance) else {
1862        return Ok(None);
1863    };
1864    if !(4.0 * trimmed.worst() <= whole.worst()) {
1865        return Ok(None);
1866    }
1867    Ok(Some((fitted, cropped.surface)))
1868}
1869
1870
1871/// Where the sampled OFFSET rulings of an analytic cone or frustum meet its
1872/// axis: the ruling fraction (past 1 beyond the far row, below 0 before the near
1873/// row) and the point. The radial ratio above already gives the fraction (both
1874/// rows and their centroids scale about the apex); what it does not give is the
1875/// POINT the far row must become, so each ruling is met with the recognized axis
1876/// here and the crossings are checked to be one point. `None` unless the source
1877/// is a `RuledRevolution` and every ruling meets the axis within `contract`,
1878/// within `contract` of one point.
1879fn analytic_offset_apex(source: &NurbsSurface, samples: &[Vec<Vec3>], contract: f64) -> Option<(f64, Vec3)> {
1880    let Some(crate::AnalyticSurface::RuledRevolution { frame, .. }) = crate::analytic_surface::recognize(source) else {
1881        return None;
1882    };
1883    let radial = |point: Vec3| {
1884        let offset = point.sub(frame.origin);
1885        offset.sub(frame.axis.scale(offset.dot(frame.axis)))
1886    };
1887    let mut crossings = Vec::with_capacity(samples.len());
1888    for row in samples {
1889        let (near, far) = (radial(row[0]), radial(row[1]));
1890        let step = far.sub(near);
1891        let at = -near.dot(step) / step.dot(step);
1892        if !at.is_finite() {
1893            return None;
1894        }
1895        crossings.push((at, row[0].add(row[1].sub(row[0]).scale(at))));
1896    }
1897    // Averaged as offsets from the first crossing, so a part far from the world
1898    // origin sums small differences, not large coordinates.
1899    let count = crossings.len() as f64;
1900    let at = crossings.iter().map(|(at, _)| at).sum::<f64>() / count;
1901    let first = crossings.first()?.1;
1902    let spread = crossings.iter().fold(Vec3::default(), |sum, (_, point)| sum.add(point.sub(first)));
1903    let centre = first.add(spread.scale(1.0 / count));
1904    let apex = frame.origin.add(frame.axis.scale(centre.sub(frame.origin).dot(frame.axis)));
1905    // On the axis, and one point: a cylinder's near-parallel rulings give a
1906    // finite `at` from rounding, and only these two readings refuse it.
1907    crossings
1908        .iter()
1909        .all(|(_, point)| radial(*point).length() <= contract && point.sub(apex).length() <= contract)
1910        .then_some((at, apex))
1911}
1912
1913/// A linear-v surface continued along its own rulings by `back` and `forward`
1914/// ruling lengths — the same surface, re-parameterized onto the longer span.
1915/// Exact: each ruling is linear in homogeneous coordinates, so extrapolating the
1916/// homogeneous control rows traces the ruling past both ends. Refused where a
1917/// continued weight stops being positive, which is where the ruling leaves the
1918/// rational patch.
1919fn extend_along_rulings(surface: &NurbsSurface, back: f64, forward: f64) -> Result<NurbsSurface, KernelRefusal> {
1920    let rows = surface
1921        .control_points
1922        .iter()
1923        .map(|row| {
1924            let step = row[1].add(row[0].scale(-1.0));
1925            vec![row[0].add(step.scale(-back)), row[1].add(step.scale(forward))]
1926        })
1927        .collect::<Vec<_>>();
1928    if rows.iter().flatten().any(|point| point.w <= 1e-12) {
1929        return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_ruled_extension_weight", format!(
1930            "offset_surface: extending a ruled face by ({back:.6}, {forward:.6}) of its rulings \
1931             carries a weight through zero; the extended face is not this surface"
1932        )));
1933    }
1934    NurbsSurface::new(surface.degree_u, 1, surface.knots_u.clone(), surface.knots_v.clone(), rows)
1935        .or_refuse(KernelStage::Refine, "new")
1936}
1937
1938/// The fit contract a carrier of `source` is refined toward: the kernel's
1939/// intersection-fit tolerance for the source net's extent.
1940fn offset_fit_contract(source: &NurbsSurface) -> f64 {
1941    let scale = crate::model_scale(
1942        source
1943            .control_points
1944            .iter()
1945            .flatten()
1946            .filter_map(|point| point.point().ok()),
1947    );
1948    crate::KernelTolerances::for_scale(scale, 1e-7).intersection_fit
1949}
1950
1951/// Halvings of every knot span [`refine_offset_fit`] may take, per direction.
1952const OFFSET_FIT_REFINEMENTS: usize = 6;
1953
1954/// The largest net one refined collocation may solve: separable weights solve
1955/// one direction at a time, non-separable ones solve the whole tensor densely.
1956const OFFSET_FIT_MAX_CONTROLS_SEPARABLE: usize = 16_384;
1957const OFFSET_FIT_MAX_CONTROLS_TENSOR: usize = 900;
1958
1959/// The out-of-sample deviation of a collocation fit from the pointwise offset,
1960/// read at the MIDPOINTS between consecutive Greville parameters, where the fit
1961/// interpolates nothing: along u (u midpoints on the v Greville rows), along v,
1962/// and between both.
1963#[derive(Clone, Debug)]
1964pub struct OffsetFitDeviation {
1965    along_u: f64,
1966    along_v: f64,
1967    between: f64,
1968    u_sites: Vec<(f64, f64)>,
1969    v_sites: Vec<(f64, f64)>,
1970    between_uv: (f64, f64),
1971}
1972
1973impl OffsetFitDeviation {
1974    pub fn worst(&self) -> f64 {
1975        self.along_u.max(self.along_v).max(self.between)
1976    }
1977
1978    fn refinement_sites(&self, bar: f64) -> (Vec<f64>, Vec<f64>) {
1979        let mut u = self.u_sites.iter().filter(|(_, miss)| *miss > bar)
1980            .map(|(parameter, _)| *parameter).collect::<Vec<_>>();
1981        let mut v = self.v_sites.iter().filter(|(_, miss)| *miss > bar)
1982            .map(|(parameter, _)| *parameter).collect::<Vec<_>>();
1983        if u.is_empty() && v.is_empty() && self.between > bar {
1984            u.push(self.between_uv.0);
1985            v.push(self.between_uv.1);
1986        }
1987        (u, v)
1988    }
1989}
1990
1991fn greville_midpoints(parameters: &[f64]) -> Vec<f64> {
1992    parameters
1993        .windows(2)
1994        .filter(|pair| pair[1] - pair[0] > 1e-12)
1995        .map(|pair| 0.5 * (pair[0] + pair[1]))
1996        .collect()
1997}
1998
1999pub fn offset_fit_deviation(
2000    fitted: &NurbsSurface,
2001    evaluator: &OffsetEvaluator,
2002    distance: f64,
2003) -> Result<OffsetFitDeviation, KernelRefusal> {
2004    let parameters_u = greville_parameters(&KnotVector::new(fitted.knots_u.clone(), fitted.degree_u).or_refuse(KernelStage::Refine, "new")?);
2005    let parameters_v = greville_parameters(&KnotVector::new(fitted.knots_v.clone(), fitted.degree_v).or_refuse(KernelStage::Refine, "new")?);
2006    let (middle_u, middle_v) = (greville_midpoints(&parameters_u), greville_midpoints(&parameters_v));
2007    let residual_locus = std::env::var("BREP_OFFSET_FIT_RESIDUAL").as_deref() != Ok("0");
2008    let gap = |u: f64, v: f64| -> Result<f64, KernelRefusal> {
2009        Ok(fitted.evaluate(u, v).or_refuse(KernelStage::Refine, "evaluate")?.sub(evaluator.at(u, v, -distance).or_refuse(KernelStage::Refine, "at")?.point).length())
2010    };
2011    let mut deviation = OffsetFitDeviation {
2012        along_u: 0.0,
2013        along_v: 0.0,
2014        between: 0.0,
2015        u_sites: Vec::new(),
2016        v_sites: if residual_locus { middle_v.iter().map(|&v| (v, 0.0)).collect() } else { Vec::new() },
2017        between_uv: (0.0, 0.0),
2018    };
2019    for &u in &middle_u {
2020        let mut along = 0.0f64;
2021        for &v in &parameters_v {
2022            let miss = gap(u, v)?;
2023            along = along.max(miss);
2024            deviation.along_u = deviation.along_u.max(miss);
2025        }
2026        if residual_locus { deviation.u_sites.push((u, along)); }
2027        for &v in &middle_v {
2028            let miss = gap(u, v)?;
2029            if miss > deviation.between { deviation.between_uv = (u, v); }
2030            deviation.between = deviation.between.max(miss);
2031        }
2032    }
2033    for &u in &parameters_u {
2034        for (index, &v) in middle_v.iter().enumerate() {
2035            let miss = gap(u, v)?;
2036            deviation.along_v = deviation.along_v.max(miss);
2037            if residual_locus { deviation.v_sites[index].1 = deviation.v_sites[index].1.max(miss); }
2038        }
2039    }
2040    Ok(deviation)
2041}
2042
2043/// `surface` with each requested LINEAR direction raised to cubic, the same
2044/// geometry: every span re-expressed as a cubic Bezier on the homogeneous net
2045/// (the points at thirds), joined C0 by triple knots. `None` when a requested
2046/// direction is not linear or carries a repeated interior knot.
2047///
2048/// A linear direction is raised rather than halved because the offset of a
2049/// ruled surface is generally not ruled, and a piecewise-linear fit converges
2050/// only as h^2: the twisted loft's v direction still read 3.3e-6 after six
2051/// halvings, where the cubic basis converges as h^4.
2052fn raise_linear_directions(
2053    surface: &NurbsSurface,
2054    in_u: bool,
2055    in_v: bool,
2056) -> Result<Option<NurbsSurface>, KernelRefusal> {
2057    fn raise(knots: &[f64], row: &[Vec4]) -> Option<(Vec<f64>, Vec<Vec4>)> {
2058        // Degree 1: knots are [k0, k0, k1, ..., kn, kn] for n + 1 controls.
2059        let count = row.len();
2060        if knots.len() != count + 2 {
2061            return None;
2062        }
2063        let breaks = &knots[1..=count];
2064        if breaks.windows(2).any(|pair| pair[1] - pair[0] <= 1e-12) {
2065            return None;
2066        }
2067        let mut raised_knots = vec![breaks[0]; 4];
2068        for &interior in &breaks[1..count - 1] {
2069            raised_knots.extend([interior; 3]);
2070        }
2071        raised_knots.extend([breaks[count - 1]; 4]);
2072        let mut points = Vec::with_capacity(3 * (count - 1) + 1);
2073        for pair in row.windows(2) {
2074            let step = pair[1].add(pair[0].scale(-1.0));
2075            points.push(pair[0]);
2076            points.push(pair[0].add(step.scale(1.0 / 3.0)));
2077            points.push(pair[0].add(step.scale(2.0 / 3.0)));
2078        }
2079        points.push(row[count - 1]);
2080        Some((raised_knots, points))
2081    }
2082    let mut knots_u = surface.knots_u.clone();
2083    let mut knots_v = surface.knots_v.clone();
2084    let mut degree_u = surface.degree_u;
2085    let mut degree_v = surface.degree_v;
2086    let mut net = surface.control_points.clone();
2087    if in_v {
2088        if degree_v != 1 {
2089            return Ok(None);
2090        }
2091        let mut rows = Vec::with_capacity(net.len());
2092        for row in &net {
2093            let Some((knots, points)) = raise(&surface.knots_v, row) else {
2094                return Ok(None);
2095            };
2096            knots_v = knots;
2097            rows.push(points);
2098        }
2099        net = rows;
2100        degree_v = 3;
2101    }
2102    if in_u {
2103        if degree_u != 1 {
2104            return Ok(None);
2105        }
2106        let count_v = net[0].len();
2107        let mut columns = Vec::with_capacity(count_v);
2108        for column in 0..count_v {
2109            let row = net.iter().map(|row| row[column]).collect::<Vec<_>>();
2110            let Some((knots, points)) = raise(&surface.knots_u, &row) else {
2111                return Ok(None);
2112            };
2113            knots_u = knots;
2114            columns.push(points);
2115        }
2116        let count_u = columns[0].len();
2117        net = (0..count_u)
2118            .map(|row| columns.iter().map(|column| column[row]).collect())
2119            .collect();
2120        degree_u = 3;
2121    }
2122    Ok(Some(NurbsSurface::new(degree_u, degree_v, knots_u, knots_v, net).or_refuse(KernelStage::Refine, "new")?))
2123}
2124
2125/// `surface`, the same geometry with a knot inserted at the midpoint of every
2126/// non-empty span of each requested direction (exact Boehm insertion on the
2127/// homogeneous net, so the weights refine with it).
2128fn halve_knot_spans(surface: &NurbsSurface, in_u: bool, in_v: bool) -> Result<NurbsSurface, KernelRefusal> {
2129    fn midpoints(knots: &[f64], degree: usize) -> Vec<f64> {
2130        let last = knots.len() - 1 - degree;
2131        knots[degree..=last]
2132            .windows(2)
2133            .filter(|pair| pair[1] - pair[0] > 1e-12)
2134            .map(|pair| 0.5 * (pair[0] + pair[1]))
2135            .collect()
2136    }
2137    insert_offset_fit_knots(surface,
2138        &if in_u { midpoints(&surface.knots_u, surface.degree_u) } else { Vec::new() },
2139        &if in_v { midpoints(&surface.knots_v, surface.degree_v) } else { Vec::new() })
2140}
2141
2142/// Insert the fit's measured residual coordinates, rather than relocating
2143/// every collocation node by blindly halving all spans. In particular a
2144/// quadratic's first midpoint insertion loses its old central Greville node;
2145/// inserting the two residual lobes preserves that node and resolves them.
2146fn insert_offset_fit_knots(surface: &NurbsSurface, u: &[f64], v: &[f64]) -> Result<NurbsSurface, KernelRefusal> {
2147    let refine = |degree: usize, knots: &[f64], net: Vec<Vec<Vec4>>, inserted: &[f64]| -> Result<(Vec<f64>, Vec<Vec<Vec4>>), KernelRefusal> {
2148        let mut inserted = inserted.to_vec();
2149        inserted.sort_by(f64::total_cmp);
2150        inserted.dedup_by(|a, b| (*a - *b).abs() <= 1e-12);
2151        inserted.retain(|parameter| knots.iter().filter(|knot| (**knot - *parameter).abs() <= 1e-12).count() < degree);
2152        let mut refined_knots = knots.to_vec();
2153        let mut rows = Vec::with_capacity(net.len());
2154        for row in net {
2155            let mut curve = NurbsCurve::new(degree, knots.to_vec(), row).or_refuse(KernelStage::Refine, "new")?;
2156            for &parameter in &inserted {
2157                curve = curve.insert_knot(parameter, 1).or_refuse(KernelStage::Refine, "insert_knot")?;
2158            }
2159            refined_knots = curve.knots.clone();
2160            rows.push(curve.control_points);
2161        }
2162        Ok((refined_knots, rows))
2163    };
2164    let mut knots_u = surface.knots_u.clone();
2165    let mut knots_v = surface.knots_v.clone();
2166    let mut net = surface.control_points.clone();
2167    if !v.is_empty() {
2168        let (knots, rows) = refine(surface.degree_v, &knots_v, net, v)?;
2169        knots_v = knots;
2170        net = rows;
2171    }
2172    if !u.is_empty() {
2173        // Transpose so each u column is a curve, refine, transpose back.
2174        let count_v = net[0].len();
2175        let columns = (0..count_v)
2176            .map(|column| net.iter().map(|row| row[column]).collect::<Vec<_>>())
2177            .collect::<Vec<_>>();
2178        let (knots, refined) = refine(surface.degree_u, &knots_u, columns, u)?;
2179        knots_u = knots;
2180        let count_u = refined[0].len();
2181        net = (0..count_u)
2182            .map(|row| refined.iter().map(|column| column[row]).collect())
2183            .collect();
2184    }
2185    NurbsSurface::new(surface.degree_u, surface.degree_v, knots_u, knots_v, net).or_refuse(KernelStage::Refine, "new")
2186}
2187
2188/// A collocation fit of the pointwise offset, refined until its OUT-OF-SAMPLE
2189/// deviation meets the kernel's intersection-fit contract.
2190///
2191/// The Greville fit interpolates the pointwise offset in the SOURCE's basis.
2192/// That is exact wherever the offset lives in that basis — planes, cylinders,
2193/// cones, spheres, tori, which is why it was built that way — and, on a
2194/// free-form face, only as good as the source's span count: a single-span cubic
2195/// Bezier wall offset by 0.3 was measured 1.2e-2 to 1.7e-2 off its pointwise
2196/// offset, with the fit exact at its four Greville rows and nowhere else.
2197///
2198/// Refinement halves the knot spans of the direction the deviation is read in
2199/// (exact knot insertion, so the parameterization does not move: the same
2200/// `(u, v)` still names the offset of the same source point, and every trim
2201/// pcurve cloned onto the carrier stays valid) and re-fits. A fit already under
2202/// the bar is returned untouched, bit for bit. The bar is the one a carrier's
2203/// EDGES are already held to (`offset_face_carrier_impl`'s `fit_tolerance`),
2204/// derived from the source net's extent.
2205///
2206/// The contract is a TARGET; the offset construction band is the GATE. A fit
2207/// that is still over the contract when the rounds run out
2208/// ([`OFFSET_FIT_REFINEMENTS`]), when a round stops improving, or when the next
2209/// net would pass the solver ceilings, is ACCEPTED as its best measured round if
2210/// that round is inside `offset_construction_band` — the allowance every
2211/// offset construction in this family is already judged against — and refused
2212/// by name if it is not. Accepted over the contract is a decision, not a
2213/// silence: `offset_surface_measured` reports the deviation, and
2214/// `a_fit_the_rounds_leave_over_the_contract_is_accepted_inside_the_band` pins
2215/// it. (Measured on the corpus: two imported `OFFSET_SURFACE`s end their rounds
2216/// at 1.3e-5 and 3.4e-5 against a contract of 2.15e-6 and a band of 0.107.)
2217///
2218/// Cost is bounded by the rounds: a direction's spans grow at most 64-fold, a
2219/// round costs one pointwise offset per Greville node plus about four per node
2220/// to measure, and one dense collocation solve per row and per column
2221/// (`n_v·n_u³ + n_u·n_v³` for separable weights), and the rounds' costs are
2222/// geometric, so the last round is about half of the whole.
2223pub fn refine_offset_fit(
2224    source: &NurbsSurface,
2225    evaluator: &OffsetEvaluator,
2226    distance: f64,
2227    fitted: NurbsSurface,
2228) -> Result<NurbsSurface, KernelRefusal> {
2229    let scale = crate::model_scale(
2230        source
2231            .control_points
2232            .iter()
2233            .flatten()
2234            .filter_map(|point| point.point().ok()),
2235    );
2236    let bar = crate::KernelTolerances::for_scale(scale, 1e-7).intersection_fit;
2237    let bar = if IMPORT_OFFSET_PRECISION.with(std::cell::Cell::get) { bar.min(1e-9) } else { bar };
2238    let trace = std::env::var("BREP_OFFSET_FIT_TRACE").ok();
2239    let started = web_time::Instant::now();
2240    let enabled = std::env::var("BREP_OFFSET_FIT_REFINE").as_deref() != Ok("0");
2241    let Ok(initial) = offset_fit_deviation(&fitted, evaluator, distance) else {
2242        return Ok(fitted);
2243    };
2244    let mut best = fitted;
2245    let mut best_deviation = initial.clone();
2246    let mut refined_source = source.clone();
2247    let mut rounds = 0usize;
2248    let mut residual_mode = false;
2249    let mut stop = "under bar";
2250    if enabled {
2251        while best_deviation.worst() > bar {
2252            if rounds == OFFSET_FIT_REFINEMENTS {
2253                stop = "refinement limit";
2254                break;
2255            }
2256            let (along_u, along_v) = (best_deviation.along_u > bar, best_deviation.along_v > bar);
2257            let (in_u, in_v) = if along_u || along_v {
2258                (along_u, along_v)
2259            } else {
2260                (true, true)
2261            };
2262            let (raise_u, raise_v) = (in_u && refined_source.degree_u == 1, in_v && refined_source.degree_v == 1);
2263            let raised = if raise_u || raise_v {
2264                raise_linear_directions(&refined_source, raise_u, raise_v)?
2265            } else {
2266                None
2267            };
2268            let (halve_u, halve_v) = match raised {
2269                Some(_) => (in_u && !raise_u, in_v && !raise_v),
2270                None => (in_u, in_v),
2271            };
2272            let raised = raised.unwrap_or_else(|| refined_source.clone());
2273            let candidate_source = if halve_u || halve_v {
2274                if residual_mode {
2275                    let (u, v) = best_deviation.refinement_sites(bar);
2276                    insert_offset_fit_knots(&raised,
2277                        if halve_u { &u } else { &[] }, if halve_v { &v } else { &[] })?
2278                } else {
2279                    halve_knot_spans(&raised, halve_u, halve_v)?
2280                }
2281            } else {
2282                raised
2283            };
2284            let weights = candidate_source
2285                .control_points
2286                .iter()
2287                .map(|row| row.iter().map(|point| point.w).collect::<Vec<_>>())
2288                .collect::<Vec<_>>();
2289            let controls = weights.len() * weights[0].len();
2290            let ceiling = if separable_weights(&weights).is_some() {
2291                OFFSET_FIT_MAX_CONTROLS_SEPARABLE
2292            } else {
2293                OFFSET_FIT_MAX_CONTROLS_TENSOR
2294            };
2295            if controls > ceiling {
2296                stop = "net ceiling";
2297                break;
2298            }
2299            let knot_u = KnotVector::new(candidate_source.knots_u.clone(), candidate_source.degree_u).or_refuse(KernelStage::Refine, "new")?;
2300            let knot_v = KnotVector::new(candidate_source.knots_v.clone(), candidate_source.degree_v).or_refuse(KernelStage::Refine, "new")?;
2301            let parameters_u = greville_parameters(&knot_u);
2302            let parameters_v = greville_parameters(&knot_v);
2303            let samples = parameters_u
2304                .iter()
2305                .map(|&u| {
2306                    parameters_v
2307                        .iter()
2308                        .map(|&v| Ok(evaluator.at(u, v, -distance).or_refuse(KernelStage::Refine, "at")?.point))
2309                        .collect::<Result<Vec<_>, KernelRefusal>>()
2310                })
2311                .collect::<Result<Vec<_>, KernelRefusal>>();
2312            let Ok(samples) = samples else {
2313                stop = "unevaluable sample";
2314                break;
2315            };
2316            let candidate = NurbsSurface::new(
2317                candidate_source.degree_u,
2318                candidate_source.degree_v,
2319                candidate_source.knots_u.clone(),
2320                candidate_source.knots_v.clone(),
2321                interpolate_tensor(&knot_u, &knot_v, &parameters_u, &parameters_v, &samples, &weights)?,
2322            ).or_refuse(KernelStage::Refine, "new")?;
2323            let Ok(deviation) = offset_fit_deviation(&candidate, evaluator, distance) else {
2324                stop = "unmeasurable round";
2325                break;
2326            };
2327            rounds += 1;
2328            if deviation.worst() >= best_deviation.worst() {
2329                // One midpoint split of a quadratic Bezier adds no freedom
2330                // to its symmetric cross-section: the C1 halves still form
2331                // one symmetric quadratic. Its shifted interpolation nodes
2332                // can make this round worse even though the next subdivision
2333                // improves substantially. Try that next subdivision once,
2334                // keeping the previous fit until an improvement is measured.
2335                let first_quadratic_split = rounds == 1
2336                    && ((halve_u && source.degree_u == 2 && source.knots_u.len() == 6)
2337                        || (halve_v && source.degree_v == 2 && source.knots_v.len() == 6));
2338                if first_quadratic_split {
2339                    refined_source = candidate_source;
2340                    continue;
2341                }
2342                // Keep every improving uniform round on its existing path.
2343                // Only a measured stall switches the next attempt to the
2344                // residual locus, starting again from the best accepted net.
2345                // The rejected candidate never replaces that best fit.
2346                if !residual_mode && best_deviation.worst() > offset_construction_band(scale)
2347                    && std::env::var("BREP_OFFSET_FIT_RESIDUAL").as_deref() != Ok("0")
2348                {
2349                    residual_mode = true;
2350                    continue;
2351                }
2352                stop = "stopped improving";
2353                break;
2354            }
2355            best = candidate;
2356            best_deviation = deviation;
2357            refined_source = candidate_source;
2358        }
2359    } else if best_deviation.worst() > bar {
2360        stop = "refinement disabled";
2361    }
2362    // The gate. Refinement aims at the fit contract; a carrier it could not
2363    // bring inside the offset family's own acceptance band is refused by name
2364    // rather than handed on — a fit measured six orders past its band used to be
2365    // recorded and used anyway.
2366    let band = offset_construction_band(scale);
2367    let refused = enabled && best_deviation.worst() > band;
2368    if let Some(path) = trace {
2369        use std::io::Write;
2370        let caller = std::env::args().skip(1).collect::<Vec<_>>().join(" ");
2371        let thread = std::thread::current().name().unwrap_or("-").to_string();
2372        let line = format!(
2373            "fit deg=({},{}) net=({},{})->({},{}) d={distance:.6} scale={scale:.4} bar={bar:.3e} \
2374             initial=(u {:.3e}, v {:.3e}, uv {:.3e}) final={:.3e} rounds={rounds} stop={stop} \
2375             refused={refused} seconds={:.4} thread={thread} args={caller}\n",
2376            source.degree_u,
2377            source.degree_v,
2378            source.control_points.len(),
2379            source.control_points[0].len(),
2380            best.control_points.len(),
2381            best.control_points[0].len(),
2382            initial.along_u,
2383            initial.along_v,
2384            initial.between,
2385            best_deviation.worst(),
2386            started.elapsed().as_secs_f64(),
2387        );
2388        if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
2389            let _ = file.write_all(line.as_bytes());
2390        }
2391    }
2392    if refused {
2393        return Err(KernelRefusal::non_convergence(KernelStage::Refine, "offset_carrier_fit", format!(
2394            "offset_surface: the fitted offset carrier stays {:.3e} off its pointwise offset at \
2395             distance {distance} after {rounds} refinement round(s) ({stop}), past the offset \
2396             construction band {band:.3e}",
2397            best_deviation.worst()
2398        )));
2399    }
2400    Ok(best)
2401}
2402
2403/// Two offset sheets of one source, re-expressed on ONE basis without moving
2404/// either: a linear direction facing a cubic one is raised, then each sheet
2405/// takes the knots the other has and it lacks (exact insertion).
2406///
2407/// [`refine_offset_fit`] refines each carrier by its own measured deviation, so
2408/// two sheets of the same source at different distances can leave on different
2409/// nets; a consumer that pairs their iso curves control point for control point
2410/// (`thicken`'s ruled walls) needs them on the same one. Weights follow the
2411/// insertions, and both sheets carry the source's weights refined the same way.
2412pub fn unify_offset_sheet_bases(
2413    first: &NurbsSurface,
2414    second: &NurbsSurface,
2415) -> Result<(NurbsSurface, NurbsSurface), KernelRefusal> {
2416    fn raise_to(surface: &NurbsSurface, degree_u: usize, degree_v: usize) -> Result<NurbsSurface, KernelRefusal> {
2417        let raise_u = surface.degree_u == 1 && degree_u == 3;
2418        let raise_v = surface.degree_v == 1 && degree_v == 3;
2419        if !raise_u && !raise_v {
2420            return Ok(surface.clone());
2421        }
2422        raise_linear_directions(surface, raise_u, raise_v)?
2423            .ok_or_else(|| {
2424                KernelRefusal::internal(
2425                    KernelStage::Refine,
2426                    "offset_raise_linear",
2427                    "offset sheets: a linear direction could not be raised",
2428                )
2429            })
2430    }
2431    let degree_u = first.degree_u.max(second.degree_u);
2432    let degree_v = first.degree_v.max(second.degree_v);
2433    let mut first = raise_to(first, degree_u, degree_v)?;
2434    let mut second = raise_to(second, degree_u, degree_v)?;
2435    if first.degree_u != second.degree_u || first.degree_v != second.degree_v {
2436        return Err(KernelRefusal::internal(KernelStage::Refine, "offset_common_basis", format!(
2437            "offset sheets: degrees ({},{}) and ({},{}) have no common basis",
2438            first.degree_u, first.degree_v, second.degree_u, second.degree_v
2439        )));
2440    }
2441    // Knots one vector has beyond the other, counted with multiplicity.
2442    fn missing(from: &[f64], into: &[f64]) -> Vec<f64> {
2443        let mut extra = Vec::new();
2444        let mut index = 0usize;
2445        for &knot in from {
2446            while index < into.len() && into[index] < knot - 1e-12 {
2447                index += 1;
2448            }
2449            if index < into.len() && (into[index] - knot).abs() <= 1e-12 {
2450                index += 1;
2451            } else {
2452                extra.push(knot);
2453            }
2454        }
2455        extra
2456    }
2457    fn insert(surface: &NurbsSurface, knots: &[f64], along_u: bool) -> Result<NurbsSurface, KernelRefusal> {
2458        if knots.is_empty() {
2459            return Ok(surface.clone());
2460        }
2461        let (degree, vector) = if along_u {
2462            (surface.degree_u, &surface.knots_u)
2463        } else {
2464            (surface.degree_v, &surface.knots_v)
2465        };
2466        let lines = if along_u {
2467            (0..surface.control_points[0].len())
2468                .map(|column| surface.control_points.iter().map(|row| row[column]).collect::<Vec<_>>())
2469                .collect::<Vec<_>>()
2470        } else {
2471            surface.control_points.clone()
2472        };
2473        let mut refined_knots = vector.clone();
2474        let mut refined = Vec::with_capacity(lines.len());
2475        for line in lines {
2476            let mut curve = NurbsCurve::new(degree, vector.clone(), line).or_refuse(KernelStage::Refine, "new")?;
2477            for &knot in knots {
2478                curve = curve.insert_knot(knot, 1).or_refuse(KernelStage::Refine, "insert_knot")?;
2479            }
2480            refined_knots = curve.knots.clone();
2481            refined.push(curve.control_points);
2482        }
2483        let net = if along_u {
2484            (0..refined[0].len())
2485                .map(|row| refined.iter().map(|column| column[row]).collect())
2486                .collect()
2487        } else {
2488            refined
2489        };
2490        let (knots_u, knots_v) = if along_u {
2491            (refined_knots, surface.knots_v.clone())
2492        } else {
2493            (surface.knots_u.clone(), refined_knots)
2494        };
2495        NurbsSurface::new(surface.degree_u, surface.degree_v, knots_u, knots_v, net).or_refuse(KernelStage::Refine, "new")
2496    }
2497    let (to_first_u, to_second_u) = (
2498        missing(&second.knots_u, &first.knots_u),
2499        missing(&first.knots_u, &second.knots_u),
2500    );
2501    first = insert(&first, &to_first_u, true)?;
2502    second = insert(&second, &to_second_u, true)?;
2503    let (to_first_v, to_second_v) = (
2504        missing(&second.knots_v, &first.knots_v),
2505        missing(&first.knots_v, &second.knots_v),
2506    );
2507    first = insert(&first, &to_first_v, false)?;
2508    second = insert(&second, &to_second_v, false)?;
2509    Ok((first, second))
2510}
2511
2512/// The 3D curve of one carrier edge: the image of the source coedge's pcurve
2513/// on the carrier surface, with the parameter range `(t0, t1)` that matches the
2514/// pcurve's domain fraction for fraction (the contract every coedge of this
2515/// carrier relies on, since the source pcurves are reused verbatim).
2516///
2517/// Built through the [`crate::image_curve`] ladder — exact on an affine sheet
2518/// (every planar offset), the exact iso-curve where the pcurve holds one
2519/// coordinate constant (a blend rail, a cylinder's cap rim, every
2520/// extrude/revolve boundary), and a fitted curve verified to `fit_tolerance`
2521/// off its nodes otherwise. Only where the ladder refuses does the edge fall
2522/// back to the degree-1 interpolant through `points` (the historical
2523/// construction), so nothing that offset before is refused now.
2524///
2525/// Why the polyline is no longer the first choice: its adaptive subdivision
2526/// stops at a 5e-4 chord sag, and a 128-chord rim on an r = 8.5 cylinder sits
2527/// up to 1.6e-4 inside the true arc. That is 16x the boolean imprint's
2528/// coincidence band, so when a later operation's section curve runs along that
2529/// rim (a cutter's side wall coplanar with the offset shell's opening wall,
2530/// 2026-09-06 report) the imprint cannot recognise the rim as the section it
2531/// already is, and reports every chord vertex as a crossing — one edge split
2532/// into forty. An exact arc is recognised as coincident and left alone.
2533pub fn carrier_edge_curve(
2534    surface: &NurbsSurface,
2535    pcurve: &NurbsCurve,
2536    points: &[Vec3],
2537    parameters: &[f64],
2538    fit_tolerance: f64,
2539) -> Result<(NurbsCurve, f64, f64), KernelRefusal> {
2540    // `BREP_CARRIER_POLYLINE=1` restores the polyline for an A/B comparison.
2541    // TRUSTED AFFINE IMAGE (lane O row 23, 2026-10-29). On an affine carrier the image
2542    // is the pcurve's control net through the patch's own affine map, exact up to
2543    // round-off for any degree and weights, so `image_curve`'s 25-sample sweep
2544    // can only confirm it; this caller discards the deviation it measures. The
2545    // image and its range are what `image_curve`'s affine tier returns.
2546    if surface.is_affine().or_refuse(KernelStage::Refine, "is_affine")? {
2547        let [q0, q1] = pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
2548        if (q1 - q0).is_finite() && (q1 - q0).abs() > 0.0 {
2549            let curve = crate::image_curve::affine_image_curve(surface, pcurve).or_refuse(KernelStage::Refine, "affine_image_curve")?;
2550            return Ok((curve, q0, q1));
2551        }
2552    }
2553    let image = if env_read!("BREP_CARRIER_POLYLINE").as_deref() == Some("1") {
2554        Err("BREP_CARRIER_POLYLINE set".to_string())
2555    } else {
2556        crate::image_curve::image_curve(surface, pcurve, fit_tolerance, "offset_face_carrier")
2557    };
2558    match image {
2559        Ok(image) if image.t0 <= image.t1 => Ok((image.curve, image.t0, image.t1)),
2560        Ok(image) => {
2561            // The image runs against the pcurve: reverse it so the edge range
2562            // is increasing, reflecting the range through the curve's domain.
2563            let [start, end] = image.curve.domain().or_refuse(KernelStage::Refine, "domain")?;
2564            let curve = image.curve.reversed().or_refuse(KernelStage::Refine, "reversed")?;
2565            Ok((curve, start + end - image.t0, start + end - image.t1))
2566        }
2567        Err(_) => {
2568            let curve = interpolate_curve(points, 1, parameters).or_refuse(KernelStage::Refine, "interpolate_curve")?;
2569            let [t0, t1] = curve.domain().or_refuse(KernelStage::Refine, "domain")?;
2570            Ok((curve, t0, t1))
2571        }
2572    }
2573}
2574
2575/// Avoid constructing the fallback trace when the exact image will be used.
2576/// Positive, bounded control nets on well-separated knots make every skipped
2577/// in-domain evaluation total. The collapse witness is an actual vertex of
2578/// the old adaptive trace: its last point, or its midpoint when the first
2579/// subdivision fires. Near-collapsed images and uncertified inputs stay eager.
2580/// `BREP_OFFSET_LAZY_CARRIER_TRACE`; on by default since
2581/// 2026-11-02, `0`/`off` restores the eager trace.
2582pub fn lazy_carrier_trace(
2583    surface: &NurbsSurface,
2584    pcurve: &NurbsCurve,
2585    collapse_tolerance: f64,
2586    fit_tolerance: f64,
2587) -> Option<(Vec<Vec3>, (NurbsCurve, f64, f64))> {
2588    if !switch!("BREP_OFFSET_LAZY_CARRIER_TRACE", true) {
2589        return None;
2590    }
2591    // A straight image costs only the initial five samples. Do not spend
2592    // certificate/ladder setup on those small traces.
2593    if pcurve.degree == 1 && pcurve.control_points.len() == 2 {
2594        let (a, b) = (pcurve.control_points[0], pcurve.control_points[1]);
2595        if (surface.degree_u <= 1 && surface.degree_v <= 1)
2596            || (a.w == b.w && a.y == b.y && surface.degree_u <= 1)
2597            || (a.w == b.w && a.x == b.x && surface.degree_v <= 1)
2598        {
2599            return None;
2600        }
2601    }
2602    fn knots_ok(knots: &[f64], degree: usize, count: usize) -> bool {
2603        degree <= 3 && count <= 64
2604            && KnotVector::new(knots.to_vec(), degree).ok().is_some_and(|k| k.control_point_count() == count)
2605            && knots.iter().all(|k| k.is_finite() && k.abs() <= 1e6)
2606            && knots.windows(2).all(|k| k[0] == k[1] || k[1] - k[0] >= 1e-6)
2607    }
2608    let bounded = |p: &Vec4| (1e-3..=1e3).contains(&p.w)
2609        && [p.x, p.y, p.z].iter().all(|x| x.is_finite() && x.abs() <= 1e12);
2610    let columns = surface.control_points.first()?.len();
2611    if !knots_ok(&surface.knots_u, surface.degree_u, surface.control_points.len())
2612        || !knots_ok(&surface.knots_v, surface.degree_v, columns)
2613        || surface.control_points.iter().any(|row| row.len() != columns || row.iter().any(|p| !bounded(p)))
2614        || !knots_ok(&pcurve.knots, pcurve.degree, pcurve.control_points.len())
2615        || pcurve.control_points.iter().any(|p| !bounded(p))
2616    {
2617        return None;
2618    }
2619    let ([u0, u1], [v0, v1]) = (surface.domain_u().ok()?, surface.domain_v().ok()?);
2620    let uv = pcurve.control_points.iter().map(|p| p.point().ok()).collect::<Option<Vec<_>>>()?;
2621    if uv.iter().any(|p| p.x < u0 || p.x > u1 || p.y < v0 || p.y > v1) {
2622        return None;
2623    }
2624    // Only the ladder's exact tiers: a fitted image is not worth speculating.
2625    if !surface.is_affine().ok()? && !uv.iter().all(|p| p.x == uv[0].x) && !uv.iter().all(|p| p.y == uv[0].y) {
2626        return None;
2627    }
2628    let [start, end] = pcurve.domain().ok()?;
2629    let evaluate = |fraction: f64| {
2630        let uv = pcurve.evaluate(start + (end - start) * fraction).ok()?;
2631        surface.evaluate(uv.x, uv.y).ok()
2632    };
2633    let first = evaluate(0.0)?;
2634    let last = evaluate(1.0)?;
2635    let samples = [evaluate(0.25)?, evaluate(0.5)?, evaluate(0.75)?];
2636    let deviation = samples.iter().enumerate().map(|(index, point)| {
2637        point.sub(first.add(last.sub(first).scale((index + 1) as f64 * 0.25))).length()
2638    }).fold(0.0, f64::max);
2639    if last.sub(first).length() <= collapse_tolerance
2640        && !(deviation > 5e-4 && samples[1].sub(first).length() > collapse_tolerance)
2641    {
2642        return None;
2643    }
2644    // Empty fallback data deliberately declines a refused image; the caller
2645    // then takes the old trace and preserves its refusal and interpolation.
2646    let image = carrier_edge_curve(surface, pcurve, &[], &[], fit_tolerance).ok()?;
2647    Some((vec![first, samples[1], last], image))
2648}
2649
2650pub fn mapped_pcurve_polyline(
2651    surface: &NurbsSurface,
2652    pcurve: &NurbsCurve,
2653    degenerate: bool,
2654) -> Result<(Vec<Vec3>, Vec<f64>), KernelRefusal> {
2655    let [start, end] = pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
2656    let evaluate = |fraction: f64| -> Result<Vec3, KernelRefusal> {
2657        let uv = pcurve.evaluate(start + (end - start) * fraction).or_refuse(KernelStage::Refine, "evaluate")?;
2658        surface.evaluate(uv.x, uv.y).or_refuse(KernelStage::Refine, "evaluate")
2659    };
2660    let first = evaluate(0.0)?;
2661    let last = evaluate(1.0)?;
2662    if degenerate {
2663        return Ok((vec![first, last], vec![0.0, 1.0]));
2664    }
2665    fn append(
2666        evaluate: &impl Fn(f64) -> Result<Vec3, KernelRefusal>,
2667        a_fraction: f64,
2668        a: Vec3,
2669        b_fraction: f64,
2670        b: Vec3,
2671        depth: usize,
2672        parameters: &mut Vec<f64>,
2673        points: &mut Vec<Vec3>,
2674    ) -> Result<(), KernelRefusal> {
2675        let fractions =
2676            [0.25, 0.5, 0.75].map(|local| a_fraction + (b_fraction - a_fraction) * local);
2677        let samples = fractions
2678            .map(evaluate)
2679            .into_iter()
2680            .collect::<Result<Vec<_>, KernelRefusal>>()?;
2681        let deviation = samples
2682            .iter()
2683            .enumerate()
2684            .map(|(index, point)| {
2685                point
2686                    .sub(a.add(b.sub(a).scale((index + 1) as f64 * 0.25)))
2687                    .length()
2688            })
2689            .fold(0.0, f64::max);
2690        if deviation <= 5e-4 || depth >= 10 {
2691            parameters.push(b_fraction);
2692            points.push(b);
2693            return Ok(());
2694        }
2695        append(
2696            evaluate,
2697            a_fraction,
2698            a,
2699            fractions[1],
2700            samples[1],
2701            depth + 1,
2702            parameters,
2703            points,
2704        )?;
2705        append(
2706            evaluate,
2707            fractions[1],
2708            samples[1],
2709            b_fraction,
2710            b,
2711            depth + 1,
2712            parameters,
2713            points,
2714        )
2715    }
2716    let mut parameters = vec![0.0];
2717    let mut points = vec![first];
2718    append(
2719        &evaluate,
2720        0.0,
2721        first,
2722        1.0,
2723        last,
2724        0,
2725        &mut parameters,
2726        &mut points,
2727    )?;
2728    Ok((points, parameters))
2729}
2730
2731/// Everything an offset carrier's construction MEASURED about itself.
2732///
2733/// The half this kernel lacked: a tolerance MEASURED from the geometry that was
2734/// actually built, rather than a band chosen from `scale` before building. It
2735/// lives in the one place that needs no durable-format change: alongside the
2736/// transient construction result, never as a field on a [`crate::BrepSolid`]
2737/// record. `io/snapshot.rs` is a documented durable format and
2738/// `SOLID_CODEC_VERSION` a versioned wire layout; persisting per-entity
2739/// tolerances is real, planned, and separately designed. This lands the
2740/// measurement with no format churn at all.
2741///
2742/// Every number here is a RECORD. None of it widens a band — see
2743/// [`MeasuredTolerance`]'s direction rule.
2744#[derive(Clone, Debug)]
2745pub struct CarrierDeviation {
2746    /// The derived band every measurement below was judged against:
2747    /// [`crate::offset_construction_band`] of the source solid's extent.
2748    pub band: f64,
2749    /// Which branch built the carrier surface.
2750    pub lane: OffsetSurfaceLane,
2751    /// The carrier surface's own fit error, when the lane has one.
2752    pub surface: Option<MeasuredTolerance>,
2753    /// `max_t ‖C_3d(t) − S_off(p(t))‖` per carrier edge id, folded over every
2754    /// coedge that references the edge — OCCT's `FillEdgeData` rule
2755    /// (`BRepOffset_SimpleOffset.cxx:296-310`), which takes the maximum over
2756    /// **every** adjacent face rather than the first one.
2757    pub edges: Vec<(u64, MeasuredTolerance)>,
2758    /// Per carrier vertex id, propagated from the incident edge ends by
2759    /// [`crate::vertex_tolerance_from_edges`] — which is also where the verdict
2760    /// on OCCT's 1.001 inflation factor is recorded.
2761    pub vertices: Vec<(u64, f64)>,
2762}
2763
2764impl CarrierDeviation {
2765    /// The worst thing the construction did, against the tightest band it
2766    /// faced. `None` only when there was nothing at all to measure.
2767    pub fn worst(&self) -> Option<MeasuredTolerance> {
2768        MeasuredTolerance::worst(
2769            self.surface
2770                .into_iter()
2771                .chain(self.edges.iter().map(|(_, measured)| *measured))
2772                .chain(
2773                    self.vertices
2774                        .iter()
2775                        .map(|(_, gap)| MeasuredTolerance::new(*gap, self.band)),
2776                ),
2777        )
2778    }
2779
2780    /// The entities whose measured deviation exceeded the derived band — the
2781    /// interesting case, and the only one any gate acts on.
2782    pub fn exceedances(&self) -> Vec<String> {
2783        let mut out = Vec::new();
2784        if let Some(surface) = self.surface {
2785            if surface.exceeds_band() {
2786                out.push(format!("carrier surface fit {}", surface.describe()));
2787            }
2788        }
2789        for (id, measured) in &self.edges {
2790            if measured.exceeds_band() {
2791                out.push(format!("edge {id} {}", measured.describe()));
2792            }
2793        }
2794        for (id, gap) in &self.vertices {
2795            let measured = MeasuredTolerance::new(*gap, self.band);
2796            if measured.exceeds_band() {
2797                out.push(format!("vertex {id} {}", measured.describe()));
2798            }
2799        }
2800        out
2801    }
2802}
2803
2804#[derive(Clone, Debug, Serialize)]
2805pub struct OffsetFaceCarrier {
2806    pub vertices: Vec<VertexRecord>,
2807    pub edges: Vec<EdgeRecord>,
2808    pub face: FaceRecord,
2809    /// What the construction measured about itself, or `None` when it was built
2810    /// through the unmeasured [`offset_face_carrier`] entry point.
2811    ///
2812    /// `#[serde(skip)]` on purpose: this struct crosses the wasm ABI as JSON
2813    /// (`abi/modeling_b.rs:500`), and a measurement is a diagnostic about a
2814    /// build, not part of the carrier the caller asked for. Skipping it keeps
2815    /// that payload byte-identical.
2816    #[serde(skip)]
2817    pub deviation: Option<CarrierDeviation>,
2818    /// Which branch built the carrier surface (always known; `deviation`
2819    /// carries it too, but only on the measured entry point). Skipped on the
2820    /// ABI for the same reason as `deviation`.
2821    #[serde(skip)]
2822    pub lane: OffsetSurfaceLane,
2823}
2824
2825/// The carrier vertex imaging `source_id` at `point`. A source vertex
2826/// normally has ONE image, claimed by the first edge to reach it. An APEX
2827/// does not: the offset of a corner blend's apex (a partial surface of
2828/// revolution about a reflex edge, its degenerate edge spanning the turn) is
2829/// an open ARC of radius |d|, and the two meridian edges into the apex end at
2830/// the arc's two ends. Handing every edge the first image collapsed that arc
2831/// onto one vertex while its curve still ran 1.7·d to the other end — a loop
2832/// that closes in ids and not in space, which the assembly could only leave
2833/// open (the 2026-10-18 shell report). An image farther than `split` from
2834/// every image already claimed is a vertex of its own.
2835fn claim_vertex_image(
2836    source_id: u64,
2837    point: Vec3,
2838    split: f64,
2839    vertex_images: &mut HashMap<u64, Vec<u64>>,
2840    vertices: &mut Vec<VertexRecord>,
2841    next_id: &mut u64,
2842) -> u64 {
2843    if let Some(ids) = vertex_images.get(&source_id) {
2844        let near = ids.iter().copied().find(|id| {
2845            vertices
2846                .iter()
2847                .find(|vertex| vertex.id == *id)
2848                .is_some_and(|vertex| vertex.point.sub(point).length() <= split)
2849        });
2850        if let Some(id) = near {
2851            return id;
2852        }
2853    }
2854    let id = *next_id;
2855    *next_id += 1;
2856    vertices.push(VertexRecord { id, point });
2857    vertex_images.entry(source_id).or_default().push(id);
2858    id
2859}
2860
2861pub fn offset_face_carrier(
2862    solid: &BrepSolid,
2863    face_id: u64,
2864    distance: f64,
2865    planar_extension: f64,
2866) -> Result<OffsetFaceCarrier, KernelRefusal> {
2867    offset_face_carrier_impl(
2868        solid,
2869        face_id,
2870        distance,
2871        &CarrierExtension::uniform(planar_extension),
2872        false,
2873    )
2874}
2875
2876/// [`offset_face_carrier`] with a per-side [`CarrierExtension`].
2877/// `BREP_OFFSET_PINCH_SIDE_BY_SOURCE` (default on; `=0` restores the size rule): which end of an inverted
2878/// ruled offset is past its pinch, read by direction rather than by size.
2879///
2880/// Cause (brep-bench probe, a cone r 3 h 4 shelled open at its base, walls 1.9
2881/// to 2.5 refused "unwelded rim leaves a non-watertight shell"): the pinch
2882/// retrim took the end with the SMALLER offset ring as the crossed one. Shrunk
2883/// by t, the base ring offsets to radius 3 − 0.8 t and the apex ring, crossed
2884/// through the axis, to 0.8 t; from t = 1.875 the true base ring is the smaller,
2885/// so the retrim pulled the cavity wall back to the pinch and kept the mirrored
2886/// sheet, which no weld can use. The crossed end is the one whose offset ring
2887/// points opposite to the source's own radial direction (read at the source's
2888/// wider ring, the other may be an apex). `None` when that reading does not
2889/// single out one end; the size rule stands.
2890fn pinch_side_by_source_enabled() -> bool {
2891    switch!("BREP_OFFSET_PINCH_SIDE_BY_SOURCE", true)
2892}
2893
2894fn pinch_side_by_source(
2895    source: &NurbsSurface,
2896    parameters_u: &[f64],
2897    parameters_v: &[f64],
2898    samples: &[Vec<Vec3>],
2899    near_centroid: Vec3,
2900    far_centroid: Vec3,
2901) -> Result<Option<bool>, KernelRefusal> {
2902    if !pinch_side_by_source_enabled() || parameters_v.len() != 2 {
2903        return Ok(None);
2904    }
2905    let mut source_rows = [Vec::new(), Vec::new()];
2906    for &u in parameters_u {
2907        for (end, &v) in parameters_v.iter().enumerate() {
2908            source_rows[end].push(source.evaluate(u, v).or_refuse(KernelStage::Refine, "evaluate")?);
2909        }
2910    }
2911    let centroid = |row: &[Vec3]| row.iter().fold(Vec3::default(), |sum, p| sum.add(*p)).scale(1.0 / row.len() as f64);
2912    let spread = |row: &[Vec3]| {
2913        let middle = centroid(row);
2914        row.iter().map(|p| p.sub(middle).length()).fold(0.0f64, f64::max)
2915    };
2916    let reference = if spread(&source_rows[0]) >= spread(&source_rows[1]) { 0 } else { 1 };
2917    let reference_centroid = centroid(&source_rows[reference]);
2918    let (mut near_sign, mut far_sign) = (0.0f64, 0.0f64);
2919    for (k, row) in samples.iter().enumerate() {
2920        let radial = source_rows[reference][k].sub(reference_centroid);
2921        near_sign += row[0].sub(near_centroid).dot(radial);
2922        far_sign += row[1].sub(far_centroid).dot(radial);
2923    }
2924    Ok(match (near_sign > 0.0, far_sign > 0.0) {
2925        (true, false) => Some(true),
2926        (false, true) => Some(false),
2927        _ => None,
2928    })
2929}
2930
2931pub fn offset_face_carrier_sided(
2932    solid: &BrepSolid,
2933    face_id: u64,
2934    distance: f64,
2935    extension: &CarrierExtension,
2936) -> Result<OffsetFaceCarrier, KernelRefusal> {
2937    offset_face_carrier_impl(solid, face_id, distance, extension, false)
2938}
2939
2940/// [`offset_face_carrier`], with every entity it builds measured against the
2941/// deviation it was meant to reproduce.
2942///
2943/// The carrier is bit-identical to [`offset_face_carrier`]'s — same body, same
2944/// arithmetic, in the same order — with a read-only measurement pass appended.
2945/// Three quantities land in [`CarrierDeviation`]:
2946///
2947/// * the carrier SURFACE's fit against the pointwise offset it interpolates
2948///   ([`offset_surface_measured`]);
2949/// * each carrier EDGE's 3D curve against the locus its pcurve traces on that
2950///   surface — the trim boundary is built by sampling exactly that composition
2951///   and interpolating the images, so this is the construction's own claim,
2952///   measured rather than assumed;
2953/// * each carrier VERTEX, propagated from the incident edge ends.
2954///
2955/// The interesting output is [`CarrierDeviation::exceedances`]: an entity whose
2956/// measured deviation is worse than the size-derived band assumed. That is a
2957/// construction that went wrong in a way the derived band alone cannot see, and
2958/// it is the case a caller should refuse on rather than ship.
2959pub fn offset_face_carrier_measured(
2960    solid: &BrepSolid,
2961    face_id: u64,
2962    distance: f64,
2963    planar_extension: f64,
2964) -> Result<OffsetFaceCarrier, KernelRefusal> {
2965    offset_face_carrier_impl(
2966        solid,
2967        face_id,
2968        distance,
2969        &CarrierExtension::uniform(planar_extension),
2970        true,
2971    )
2972}
2973
2974/// The measured deviations of one built carrier: surface fit, per edge, per
2975/// vertex.
2976///
2977/// Read-only over what the construction produced. The edge measurement is
2978/// [`crate::measure_edge_against_pcurve_image`] — validate's own
2979/// `adaptive_coedge_error` floored by a span-midpoint pass, because the sampler
2980/// alone is aliased against exactly the curves this construction builds (see
2981/// that module's doc) — taken against the far tighter
2982/// [`crate::offset_construction_band`] instead of the vendor-forgiving
2983/// `pcurve_acceptance` validate will use later.
2984fn measure_carrier(
2985    surface: &NurbsSurface,
2986    vertices: &[VertexRecord],
2987    edges: &[EdgeRecord],
2988    loops: &[LoopRecord],
2989    lane: OffsetSurfaceLane,
2990    surface_fit: Option<MeasuredTolerance>,
2991    band: f64,
2992) -> Result<CarrierDeviation, KernelRefusal> {
2993    let edge_by_id: HashMap<u64, &EdgeRecord> = edges.iter().map(|edge| (edge.id, edge)).collect();
2994    // Fold over coedges, not edges: a seam edge is referenced twice with two
2995    // different pcurves, and OCCT's `FillEdgeData` takes the maximum over every
2996    // adjacent face for exactly that reason.
2997    let mut per_edge: HashMap<u64, MeasuredTolerance> = HashMap::default();
2998    for loop_record in loops {
2999        for coedge in &loop_record.coedges {
3000            let Some(edge) = edge_by_id.get(&coedge.edge_id) else {
3001                continue;
3002            };
3003            let measured = measure_edge_against_pcurve_image(
3004                surface,
3005                &coedge.pcurve,
3006                edge,
3007                coedge.forward,
3008                band,
3009            )?;
3010            per_edge
3011                .entry(edge.id)
3012                .and_modify(|existing| *existing = existing.worse_of(measured))
3013                .or_insert(measured);
3014        }
3015    }
3016
3017    let mut measured_edges: Vec<(u64, MeasuredTolerance)> = per_edge.into_iter().collect();
3018    measured_edges.sort_by_key(|(id, _)| *id);
3019    let deviation_of: HashMap<u64, f64> = measured_edges
3020        .iter()
3021        .map(|(id, measured)| (*id, measured.deviation()))
3022        .collect();
3023
3024    // Edge ENDS by the vertex they claim, built once. A degenerate edge claims
3025    // the same vertex at both ends and contributes both, which is right: the
3026    // question is how far every representation meeting there actually lands.
3027    let mut ends_at: HashMap<u64, Vec<(&EdgeRecord, f64)>> = HashMap::default();
3028    for edge in edges {
3029        ends_at
3030            .entry(edge.start_vertex_id)
3031            .or_default()
3032            .push((edge, edge.t0));
3033        ends_at
3034            .entry(edge.end_vertex_id)
3035            .or_default()
3036            .push((edge, edge.t1));
3037    }
3038
3039    let mut measured_vertices = Vec::with_capacity(vertices.len());
3040    for vertex in vertices {
3041        let mut gaps = Vec::new();
3042        let mut incident = Vec::new();
3043        for (edge, parameter) in ends_at.get(&vertex.id).into_iter().flatten() {
3044            gaps.push(vertex_endpoint_gap(
3045                vertex.point,
3046                edge.curve.evaluate(*parameter).or_refuse(KernelStage::Refine, "evaluate")?,
3047            ));
3048            incident.push(deviation_of.get(&edge.id).copied().unwrap_or(0.0));
3049        }
3050        measured_vertices.push((vertex.id, vertex_tolerance_from_edges(gaps, incident)));
3051    }
3052
3053    Ok(CarrierDeviation {
3054        band,
3055        lane,
3056        surface: surface_fit,
3057        edges: measured_edges,
3058        vertices: measured_vertices,
3059    })
3060}
3061
3062fn offset_face_carrier_impl(
3063    solid: &BrepSolid,
3064    face_id: u64,
3065    distance: f64,
3066    extension: &CarrierExtension,
3067    measure: bool,
3068) -> Result<OffsetFaceCarrier, KernelRefusal> {
3069    let source = solid
3070        .shells
3071        .iter()
3072        .flat_map(|shell| &shell.faces)
3073        .find(|face| face.id == face_id)
3074        .ok_or_else(|| format!("offset_face_carrier: missing face {face_id}")).or_refuse(KernelStage::Refine, "offset_missing_face")?;
3075    // The band is derived from the SOURCE SOLID's extent, matching every other
3076    // direct-edit/offset site (`face_offset.rs:103` and its siblings all take
3077    // `solid_model_scale`). The alternative basis is the FACE's own extent — the
3078    // reference shell keys its size-relative offset quantities on the 3D arc
3079    // length of the face's own boundary iso, never on the assembly. Which basis
3080    // is better is unsettled: it is a measurement to make over the refusal
3081    // corpus before switching, not a change to smuggle in here.
3082    let band = offset_construction_band(solid_model_scale(solid));
3083    // The accuracy bar a carrier EDGE's 3D curve must meet against the locus its
3084    // pcurve traces on the carrier surface — the kernel's own SSI fit contract,
3085    // the same bar `thicken` holds its wall boundaries to. NOT the construction
3086    // band: that is the surface-fit allowance (5e-4 of the part), 50x looser
3087    // than the boolean's coincidence band, and an edge fitted only that well is
3088    // what a later imprint mistakes for a crossing (see `carrier_edge_curve`).
3089    let fit_tolerance =
3090        crate::KernelTolerances::for_scale(solid_model_scale(solid), 1e-7).intersection_fit;
3091    let (surface, lane, surface_fit) = if measure {
3092        let measured = offset_surface_measured_sided(source, distance, extension, band)?;
3093        (measured.surface, measured.lane, measured.fit)
3094    } else {
3095        let (surface, lane) = offset_surface_with_lane(source, distance, extension)?;
3096        (surface, lane, None)
3097    };
3098    let source_edges = solid
3099        .edges
3100        .iter()
3101        .map(|edge| (edge.id, edge))
3102        .collect::<HashMap<_, _>>();
3103    let source_vertices = solid
3104        .vertices
3105        .iter()
3106        .map(|vertex| (vertex.id, vertex))
3107        .collect::<HashMap<_, _>>();
3108    let mut vertices = Vec::new();
3109    let mut vertex_images = HashMap::default();
3110    // Two images of one source vertex this far apart are two vertices (an
3111    // apex's arc, `claim_vertex_image`); fitting noise at a pole stays far
3112    // below it.
3113    let vertex_split = (distance.abs() * 0.1).max(band);
3114    let mut edges = Vec::new();
3115    let mut edge_images = HashMap::default();
3116    let mut loops = Vec::new();
3117    let mut next_id = 1u64;
3118
3119    for source_loop in &source.loops {
3120        let mut coedges = Vec::new();
3121        for source_coedge in &source_loop.coedges {
3122            let source_edge = source_edges
3123                .get(&source_coedge.edge_id)
3124                .ok_or_else(|| "offset_face_carrier: missing source edge".to_string()).or_refuse(KernelStage::Refine, "offset_missing_edge")?;
3125            let (source_start, source_end) = if source_coedge.forward {
3126                (source_edge.start_vertex_id, source_edge.end_vertex_id)
3127            } else {
3128                (source_edge.end_vertex_id, source_edge.start_vertex_id)
3129            };
3130            if !source_vertices.contains_key(&source_start)
3131                || !source_vertices.contains_key(&source_end)
3132            {
3133                return Err(KernelRefusal::internal(KernelStage::Refine, "offset_missing_vertex", "offset_face_carrier: missing source vertex"));
3134            }
3135            // Map even DEGENERATE source edges through the full polyline: a
3136            // cone apex's image on the offset surface is a genuine CIRCLE
3137            // (radius d·cos half-angle), not a point — shortcutting to the
3138            // two endpoints would collapse the ring and leave the carrier's
3139            // topology inconsistent with its surface. Edges whose image truly
3140            // collapses (sphere poles, planar corners) still interpolate to a
3141            // point-sized curve and keep their degenerate flag below.
3142            // Map even DEGENERATE source edges through the full polyline: an
3143            // EXTERIOR cone offset turns the apex point into a genuine RING
3144            // (radius d·cos half-angle) — shortcutting to the endpoints would
3145            // collapse it and leave the carrier topology inconsistent with
3146            // its surface (and the ring imprint would be dropped as
3147            // boundary-coincident with a "degenerate" edge). Images that
3148            // truly collapse (sphere poles; interior apexes after the pinch
3149            // retrim) stay degenerate below. The threshold scales with the
3150            // offset distance: a real ring measures ~d·cos α, while fitted
3151            // pole rows wobble ~1e-4 absolute.
3152            let collapse_tolerance = 1e-6f64.max(distance.abs() * 1e-2);
3153            let (points, parameters, exact_image) = match lazy_carrier_trace(
3154                &surface, &source_coedge.pcurve, collapse_tolerance, fit_tolerance,
3155            ) {
3156                Some((points, image)) => (points, Vec::new(), Some(image)),
3157                None => {
3158                    let (points, parameters) = mapped_pcurve_polyline(&surface, &source_coedge.pcurve, false)?;
3159                    (points, parameters, None)
3160                }
3161            };
3162            let within = |bar: f64| points.iter().all(|point| point.sub(points[0]).length() <= bar);
3163            let distance_collapsed = within(collapse_tolerance);
3164            // `BREP_OFFSET_OPEN_IMAGE_COLLAPSE` (default on, `0` restores; `check` logs
3165            // each disagreement): the distance-scaled bar is for images whose
3166            // source closes on one vertex (a pole, an apex, a fold ring). An
3167            // open source edge keeps two image vertices, which a collapse
3168            // would leave on a zero-length "degenerate" edge no weld can pair;
3169            // its image collapses only within the model floor and a 1e-4 share
3170            // of the distance. A rounded corner shelled to within 6e-4 of its
3171            // radius keeps its 8.5e-4 arc.
3172            let open_mode = crate::mode_switch!("BREP_OFFSET_OPEN_IMAGE_COLLAPSE", true);
3173            let image_collapsed = if open_mode != crate::env_read::Mode::Off
3174                && source_start != source_end
3175                && !source_edge.degenerate
3176            {
3177                let open_collapsed = within(1e-6f64.max(distance.abs() * 1e-4));
3178                if open_mode == crate::env_read::Mode::Check && open_collapsed != distance_collapsed {
3179                    eprintln!(
3180                        "OPEN_IMAGE_COLLAPSE differs: source face {face_id} edge {} distance {distance:.6e}: distance bar {collapse_tolerance:.3e} collapsed={distance_collapsed}, open rule {open_collapsed}",
3181                        source_edge.id,
3182                    );
3183                }
3184                if open_mode == crate::env_read::Mode::On { open_collapsed } else { distance_collapsed }
3185            } else {
3186                distance_collapsed
3187            };
3188            let (edge_id, forward) =
3189                if let Some((edge_id, edge_start_vertex_id, creator_forward)) =
3190                    edge_images.get(&source_edge.id)
3191                {
3192                    if source_start == source_end {
3193                        // A CLOSED source edge (a seam of a periodic face: both
3194                        // ends are the same vertex) is referenced twice by the
3195                        // same loop, once per seam side, and the two references
3196                        // traverse it in OPPOSITE senses — that is what closes
3197                        // the loop. The endpoint test below cannot see that:
3198                        // both ends map to the same vertex image, so it answers
3199                        // `true` for both references and the returning coedge
3200                        // comes back mis-oriented.
3201                        //
3202                        // Measured on a full torus (one vertex, two seam edges):
3203                        // the source records `forward: false` on the two
3204                        // returning coedges and validates clean, while the
3205                        // carrier recorded `forward: true` on both and its rim
3206                        // edge measured 12.5 — a whole part diameter — against
3207                        // its own composed pcurve image. The measured tolerance
3208                        // this slice adds is what surfaced it; no existing gate
3209                        // reaches this shape.
3210                        //
3211                        // The source coedge's own sense is the answer: the image
3212                        // edge runs along the CREATING coedge's pcurve, so a
3213                        // later reference runs with it exactly when the two
3214                        // source coedges traverse the source edge the same way.
3215                        (*edge_id, source_coedge.forward == *creator_forward)
3216                    } else {
3217                        // UNCHANGED for every open edge: the image edge's start
3218                        // vertex identifies which way this coedge runs.
3219                        (
3220                            *edge_id,
3221                            vertex_images
3222                                .get(&source_start)
3223                                .is_some_and(|ids: &Vec<u64>| ids.contains(edge_start_vertex_id)),
3224                        )
3225                    }
3226                } else {
3227                    let (curve, t0, t1) = if image_collapsed {
3228                        let curve = NurbsCurve::new(
3229                            1,
3230                            vec![0.0, 0.0, 1.0, 1.0],
3231                            vec![
3232                                Vec4::from_point(points[0], 1.0),
3233                                Vec4::from_point(points[0], 1.0),
3234                            ],
3235                        ).or_refuse(KernelStage::Refine, "new")?;
3236                        (curve, 0.0, 1.0)
3237                    } else if let Some(image) = exact_image {
3238                        image
3239                    } else {
3240                        carrier_edge_curve(
3241                            &surface,
3242                            &source_coedge.pcurve,
3243                            &points,
3244                            &parameters,
3245                            fit_tolerance,
3246                        )?
3247                    };
3248                    let start_vertex_id = claim_vertex_image(
3249                        source_start,
3250                        points[0],
3251                        vertex_split,
3252                        &mut vertex_images,
3253                        &mut vertices,
3254                        &mut next_id,
3255                    );
3256                    let end_vertex_id = claim_vertex_image(
3257                        source_end,
3258                        points[points.len() - 1],
3259                        vertex_split,
3260                        &mut vertex_images,
3261                        &mut vertices,
3262                        &mut next_id,
3263                    );
3264                    let id = next_id;
3265                    next_id += 1;
3266                    edges.push(EdgeRecord {
3267                        id,
3268                        curve,
3269                        t0,
3270                        t1,
3271                        start_vertex_id,
3272                        end_vertex_id,
3273                        // Degenerate exactly when the IMAGE collapsed. A cone
3274                        // apex maps to a real RING on an exterior offset and
3275                        // must carry a real closed edge; a real source edge
3276                        // whose image collapses to a point is a degenerate edge
3277                        // ON THE CARRIER whatever it was on the source.
3278                        //
3279                        // That second half is what the CARVE needs. The new
3280                        // boundary a carve introduces is a piece of the fold
3281                        // locus, which on the source is an ordinary curve — a
3282                        // parallel circle on a cone — and whose whole defining
3283                        // property is that the offset collapses there. Reading
3284                        // the source's flag as well left it a zero-length
3285                        // NON-degenerate closed edge, which no weld can use.
3286                        degenerate: image_collapsed,
3287                        // Image of a named source edge on the offset carrier;
3288                        // suffixed so it cannot collide with the source edge
3289                        // when both faces survive into one solid.
3290                        name: source_edge
3291                            .name
3292                            .as_ref()
3293                            .map(|name| format!("{name}_Offset")),
3294                    });
3295                    edge_images.insert(
3296                        source_edge.id,
3297                        (id, start_vertex_id, source_coedge.forward),
3298                    );
3299                    (id, true)
3300                };
3301            let id = next_id;
3302            next_id += 1;
3303            coedges.push(CoedgeRecord {
3304                id,
3305                edge_id,
3306                forward,
3307                pcurve: source_coedge.pcurve.clone(),
3308            });
3309        }
3310        let id = next_id;
3311        next_id += 1;
3312        loops.push(LoopRecord { id, coedges });
3313    }
3314    let deviation = if measure {
3315        Some(measure_carrier(
3316            &surface,
3317            &vertices,
3318            &edges,
3319            &loops,
3320            lane,
3321            surface_fit,
3322            band,
3323        )?)
3324    } else {
3325        None
3326    };
3327    Ok(OffsetFaceCarrier {
3328        vertices,
3329        edges,
3330        face: FaceRecord {
3331            id: next_id,
3332            surface,
3333            same_sense: source.same_sense,
3334            loops,
3335            name: source.name.as_ref().map(|name| format!("{name}_Offset")),
3336        },
3337        deviation,
3338        lane,
3339    })
3340}
3341
3342
3343
3344
3345