Skip to main content

brep_kernel/offset/
offset.rs

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