Skip to main content

brep_blend/blending/blend/chain/
closed.rs

1use crate::{KernelRefusal, KernelStage, OrRefuse};
2use super::*;
3
4/// Piece of a support rim assigned to one mate face.
5pub(super) struct RimPiece {
6    /// Global-parameter window of this piece.
7    pub(super) window: [f64; 2],
8    pub(super) edge_id: u64,
9}
10
11/// Blend a chain of conjugated edges with one rolling-ball blend face
12/// (Golovanov §6.9.5: all conjugated edges processed together).  A CLOSED
13/// chain (stadium rim, T-pipe saddle) welds into a periodic blend; an OPEN
14/// chain (line->arc->line capped by end faces) rolls a clamped blend that
15/// terminates in a transverse edge on each end face.
16pub fn blend_smooth_chain(
17    solid: &BrepSolid,
18    seed_edge_id: u64,
19    radius: f64,
20    chamfer: bool,
21    name: Option<&str>,
22) -> Result<BrepSolid, KernelRefusal> {
23    // One blend operation: the reports of an earlier one, never consumed, are
24    // dropped as it starts (nested calls keep this operation's).
25    let _operation = crate::blend::BlendOperation::enter();
26    if !(radius > 0.0) || !radius.is_finite() {
27        return Err(KernelRefusal::input(KernelStage::Collect, "radius", "blend: radius must be positive"));
28    }
29    let chain = collect_smooth_chain(solid, seed_edge_id)?;
30    if chain.segments.len() < 2 {
31        return Err(KernelRefusal::internal(KernelStage::Refine, "chain_single_segment", "blend: chain collapsed to a single segment"));
32    }
33    // An asymmetric chamfer's law, resolved onto the chain's sides.
34    let pairs: Vec<[u64; 2]> = chain.segments.iter().map(|segment| [segment.first.face.id, segment.second.face.id]).collect();
35    let _sides = crate::blend::setback::chain_sides(&pairs)?;
36    if chain.closed {
37        blend_closed_smooth_chain(solid, &chain.segments, radius, chamfer, name)
38    } else {
39        blend_open_smooth_chain(solid, &chain, radius, chamfer, name)
40    }
41}
42
43/// `blend_smooth_chain` restricted to CLOSED chains: an edge that is one arc
44/// of a seam-split rim (a cyl×cyl saddle) is blended as the whole rim, but an
45/// OPEN tangent chain is not walked — filleting one edge of it must not
46/// fillet the unselected edges it runs into.  Tangent propagation is a
47/// selection policy for the feature layer; the kernel caps an unselected
48/// continuation instead (`network.rs`).
49pub fn blend_smooth_chain_if_closed(
50    solid: &BrepSolid,
51    seed_edge_id: u64,
52    radius: f64,
53    chamfer: bool,
54    name: Option<&str>,
55) -> Result<BrepSolid, KernelRefusal> {
56    // One blend operation: the reports of an earlier one, never consumed, are
57    // dropped as it starts (nested calls keep this operation's).
58    let _operation = crate::blend::BlendOperation::enter();
59    if !(radius > 0.0) || !radius.is_finite() {
60        return Err(KernelRefusal::input(KernelStage::Collect, "radius", "blend: radius must be positive"));
61    }
62    let chain = collect_smooth_chain(solid, seed_edge_id)?;
63    if chain.segments.len() < 2 {
64        return Err(KernelRefusal::internal(KernelStage::Refine, "chain_single_segment", "blend: chain collapsed to a single segment"));
65    }
66    // An asymmetric chamfer's law, resolved onto the chain's sides.
67    let pairs: Vec<[u64; 2]> = chain.segments.iter().map(|segment| [segment.first.face.id, segment.second.face.id]).collect();
68    let _sides = crate::blend::setback::chain_sides(&pairs)?;
69    if !chain.closed {
70        return Err(
71            KernelRefusal::unsupported(KernelStage::Classify, "open_tangent_chain", "blend: the edge is one arc of an OPEN tangent chain; the unselected \
72             continuation is capped, not blended"),
73        );
74    }
75    blend_closed_smooth_chain(solid, &chain.segments, radius, chamfer, name)
76}
77
78// BREP lane L: begin lcount236_chain_ladder_memo_20261016
79/// A closed chain's ladder that tops out answers the same refusal for the same
80/// inputs, and a fillet selection asks it again and again: the group's cutter
81/// composition, then every drop-one subset, each blending the same collar on a
82/// solid the earlier edges did not touch there (up to four calls a case). Up to
83/// its verdict the ladder reads only the chain — every segment's edge, both
84/// mate faces (surface, sense, loops) and coedges, the signed radii — the
85/// radius, the chamfer flag, the bar and three switches, never the rest of the
86/// solid; the key is exactly those, bit for bit. Only the `chain_ladder_top`
87/// refusal is kept, and a hit returns that refusal unchanged. With
88/// `BREP_CHAIN_LADDER_SIGNED_KEY` (default on since the promotion 2026-11-05;
89/// `=0` off) the mates' loops leave the key and the segments' signed radii, the
90/// only reading of those loops the ladder makes, take their place.
91/// `BREP_CHAIN_LADDER_MEMO=0` turns the memo off; `=verify` recomputes every
92/// hit and panics unless the recomputed answer is the cached refusal, byte for
93/// byte.
94fn blend_closed_smooth_chain(
95    solid: &BrepSolid,
96    segments: &[ChainSegment<'_>],
97    radius: f64,
98    chamfer: bool,
99    name: Option<&str>,
100) -> Result<BrepSolid, KernelRefusal> {
101    let mode = std::env::var("BREP_CHAIN_LADDER_MEMO");
102    let (memo_on, verify) = match mode.as_deref() {
103        Ok("0") => (false, false),
104        Ok("verify") => (true, true),
105        _ => (true, false),
106    };
107    // An asymmetric chamfer's ladder is not the ball's: never memoized.
108    if !memo_on || crate::blend::setback::sides().is_some() {
109        return blend_closed_smooth_chain_unmemoized(solid, segments, radius, chamfer, name);
110    }
111    let bar = crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
112    // Lane F (2026-10-31, `BREP_CHAIN_LADDER_SIGNED_KEY`, default on since the
113    // promotion 2026-11-05):
114    // up to its verdict the ladder reads the mates' loops ONLY through the
115    // segments' signed radii (`signed_radii`, the march's and the dense
116    // contacts' one into-face probe, called with exactly these arguments);
117    // every other read is a carrier, a pcurve or an edge curve. Keyed on those
118    // signs instead of on the whole loops, a chain whose mates another blend of
119    // the same selection changed elsewhere asks the same ladder again and hits.
120    let signed = if chain_ladder_signed_key_on() {
121        let mut signs = Vec::with_capacity(segments.len());
122        for segment in segments {
123            match crate::blend::stations::signed_radii(
124                segment.edge,
125                segment.first.face,
126                segment.first.coedge,
127                segment.second.face,
128                segment.second.coedge,
129                radius,
130            ) {
131                Ok(pair) => signs.push(pair),
132                // The march refuses at the same call: nothing to key.
133                Err(_) => return blend_closed_smooth_chain_unmemoized(solid, segments, radius, chamfer, name),
134            }
135        }
136        Some(signs)
137    } else {
138        None
139    };
140    let key = ladder_memo_key(segments, radius, chamfer, bar, signed.as_deref());
141    let cached = LADDER_MEMO.with(|memo| memo.borrow().iter().find(|(stored, _)| *stored == key).map(|(_, refusal)| refusal.clone()));
142    crate::blend::carve::carve_trace(format_args!(
143        "blend chain ladder memo: {} for segments {:?}",
144        if cached.is_some() { "hit" } else { "miss" },
145        segments
146            .iter()
147            .map(|segment| (segment.edge.id, segment.forward, segment.first.face.id, segment.second.face.id))
148            .collect::<Vec<_>>()
149    ));
150    if let (Some(refusal), false) = (&cached, verify) {
151        crate::blend::record_count("count.chain_ladder_memo.hit", 1);
152        return Err(refusal.clone());
153    }
154    let result = blend_closed_smooth_chain_unmemoized(solid, segments, radius, chamfer, name);
155    if let Some(refusal) = cached {
156        let same = matches!(&result, Err(again) if *again == refusal && format!("{again:?}") == format!("{refusal:?}"));
157        assert!(same, "chain ladder memo mismatch: cached {refusal:?}, recomputed {:?}", result.as_ref().err());
158        crate::blend::record_count("count.chain_ladder_memo.verified", 1);
159        return result;
160    }
161    if let Err(refusal) = &result {
162        if matches!(&refusal.class, crate::RefusalClass::NonConvergence { what } if what == "chain_ladder_top") {
163            LADDER_MEMO.with(|memo| {
164                let mut memo = memo.borrow_mut();
165                if memo.len() >= LADDER_MEMO_CAPACITY {
166                    memo.remove(0);
167                }
168                memo.push((key, refusal.clone()));
169            });
170        }
171    }
172    result
173}
174
175/// Whether the ladder memo keys a chain's mates by the segments' signed radii
176/// instead of their whole loops (lane F 2026-10-31): ON unless
177/// `BREP_CHAIN_LADDER_SIGNED_KEY=0` (or `off`); promoted 2026-11-05.
178fn chain_ladder_signed_key_on() -> bool {
179    switch!("BREP_CHAIN_LADDER_SIGNED_KEY", true)
180}
181
182/// Whether the ladder memo keys a closed chain from its smallest edge id rather
183/// than from its seed (2026-11-05): ON unless `BREP_CHAIN_LADDER_ROTATION_KEY=0`
184/// (or `off`); promoted 2026-11-05.
185fn chain_ladder_rotation_key_on() -> bool {
186    switch!("BREP_CHAIN_LADDER_ROTATION_KEY", true)
187}
188
189/// How many topped-out ladders the memo keeps (oldest dropped first).
190const LADDER_MEMO_CAPACITY: usize = 32;
191
192thread_local! {
193    /// Topped-out closed-chain ladders: the bit-exact key and the refusal.
194    static LADDER_MEMO: std::cell::RefCell<Vec<(Vec<u64>, KernelRefusal)>> = const { std::cell::RefCell::new(Vec::new()) };
195}
196
197/// Every input the closed-chain ladder reads up to its verdict, as raw bits.
198fn ladder_memo_key(segments: &[ChainSegment<'_>], radius: f64, chamfer: bool, bar: f64, signed: Option<&[(f64, f64)]>) -> Vec<u64> {
199    fn curve(key: &mut Vec<u64>, curve: &NurbsCurve) {
200        key.extend([curve.degree as u64, curve.knots.len() as u64, curve.control_points.len() as u64]);
201        key.extend(curve.knots.iter().map(|knot| knot.to_bits()));
202        for point in &curve.control_points {
203            key.extend([point.x.to_bits(), point.y.to_bits(), point.z.to_bits(), point.w.to_bits()]);
204        }
205    }
206    fn face(key: &mut Vec<u64>, face: &FaceRecord, loops: bool) {
207        let surface = &face.surface;
208        key.extend([face.id, face.same_sense as u64, surface.degree_u as u64, surface.degree_v as u64]);
209        key.extend([surface.knots_u.len() as u64, surface.knots_v.len() as u64, surface.control_points.len() as u64]);
210        key.extend(surface.knots_u.iter().chain(&surface.knots_v).map(|knot| knot.to_bits()));
211        for row in &surface.control_points {
212            key.push(row.len() as u64);
213            for point in row {
214                key.extend([point.x.to_bits(), point.y.to_bits(), point.z.to_bits(), point.w.to_bits()]);
215            }
216        }
217        if !loops {
218            return;
219        }
220        key.push(face.loops.len() as u64);
221        for loop_record in &face.loops {
222            key.extend([loop_record.id, loop_record.coedges.len() as u64]);
223            for coedge in &loop_record.coedges {
224                key.extend([coedge.id, coedge.edge_id, coedge.forward as u64]);
225                curve(key, &coedge.pcurve);
226            }
227        }
228    }
229    let mut key = vec![
230        radius.to_bits(),
231        chamfer as u64,
232        bar.to_bits(),
233        crate::blend::station_refinement_on() as u64,
234        crate::blend::chain_arc_stations_on() as u64,
235        wall_verdict_on() as u64,
236        local_continue_on() as u64,
237        segments.len() as u64,
238        signed.is_some() as u64,
239    ];
240    // (2026-11-05, `BREP_CHAIN_LADDER_ROTATION_KEY`): a closed chain seeded at
241    // another of its edges is the same cycle read from a different start.
242    // Orientation and mate order are kept as read: a chain walked the other
243    // way keys differently and misses.
244    let start = if chain_ladder_rotation_key_on() {
245        key.push(1);
246        segments.iter().enumerate().min_by_key(|(_, segment)| segment.edge.id).map_or(0, |(index, _)| index)
247    } else {
248        0
249    };
250    for index in (0..segments.len()).map(|offset| (start + offset) % segments.len()) {
251        let segment = &segments[index];
252        if let Some((rho1, rho2)) = signed.and_then(|signs| signs.get(index)) {
253            key.extend([rho1.to_bits(), rho2.to_bits()]);
254        }
255        let edge = segment.edge;
256        key.extend([edge.id, edge.start_vertex_id, edge.end_vertex_id, edge.t0.to_bits(), edge.t1.to_bits(), segment.forward as u64]);
257        curve(&mut key, &edge.curve);
258        for mate in [&segment.first, &segment.second] {
259            key.extend([mate.coedge.id, mate.coedge.edge_id, mate.coedge.forward as u64, mate.loop_index as u64, mate.rho.to_bits()]);
260            curve(&mut key, &mate.coedge.pcurve);
261            face(&mut key, mate.face, signed.is_none());
262        }
263    }
264    key
265}
266// BREP lane L: end lcount236_chain_ladder_memo_20261016
267
268/// Blend a CLOSED chain of conjugated edges with one rolling-ball blend
269/// face (Golovanov §6.9.5: all conjugated edges processed together).
270///
271/// A wall whose ball-centre curve turns tighter than the ball FOLDS, and the
272/// envelope a plain march sweeps is then not the blend (`blend/fold.rs`).  It
273/// is not refused here any more where the fold is a lens the wall closes on
274/// itself: the chain is re-marched up a measured ladder of budgets and the lens
275/// is carved out along the crease (`blend/carve.rs`).  The re-march is the
276/// whole of the extra cost and only a folding wall pays it — the first march is
277/// the ordinary one, and its refusal is what asks for the second.
278fn blend_closed_smooth_chain_unmemoized(
279    solid: &BrepSolid,
280    segments: &[ChainSegment<'_>],
281    radius: f64,
282    chamfer: bool,
283    name: Option<&str>,
284) -> Result<BrepSolid, KernelRefusal> {
285    let bar = crate::blend::setback::chain_bar(solid, crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit);
286    // The plain collar climbs the same measured ladder the carve does, from the
287    // same first rung: a budget picked once is a resolution request in disguise.
288    let mut budget = ChainBudget::for_chain(segments, CHAIN_PER_SEGMENT)?;
289    // Every too-coarse rung's reading, for the refusal at the top.
290    let mut trend: Vec<(usize, f64)> = Vec::new();
291    let first = loop {
292        let per_segment = budget.rung;
293        let rung = build_closed_smooth_chain(
294            solid,
295            segments,
296            radius,
297            chamfer,
298            name,
299            &budget,
300            FoldPolicy::Refuse,
301            bar,
302        );
303        match rung {
304            Ok(Rung::TooCoarse { deviation }) => {
305                crate::blend::carve::carve_trace(format_args!(
306                    "blend chain: {} leaves the rails \
307                     {deviation:.6e} from the rolling ball, against {bar:.3e}",
308                    budget.describe()
309                ));
310                trend.push((per_segment, deviation));
311                if budget.largest() * 2 > CHAIN_CARVE_MAX_PER_SEGMENT {
312                    let (best_rung, best, listing) = ladder_trend(&trend);
313                    return Err(KernelRefusal::non_convergence(KernelStage::Refine, "chain_ladder_top", format!(
314                        "blend: the chain's ladder reached its top, {per_segment} stations per segment, \
315                         and no rung passed — its best, {best_rung} stations per segment, left this \
316                         collar's fitted rails {best:.6e} from the rolling ball's own contacts against \
317                         a bar of {bar:.3e} (rung by rung: {listing}), so there is no wall accurate \
318                         enough to build"
319                    )));
320                }
321                budget = budget.doubled();
322            }
323            // The continuation Newton of one station did not converge from its
324            // neighbour at this spacing. Only that typed station failure climbs:
325            // the next rung seeds every station from a neighbour half as far
326            // away. At the top the march's own refusal is returned verbatim.
327            Ok(Rung::StationFailed(failure)) => {
328                crate::blend::carve::carve_trace(format_args!(
329                    "blend chain: {per_segment} stations per segment: segment {} position {} \
330                     (t {:.9}) continued from position {} (t {:.9}, seed {:?}) did not converge: {}",
331                    failure.segment, failure.position, failure.t, failure.from_position,
332                    failure.from_t, failure.seed_uv, failure.error
333                ));
334                if budget.largest() * 2 > CHAIN_CARVE_MAX_PER_SEGMENT {
335                    break Err(failure.error);
336                }
337                budget = budget.doubled();
338            }
339            other => break other,
340        }
341    };
342    if let Err(error) = &first {
343        crate::blend::carve::carve_trace(format_args!(
344            "blend chain: the march at {} refused: {error}", budget.describe()
345        ));
346    }
347    match first {
348        Ok(Rung::Built(built)) => Ok(built),
349        Ok(Rung::TooCoarse { .. }) | Ok(Rung::StationFailed(_)) => {
350            Err(KernelRefusal::internal(KernelStage::Refine, "chain_ladder_rung", "blend: the chain ladder left an accuracy rung unhandled"))
351        }
352        // A fold that reaches a RAIL is not a lens: every section of that wall
353        // is singular somewhere between its contacts, so there is nothing to cut
354        // away and keep, and the ladder below would only re-march it to its top
355        // before the carve refused the same band. Its refusal names the face it
356        // cannot cross, and it is terminal as it stands (`blend/fold.rs`).
357        Err(error) if crate::blend::fold::is_rail_fold(&error) => Err(error),
358        // A CHAMFER section is a straight line and has no ball centre to read
359        // the fold locus against, so its fold stays the refusal it was.
360        Err(error) if crate::blend::is_wall_fold(&error) && !chamfer => {
361            carve_ladder(solid, segments, radius, name, bar)
362                // A CARVE THAT FAILS IS STILL A FOLD, and the fold is terminal.
363                // If the carve's own refusal did not read as one, the ladder
364                // below would answer a proven-folding centre curve with the
365                // cutter's unrelated complaint — which is the exact failure
366                // `fold.rs` was made terminal to stop. So every exit from this
367                // branch carries the fold's own prefix, with the carve's reason
368                // inside it.
369                .map_err(|carve_error| {
370                    if crate::blend::is_wall_fold(&carve_error) {
371                        carve_error
372                    } else {
373                        crate::blend::fold::wall_fold_refusal(
374                            Vec::new(),
375                            format!(
376                                "{} {} fits this edge: the wall folds, and the fold band could not \
377                                 be carved — {carve_error}",
378                                crate::blend::WALL_FOLDS,
379                                radius.abs()
380                            ),
381                        )
382                    }
383                })
384        }
385        Err(error) => Err(error),
386    }
387}
388
389/// Re-march a folding chain up a ladder of station budgets and carve at the
390/// first rung whose wall IS the rolling ball's to `bar`.
391///
392/// The budget is not chosen: a larger or a tighter fillet needs a different
393/// rung, and a number picked once from one fixture would be a resolution
394/// request in disguise. Each rung is measured by the rolling ball itself — its
395/// contacts re-solved halfway between stations, where an interpolant is worst —
396/// against the fitted rails, and the ladder stops at the first rung inside
397/// `intersection_fit`. A wall that still misses at the top is refused by name.
398fn carve_ladder(
399    solid: &BrepSolid,
400    segments: &[ChainSegment<'_>],
401    radius: f64,
402    name: Option<&str>,
403    bar: f64,
404) -> Result<BrepSolid, KernelRefusal> {
405    let mut budget = ChainBudget::for_chain(segments, CHAIN_PER_SEGMENT)?;
406    loop {
407        let per_segment = budget.rung;
408        match build_closed_smooth_chain(
409            solid,
410            segments,
411            radius,
412            false,
413            name,
414            &budget,
415            FoldPolicy::Carve,
416            bar,
417        )? {
418            Rung::Built(built) => {
419                crate::blend::carve::carve_trace(format_args!(
420                    "blend carve: {} is the first rung inside \
421                     {bar:.3e}",
422                    budget.describe()
423                ));
424                return Ok(built);
425            }
426            // The carve keeps its own contract: a station failure refuses as
427            // it did before the plain ladder learned to climb on it.
428            Rung::StationFailed(failure) => return Err(failure.error),
429            Rung::TooCoarse { deviation } => {
430                crate::blend::carve::carve_trace(format_args!(
431                    "blend carve: {} leaves the rails \
432                     {deviation:.6e} from the rolling ball, against {bar:.3e}",
433                    budget.describe()
434                ));
435                if budget.largest() * 2 > CHAIN_CARVE_MAX_PER_SEGMENT {
436                    return Err(crate::blend::fold::wall_fold_refusal(
437                        Vec::new(),
438                        format!(
439                            "{} {} fits this edge: the wall folds, and at {per_segment} stations \
440                             per segment — the top of the carve's ladder — its fitted rails are \
441                             still {deviation:.6e} from the rolling ball's own contacts against a \
442                             bar of {bar:.3e}, so there is no wall accurate enough to carve",
443                            crate::blend::WALL_FOLDS,
444                            radius.abs()
445                        ),
446                    ));
447                }
448                budget = budget.doubled();
449            }
450        }
451    }
452}
453
454/// One rung of a chain build: the finished solid, or — for a carve — the
455/// measured reason this budget is not enough.
456enum Rung {
457    Built(BrepSolid),
458    TooCoarse { deviation: f64 },
459    /// A station's continuation Newton found no root at this budget
460    /// (`march::ChainStationFailure`); a finer rung is a nearer seed.
461    StationFailed(ChainStationFailure),
462}
463
464/// The worst distance from the rolling ball's halfway contacts to the fitted
465/// rails `cr` and `cs`, each found by a closest-point Newton from the
466/// parameter the chord map assigns the midpoint.
467///
468/// THE NEWTON STAYS WHERE IT WAS SEEDED. The foot of a halfway contact is
469/// inside the station interval it was solved in, so every step is bounded by
470/// that interval's own length in the fit's parameter, clamped to the rail's
471/// domain, and taken only when it brings the rail closer. A plain Newton stops
472/// wherever the distance is stationary along the curve, which a rail that
473/// turns sharply at a chain junction offers well away from the foot. Measured
474/// on a 20 cube rounded at r = 3 with a bottom edge at r = 4 (the wall folds at
475/// the arcs' rails, so this is the ladder's reading with that refusal set
476/// aside): unguarded, every rung read the distance from the halfway contact
477/// beside a junction to the junction itself — 2.927709e-1 at 24 stations per
478/// segment against a half interval of 0.291667, halving per rung to
479/// 9.128591e-3 at 768 — and on two of the eight mirror-image edges a foot
480/// across the chain, 1.299089e1. Guarded, all eight read 6.961233e-3 at 24
481/// and 6.920006e-6 to 6.920008e-6 at 768, falling fourfold per rung as a
482/// cubic's does. A far foot can read short as well as long, which would pass
483/// a rung that misses.
484///
485/// Also returns every interval over `bar`, named by its left sample's index:
486/// what local refinement inserts a station into.
487fn rail_deviation(
488    samples: &[ChainSample],
489    cr: &NurbsCurve,
490    cs: &NurbsCurve,
491    fit_low: f64,
492    fit_range: f64,
493    budget: &ChainBudget,
494    bar: f64,
495) -> Result<(f64, Vec<usize>), KernelRefusal> {
496    // Each interval runs from a station to the NEXT one along its segment — the
497    // next grid position, a station local refinement inserted, or the
498    // segment's own end station — in the order the stations take.
499    let mut order: Vec<usize> = (0..samples.len())
500        .filter(|&index| (0..=budget.count(samples[index].segment) as isize).contains(&samples[index].position))
501        .collect();
502    order.sort_by(|&a, &b| {
503        let (a, b) = (&samples[a], &samples[b]);
504        a.segment.cmp(&b.segment).then(a.position.cmp(&b.position)).then(a.offset.total_cmp(&b.offset))
505    });
506    let next_of: std::collections::HashMap<usize, f64> = order
507        .windows(2)
508        .filter(|pair| samples[pair[0]].segment == samples[pair[1]].segment)
509        .map(|pair| (pair[0], samples[pair[1]].parameter))
510        .collect();
511    let mut failing = Vec::new();
512    let closest = closest_on_rail;
513    let mut worst: f64 = 0.0;
514    // Each segment's worst halfway contact, for `BREP_BLEND_CARVE_TRACE=1`: where
515    // along the chain a rung misses is what tells a junction from a bend.
516    let mut per_segment_worst: Vec<(f64, isize, f64, f64, Vec3, Vec3)> = Vec::new();
517    for &index in &order {
518        let sample = &samples[index];
519        let Some([p1, p2]) = sample.midpoint else {
520            continue;
521        };
522        let Some(&next) = next_of.get(&index) else {
523            continue;
524        };
525        let global = (0.5 * (sample.parameter + next)).rem_euclid(1.0);
526        let seed = (global - fit_low) / fit_range;
527        let reach = (next - sample.parameter).abs() / fit_range;
528        let (miss1, miss2) = (closest(cr, p1, seed, reach)?, closest(cs, p2, seed, reach)?);
529        worst = worst.max(miss1).max(miss2);
530        if miss1.max(miss2) > bar {
531            failing.push(index);
532        }
533        if per_segment_worst.len() <= sample.segment {
534            per_segment_worst.resize(
535                sample.segment + 1,
536                (0.0, 0, 0.0, 0.0, Vec3::default(), Vec3::default()),
537            );
538        }
539        if miss1.max(miss2) >= per_segment_worst[sample.segment].0 {
540            per_segment_worst[sample.segment] = (miss1.max(miss2), sample.position, miss1, miss2, p1, p2);
541        }
542    }
543    for (segment, (miss, position, miss1, miss2, p1, p2)) in per_segment_worst.iter().enumerate() {
544        crate::blend::carve::carve_trace(format_args!(
545            "  rail miss segment {segment}: worst {miss:.6e} after station {position} \
546             (cr {miss1:.6e} at ({:.6}, {:.6}, {:.6}), cs {miss2:.6e} at ({:.6}, {:.6}, {:.6}))",
547            p1.x, p1.y, p1.z, p2.x, p2.y, p2.z
548        ));
549    }
550    Ok((worst, failing))
551}
552
553/// Most dense INTERVALS (4097 samples) a closed chain's support-piece track may
554/// hold: the existing ceiling its uniform track is built under, and the one
555/// local refinement of that track stays within — not a sample count.
556const PIECE_TRACK_CEILING: usize = 4096;
557
558/// Distance from `target` to a fitted rail, by a Newton that stays where it is
559/// seeded (`rail_deviation`'s reading, shared with the dense diagnostic).
560fn closest_on_rail(curve: &NurbsCurve, target: Vec3, seed: f64, reach: f64) -> Result<f64, KernelRefusal> {
561    let [low, high] = curve.domain().or_refuse(KernelStage::Refine, "domain")?;
562    let (u, _) = crate::projection::curve_foot_newton(curve, target, seed, [low, high],
563        crate::projection::CurveFootPolicy {
564            domain: crate::projection::FootDomain::Clamp,
565            iterations: 40,
566            slope_guard: -1.0, // nonpositive curvature uses the downhill step
567            step_limit: reach,
568            parameter_tolerance: 1e-15,
569            mode: crate::projection::FootMode::Backtracked,
570        }).or_refuse(KernelStage::Refine, "curve_foot_newton")?;
571    Ok(curve.derivatives_extended(u, 0).or_refuse(KernelStage::Refine, "derivatives_extended")?[0].sub(target).length())
572}
573
574/// Points of every interval the LOCAL-INSERTION path judges a chain rung's
575/// rails on: j/16, j = 1..15 (the halfway point among them).
576pub(super) const LOCAL_RAIL_STENCIL: usize = 16;
577
578/// One dense contact pair's miss: each rail's raw reading is checked BEFORE
579/// they are joined (`f64::max` alone drops a NaN on either side); `None` when
580/// either is unreadable.
581fn rail_pair_miss(cr_miss: f64, cs_miss: f64) -> Option<f64> {
582    (cr_miss.is_finite() && cs_miss.is_finite()).then(|| cr_miss.max(cs_miss))
583}
584
585/// Each solved dense contact's distance to the fitted rails, read with the same
586/// closest-point Newton and seeds `rail_deviation` uses, keyed by the
587/// interval's left sample: the readable misses, and separately every interval
588/// with an unreadable reading on either rail (a non-finite distance, or a foot
589/// that could not be evaluated).
590#[allow(clippy::too_many_arguments)]
591pub(super) fn dense_rail_misses(
592    contacts: &crate::blend::chain::DenseContacts,
593    samples: &[ChainSample],
594    cr: &NurbsCurve,
595    cs: &NurbsCurve,
596    low: f64,
597    range: f64,
598    wrap: bool,
599) -> Result<(Vec<(usize, f64)>, Vec<usize>), KernelRefusal> {
600    let mut readable = Vec::with_capacity(contacts.solved.len());
601    let mut unreadable = Vec::new();
602    for (left, next, fraction, p1, p2) in &contacts.solved {
603        let (from, to) = (samples[*left].parameter, samples[*next].parameter);
604        // A closed chain's chord parameter wraps with period 1; an OPEN
605        // chain's runs straight through its ends (its last station's may
606        // overshoot 1, and wrapping it would read the far end).
607        let global = from + fraction * (to - from);
608        let global = if wrap { global.rem_euclid(1.0) } else { global };
609        let seed = (global - low) / range;
610        let reach = (to - from).abs() / range;
611        // A closest foot that cannot be evaluated is an unreadable reading of
612        // this interval, not a refusal of the rung.
613        let cr_miss = closest_on_rail(cr, *p1, seed, reach).unwrap_or(f64::NAN);
614        let cs_miss = closest_on_rail(cs, *p2, seed, reach).unwrap_or(f64::NAN);
615        match rail_pair_miss(cr_miss, cs_miss) {
616            Some(miss) => readable.push((*left, miss)),
617            None => unreadable.push(*left),
618        }
619    }
620    Ok((readable, unreadable))
621}
622
623/// The local-insertion path's rail verdict: the halfway reading joined with the
624/// dense stencil's, FAIL-CLOSED — an interval with a dense contact over `bar`,
625/// an unreadable distance, or a contact that was not read (unsolved, or
626/// unreadable on either rail), fails; the worst is the largest readable
627/// distance. Intervals are named by their left sample.
628pub(super) fn combine_rail_verdict(
629    halfway: (f64, Vec<usize>),
630    dense: &[(usize, f64)],
631    unsolved: &[usize],
632    bar: f64,
633) -> (f64, Vec<usize>) {
634    let (mut worst, mut failing) = halfway;
635    for &(left, miss) in dense {
636        if !miss.is_finite() {
637            failing.push(left);
638            continue;
639        }
640        if miss > bar {
641            failing.push(left);
642        }
643        worst = worst.max(miss);
644    }
645    failing.extend_from_slice(unsolved);
646    failing.sort_unstable();
647    failing.dedup();
648    (worst, failing)
649}
650
651/// Whether the construction request runs on an accepted plain fillet rung:
652/// always, outside the controls that turn it off on their own thread
653/// (`MODEL_REQUEST_OFF`) or that turn the wall verdict off.
654/// The construction request's round limit: the existing local-refinement
655/// budget, outside the control that sets it to zero on its own thread to
656/// force the typed unmet report.
657pub(super) fn model_rounds_limit() -> usize {
658    REFINE_ROUNDS
659}
660
661pub(super) fn model_request_on() -> bool {
662    wall_verdict_on()
663}
664
665
666/// Whether the fillet wall verdict runs: always, outside the mutation control
667/// that turns it off on its own thread (`WALL_VERDICT_OFF`).
668pub(super) fn wall_verdict_on() -> bool {
669    true
670}
671
672
673
674
675
676/// Section-angle probes across a fillet wall, as fractions of its `v` span:
677/// k/8 for k = 1..7, between (never on) the rails the rail verdict reads.
678pub(super) const WALL_SECTION_PROBES: usize = 8;
679
680/// How far `p` stands from the rolling ball's sweep, read at p's OWN
681/// characteristic: the stationary point of |p − C(s)|, C the cubic through
682/// four consecutive exact ball centres of `nodes` around node `j` (`nodes`
683/// uniform in fraction across one interval, its ends the interval's own
684/// stations), searched within one node of `j`, minus `radius`.
685///
686/// The cubic is an APPROXIMATION of the centre curve, not the exact sweep:
687/// its error grows with the node spacing and the spine's higher derivatives,
688/// and [`wall_probe_reading`] estimates it by a second, overlapping stencil.
689///
690/// A STATIONARY point, not the nearest centre: past a fold's focal point an
691/// envelope point is a MAXIMUM of its distance to the spine, and a global
692/// nearest centre would read a carved wall's lens as inside another ball. A
693/// centre at the probe's own chain parameter is not used either: the wall's
694/// `u` and the stencil's edge parameter name the same section only to first
695/// order, and a spine offset ℓ adds √(ρ² + ℓ²) − ρ to the reading.
696///
697/// `None` — unreadable, which fails its interval — for a non-finite input,
698/// fewer than four nodes, a probe at an interval end, or a solve that leaves
699/// its window or does not converge.
700pub fn sweep_residual(p: Vec3, nodes: &[Vec3], j: usize, radius: f64) -> Option<f64> {
701    let j = locate_foot(p, nodes, j, radius)?;
702    sweep_residual_on(p, nodes, (j - 1).min(nodes.len() - 4), j, radius)
703}
704
705/// How many nodes the stencil may follow a probe's foot away from the probe's
706/// own node.
707const FOOT_TRAVEL: usize = 4;
708
709/// The node whose stencil holds `p`'s stationary point, starting from node
710/// `j`: the probe's wall `u` and the centres' edge parameter name the same
711/// section only to first order, so the foot can sit more than the one-node
712/// window from `j` (the 15- and 20-degree rows' feet stood up to 1.5 nodes,
713/// one 3.3, from it, every decline there a window exit).
714/// A solve that leaves its window moves the stencil to the node nearest
715/// where it left, at most [`FOOT_TRAVEL`] nodes from `j` and never back to a
716/// node already tried; `None` when the foot is not found that way (or a
717/// solve is unreadable), which fails its interval as before.
718fn locate_foot(p: Vec3, nodes: &[Vec3], j: usize, radius: f64) -> Option<usize> {
719    locate_foot_read(p, nodes, j, radius).map(|(node, _)| node)
720}
721
722/// Keep the converged stencil's distance with its node. The caller can use
723/// this exact reading instead of solving the same stencil a second time.
724fn locate_foot_read(p: Vec3, nodes: &[Vec3], j: usize, radius: f64) -> Option<(usize, f64)> {
725    locate_foot_read_prepared(p, nodes, j, radius, None)
726}
727
728fn locate_foot_read_prepared(p: Vec3, nodes: &[Vec3], j: usize, radius: f64, prepared: Option<&StencilPreparation>) -> Option<(usize, f64)> {
729    let n = nodes.len();
730    if n < 4 || j == 0 || j + 1 >= n {
731        return None;
732    }
733    let mut tried: Vec<usize> = Vec::new();
734    let mut at = j;
735    loop {
736        let base = (at - 1).min(n - 4);
737        match stencil_solve_prepared(p, nodes, base, at, radius, prepared) {
738            Solve::Read(distance) => return Some((at, distance)),
739            Solve::Unread => return None,
740            Solve::Window(s) => {
741                tried.push(at);
742                let next = (base as f64 + s).round();
743                let next = if next.is_finite() { next.clamp(1.0, (n - 2) as f64) as usize } else { at };
744                if tried.contains(&next) || next.abs_diff(j) > FOOT_TRAVEL {
745                    wall_decline(|| format!(
746                        "foot search from node {j} of {n}: tried {tried:?}, next {next} ({})",
747                        if tried.contains(&next) { "already tried" } else { "beyond FOOT_TRAVEL" }
748                    ));
749                    return None;
750                }
751                at = next;
752            }
753        }
754    }
755}
756
757/// [`sweep_residual`] on the cubic through `nodes[base..base + 4]`, the
758/// stationary point searched from node `j` within one node of it.
759fn sweep_residual_on(p: Vec3, nodes: &[Vec3], base: usize, j: usize, radius: f64) -> Option<f64> {
760    match stencil_solve(p, nodes, base, j, radius) {
761        Solve::Read(distance) => Some(distance),
762        Solve::Window(_) | Solve::Unread => None,
763    }
764}
765
766/// One stencil's solve: the distance read, or where (in node units from
767/// `base`) the search left its one-node window, or unreadable.
768enum Solve {
769    Read(f64),
770    Window(f64),
771    Unread,
772}
773
774thread_local! {
775    /// When Some, every decline inside the declared wall reader appends WHY
776    /// (innermost first): set and taken by `declared_wall_probe_why` only, so
777    /// every other caller pays one thread-local read per decline and the
778    /// reader's arithmetic and outcomes are the same either way.
779    static WALL_DECLINES: std::cell::RefCell<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
780}
781
782fn wall_decline(reason: impl FnOnce() -> String) {
783    WALL_DECLINES.with(|log| {
784        if let Some(lines) = log.borrow_mut().as_mut() {
785            lines.push(reason());
786        }
787    });
788}
789
790/// [`declared_wall_probe`] with, when it declines, the chain of declines
791/// that made it (innermost first): which tier (fine / coarse), which
792/// stencil, and inside the solver the exit (unreadable input, a vanishing
793/// slope, a window exit with the overshot `s`, its offset from the window and
794/// whether the solver's OWN stationarity predicate already held at the
795/// overshot point, a stall, a non-finite distance) or the foot search's
796/// tried nodes. Exactly the same arithmetic as `declared_wall_probe`.
797pub fn declared_wall_probe_why(p: Vec3, fine: &[Vec3], jf: usize, radius: f64) -> Result<(f64, f64), String> {
798    let previous = WALL_DECLINES.with(|log| log.replace(Some(Vec::new())));
799    let read = declared_wall_probe(p, fine, jf, radius);
800    let lines = WALL_DECLINES.with(|log| log.replace(previous)).unwrap_or_default();
801    read.ok_or_else(|| if lines.is_empty() { "declined (no inner cause recorded)".to_string() } else { lines.join(" <- ") })
802}
803
804fn stencil_solve(p: Vec3, nodes: &[Vec3], base: usize, j: usize, radius: f64) -> Solve {
805    stencil_solve_prepared(p, nodes, base, j, radius, None)
806}
807
808fn stencil_solve_prepared(p: Vec3, nodes: &[Vec3], base: usize, j: usize, radius: f64, prepared: Option<&StencilPreparation>) -> Solve {
809    let finite = |v: Vec3| v.x.is_finite() && v.y.is_finite() && v.z.is_finite();
810    let n = nodes.len();
811    if n < 4 || j == 0 || j + 1 >= n || base + 4 > n || !radius.is_finite() || !finite(p) || !prepared.map_or_else(|| wall_nodes_finite(nodes), |cache| cache.finite) {
812        wall_decline(|| format!("stencil {n} nodes base {base} j {j}: unreadable input"));
813        return Solve::Unread;
814    }
815    let [p0, d1, d2, d3] = prepared.map_or_else(|| wall_coefficients(nodes, base), |cache| cache.coefficients(nodes, base));
816    let curve = |s: f64| -> (Vec3, Vec3, Vec3) {
817        let c = p0.add(d1.scale(s)).add(d2.scale(s * (s - 1.0))).add(d3.scale(s * (s - 1.0) * (s - 2.0)));
818        let c1 = d1.add(d2.scale(2.0 * s - 1.0)).add(d3.scale(3.0 * s * s - 6.0 * s + 2.0));
819        let c2 = d2.scale(2.0).add(d3.scale(6.0 * s - 6.0));
820        (c, c1, c2)
821    };
822    let start = j as f64 - base as f64;
823    let initial = prepared.and_then(|cache| cache.start(base, j, &curve));
824    let point_length = p.length();
825    let mut s = start;
826    let mut converged = false;
827    let mut converged_point = None;
828    for iteration in 0..50 {
829        let state = if iteration == 0 { initial.unwrap_or_else(|| WallStart::new(curve(s))) }
830            else { WallStart::new(curve(s)) };
831        let (c, c1, c2) = state.curve;
832        let w = c.sub(p);
833        let (g, slope) = (w.dot(c1), state.tangent_squared + w.dot(c2));
834        if !(g.is_finite() && slope.is_finite()) || slope == 0.0 {
835            wall_decline(|| format!("stencil {n} nodes base {base} j {j}: slope {slope:e} g {g:e} at s {s}"));
836            return Solve::Unread;
837        }
838        // Converged at THIS s once the stationarity condition holds to its own
839        // rounding: g = (C − p)·C′ carries an absolute error of a few
840        // ε·(|p| + |C|)·|C′|, so at a node spacing of 1e-4 the Newton step
841        // cannot fall below ~1e-11 node units and the relative step test
842        // alone never fires — a line-for-line model of this reader read 87 %
843        // to 97 % of the NX and skew walls' fine-stencil probes unreadable
844        // that way (its Newton run past the stop read |g| / (ε·(|p| + |C|)·|C′|)
845        // at most 0.91 there; 16 keeps a margin). Tested before the step, so
846        // the point read is the point whose stationarity was checked; its
847        // distance is off the true stationary one by about
848        // ½·|g|·δs/|C − p| ≤ 8ε·(|p| + |C|)·|C′|/ρ for δs within the
849        // one-node window, far below any bar.
850        let stationary = g.abs() <= 16.0 * f64::EPSILON * (point_length + state.point_length) * state.tangent_length;
851        if stationary {
852            converged = true;
853            converged_point = Some(c);
854            break;
855        }
856        let step = g / slope;
857        let before = s;
858        s -= step;
859        if !((s - start).abs() <= 1.0) {
860            wall_decline(|| {
861                // The solver's own stationarity predicate, read at the
862                // overshot point (diagnostic only: nothing decides on it).
863                let (c, c1, _) = curve(s);
864                let g_after = c.sub(p).dot(c1);
865                let stationary_after = g_after.abs() <= 16.0 * f64::EPSILON * (p.length() + c.length()) * c1.length();
866                format!(
867                    "stencil {n} nodes base {base} j {j}: window exit s {before} -> {s} (start {start}, |s - start| - 1 = {:e}), \
868                     g {g:e} -> {g_after:e}, stationary at the overshot s: {stationary_after}",
869                    (s - start).abs() - 1.0
870                )
871            });
872            return if s.is_finite() { Solve::Window(s) } else { Solve::Unread };
873        }
874        if step.abs() <= 1e-14 * (1.0 + s.abs()) {
875            converged = true;
876            break;
877        }
878    }
879    if !converged {
880        wall_decline(|| format!("stencil {n} nodes base {base} j {j}: no convergence in 50 steps, s {s}"));
881        return Solve::Unread;
882    }
883    let distance = converged_point.unwrap_or_else(|| curve(s).0).sub(p).length() - radius;
884    if distance.is_finite() {
885        Solve::Read(distance)
886    } else {
887        wall_decline(|| format!("stencil {n} nodes base {base} j {j}: non-finite distance at s {s}"));
888        Solve::Unread
889    }
890}
891
892/// One wall probe read on TWO overlapping four-centre stencils around node
893/// `j` (the one [`sweep_residual`] uses and its neighbour): `(worst, spread)`
894/// — the larger magnitude, which keeps ONE stencil's under-read from passing,
895/// and how far apart the two readings are. Both are PROXY readings: when both
896/// stencils under-read alike (a symmetric node set about a foot near the
897/// focal distance) the larger still under-reads and the spread reads zero,
898/// so neither number is an error bound. `None` when either stencil is
899/// unreadable.
900pub fn wall_probe_reading(p: Vec3, nodes: &[Vec3], j: usize, radius: f64) -> Option<(f64, f64)> {
901    let n = nodes.len();
902    if n < 5 || j == 0 || j + 1 >= n {
903        return None;
904    }
905    let j = locate_foot(p, nodes, j, radius)?;
906    let first = (j - 1).min(n - 4);
907    let second = if j >= 2 { (j - 2).min(n - 4) } else { j.min(n - 4) };
908    let second = if second == first { if first >= 1 { first - 1 } else { first + 1 } } else { second };
909    let a = sweep_residual_on(p, nodes, first, j, radius)?;
910    let b = sweep_residual_on(p, nodes, second, j, radius)?;
911    Some((a.abs().max(b.abs()), (a - b).abs()))
912}
913
914// The DECLARED wall reading at one probe, the one rule both wall tiers
915// decide on: `(reading, uncertainty)`, declared = reading + uncertainty.
916// `fine` are the interval's centres at twice the probe density, `jf` the
917// probe's (even) node among them; the coarse set is every other node. The
918// reading is the larger fine two-stencil magnitude; the uncertainty is the
919// larger of the fine stencils' spread and how far the fine reading moved
920// from the coarse one — the proxy's error estimated from its own change with
921// node density, which two stencils agreeing at one density cannot show (two
922// symmetric stencils that both under-read read a spread of zero). An
923// ESTIMATE, not a bound: a proxy whose error does not shrink with density
924// would still hide. `None` when any reading is unreadable.
925
926fn wall_solve_reuse_on() -> bool {
927    switch!(live "BREP_WALL_SOLVE_REUSE", true)
928}
929
930pub fn declared_wall_probe(p: Vec3, fine: &[Vec3], jf: usize, radius: f64) -> Option<(f64, f64)> {
931    declared_wall_probe_with(p, fine, jf, radius, wall_solve_reuse_on())
932}
933
934fn declared_wall_probe_with(p: Vec3, fine: &[Vec3], jf: usize, radius: f64, reuse: bool) -> Option<(f64, f64)> {
935    declared_wall_probe_prepared(p, fine, jf, radius, reuse, None)
936}
937
938fn declared_wall_probe_prepared(p: Vec3, fine: &[Vec3], jf: usize, radius: f64, reuse: bool, prepared: Option<&PreparedWall<'_>>) -> Option<(f64, f64)> {
939    if jf % 2 != 0 || fine.len() < 9 || fine.len() % 2 == 0 {
940        wall_decline(|| format!("declared reader: node {jf} of {} not an even node of an odd fine set", fine.len()));
941        return None;
942    }
943    let (reading, spread, at_fine) = if reuse {
944        let read = (|| {
945            let n = fine.len();
946            let (j, a) = locate_foot_read_prepared(p, fine, jf, radius, prepared.map(|c| &c.fine_stencils))?;
947            let first = (j - 1).min(n - 4);
948            let second = if j >= 2 { (j - 2).min(n - 4) } else { j.min(n - 4) };
949            let second = if second == first { if first >= 1 { first - 1 } else { first + 1 } } else { second };
950            let b = match stencil_solve_prepared(p, fine, second, j, radius, prepared.map(|c| &c.fine_stencils)) {
951                Solve::Read(distance) => distance,
952                _ => return None,
953            };
954            Some((a.abs().max(b.abs()), (a - b).abs(), a))
955        })();
956        let Some(read) = read else {
957            wall_decline(|| format!("FINE two-stencil reading at node {jf} of {}", fine.len()));
958            return None;
959        };
960        read
961    } else {
962        let Some((reading, spread)) = wall_probe_reading(p, fine, jf, radius) else {
963            wall_decline(|| format!("FINE two-stencil reading at node {jf} of {}", fine.len()));
964            return None;
965        };
966        let Some(at_fine) = sweep_residual(p, fine, jf, radius) else {
967            wall_decline(|| format!("FINE sweep at node {jf} of {}", fine.len()));
968            return None;
969        };
970        (reading, spread, at_fine)
971    };
972    let coarse_owned;
973    let coarse = match prepared {
974        Some(cache) => cache.coarse.as_slice(),
975        None => { coarse_owned = wall_coarse(fine); &coarse_owned }
976    };
977    let at_coarse = if reuse {
978        locate_foot_read_prepared(p, coarse, jf / 2, radius, prepared.map(|c| &c.coarse_stencils)).map(|(_, distance)| distance)
979    } else {
980        sweep_residual(p, coarse, jf / 2, radius)
981    };
982    let Some(at_coarse) = at_coarse else {
983        wall_decline(|| format!("COARSE sweep at node {} of {}", jf / 2, coarse.len()));
984        return None;
985    };
986    let uncertainty = spread.max((at_fine - at_coarse).abs());
987    uncertainty.is_finite().then_some((reading, uncertainty))
988}
989
990/// The even fine node whose position along the CENTRE PATH (cumulative
991/// chord of `fine`) is nearest `fraction` of it, inside 2..=n-3; `None` when
992/// the path has no finite positive length.
993///
994/// A wall probe sits at a fraction of its interval in the WALL's parameter,
995/// which is chord-like; the exact centres sit at uniform fractions of the
996/// edge's NATIVE parameter. On a regular edge the two agree to first order and
997/// the probe's foot lies within a node or two of its own node. At a
998/// STATIONARY section (the edge's derivative vanishes there) the centre moves
999/// like t^2 in the native parameter, so a probe at chord fraction f has its foot
1000/// near native fraction sqrt(f): the probe at node 2 of 32 (f = 1/16) has its
1001/// foot near node 8, past `FOOT_TRAVEL`, and the reader declines though the
1002/// centre locus is perfectly regular there (zero_tangent_sites' stationary
1003/// stadium and tombstone rims refused that way with every reading under the
1004/// bar).
1005pub fn centre_path_node(fine: &[Vec3], fraction: f64) -> Option<usize> {
1006    let n = fine.len();
1007    if n < 7 || !(fraction.is_finite()) {
1008        return None;
1009    }
1010    let mut cumulative = Vec::with_capacity(n);
1011    cumulative.push(0.0_f64);
1012    for pair in fine.windows(2) {
1013        let step = pair[1].sub(pair[0]).length();
1014        cumulative.push(cumulative.last().copied().unwrap_or(0.0) + step);
1015    }
1016    let total = *cumulative.last()?;
1017    if !(total.is_finite() && total > 0.0) {
1018        return None;
1019    }
1020    let target = fraction.clamp(0.0, 1.0) * total;
1021    let nearest = (0..n).min_by(|&a, &b| (cumulative[a] - target).abs().total_cmp(&(cumulative[b] - target).abs()))?;
1022    let even = 2 * ((nearest as f64 / 2.0).round() as usize);
1023    Some(even.clamp(2, (n - 3) & !1))
1024}
1025
1026/// [`declared_wall_probe_why`] from the probe's own node `jf`; when that
1027/// declines, once more from the node the probe's `fraction` reaches along the
1028/// centre path ([`centre_path_node`]), when that is another node. The same
1029/// reader, bars and fail-closed rule decide; a probe it still cannot read is
1030/// unread (both declines named). A probe the first read reads is read exactly
1031/// as before.
1032pub fn declared_wall_probe_located_why(p: Vec3, fine: &[Vec3], jf: usize, fraction: f64, radius: f64) -> Result<(f64, f64), String> {
1033    let first = match declared_wall_probe_why(p, fine, jf, radius) {
1034        Ok(read) => return Ok(read),
1035        Err(why) => why,
1036    };
1037    match centre_path_node(fine, fraction) {
1038        Some(located) if located != jf => declared_wall_probe_why(p, fine, located, radius)
1039            .map_err(|again| format!("{first} -- and from centre-path node {located}: {again}")),
1040        _ => Err(first),
1041    }
1042}
1043
1044/// [`declared_wall_probe_located_why`] as an `Option`.
1045pub fn declared_wall_probe_located(p: Vec3, fine: &[Vec3], jf: usize, fraction: f64, radius: f64) -> Option<(f64, f64)> {
1046    match declared_wall_probe(p, fine, jf, radius) {
1047        Some(read) => Some(read),
1048        None => match centre_path_node(fine, fraction) {
1049            Some(located) if located != jf => declared_wall_probe(p, fine, located, radius),
1050            _ => None,
1051        },
1052    }
1053}
1054
1055/// [`declared_wall_probe_why`] on centres at NON-UNIFORM native abscissae
1056/// `ts` (one per node, strictly increasing): the same two-tier rule, the
1057/// same two overlapping four-centre stencils, the same foot search
1058/// (`FOOT_TRAVEL`), the same 16·ε stationarity predicate and the same
1059/// window (one node either side of the start node), with each cubic the
1060/// Newton interpolant on the nodes' OWN abscissae instead of the implicit
1061/// 0, 1, 2, 3. For a junction of two intervals of unequal native width (local
1062/// insertions make them so): the uniform reader would place the two halves'
1063/// nodes at one spacing and distort the centre locus. The coarse tier is
1064/// every other node at every other abscissa. A caller whose abscissae are
1065/// uniform uses the uniform reader, bit for bit.
1066pub fn declared_wall_probe_at_why(p: Vec3, fine: &[Vec3], ts: &[f64], jf: usize, radius: f64) -> Result<(f64, f64), String> {
1067    if jf % 2 != 0
1068        || fine.len() < 9
1069        || fine.len() % 2 == 0
1070        || ts.len() != fine.len()
1071        || !ts.iter().all(|t| t.is_finite())
1072        || !ts.windows(2).all(|pair| pair[1] > pair[0])
1073    {
1074        return Err(format!("native-abscissa reader: node {jf} of {} with {} finite, strictly increasing abscissae required", fine.len(), ts.len()));
1075    }
1076    let previous = WALL_DECLINES.with(|log| log.replace(Some(Vec::new())));
1077    let read = (|| -> Option<(f64, f64)> {
1078        let (reading, spread) = wall_probe_reading_at(p, fine, ts, jf, radius).or_else(|| {
1079            wall_decline(|| format!("FINE two-stencil reading (native abscissae) at node {jf} of {}", fine.len()));
1080            None
1081        })?;
1082        let at_fine = sweep_residual_at(p, fine, ts, jf, radius).or_else(|| {
1083            wall_decline(|| format!("FINE sweep (native abscissae) at node {jf} of {}", fine.len()));
1084            None
1085        })?;
1086        let coarse: Vec<Vec3> = fine.iter().step_by(2).copied().collect();
1087        let coarse_ts: Vec<f64> = ts.iter().step_by(2).copied().collect();
1088        let at_coarse = sweep_residual_at(p, &coarse, &coarse_ts, jf / 2, radius).or_else(|| {
1089            wall_decline(|| format!("COARSE sweep (native abscissae) at node {} of {}", jf / 2, coarse.len()));
1090            None
1091        })?;
1092        let uncertainty = spread.max((at_fine - at_coarse).abs());
1093        uncertainty.is_finite().then_some((reading, uncertainty))
1094    })();
1095    let lines = WALL_DECLINES.with(|log| log.replace(previous)).unwrap_or_default();
1096    read.ok_or_else(|| if lines.is_empty() { "declined (no inner cause recorded)".to_string() } else { lines.join(" <- ") })
1097}
1098
1099fn wall_probe_reading_at(p: Vec3, nodes: &[Vec3], ts: &[f64], j: usize, radius: f64) -> Option<(f64, f64)> {
1100    let n = nodes.len();
1101    if n < 5 || j == 0 || j + 1 >= n {
1102        return None;
1103    }
1104    let j = locate_foot_at(p, nodes, ts, j, radius)?;
1105    let first = (j - 1).min(n - 4);
1106    let second = if j >= 2 { (j - 2).min(n - 4) } else { j.min(n - 4) };
1107    let second = if second == first { if first >= 1 { first - 1 } else { first + 1 } } else { second };
1108    let a = match stencil_solve_at(p, nodes, ts, first, j, radius) { Solve::Read(distance) => distance, _ => return None };
1109    let b = match stencil_solve_at(p, nodes, ts, second, j, radius) { Solve::Read(distance) => distance, _ => return None };
1110    Some((a.abs().max(b.abs()), (a - b).abs()))
1111}
1112
1113fn sweep_residual_at(p: Vec3, nodes: &[Vec3], ts: &[f64], j: usize, radius: f64) -> Option<f64> {
1114    let j = locate_foot_at(p, nodes, ts, j, radius)?;
1115    match stencil_solve_at(p, nodes, ts, (j - 1).min(nodes.len() - 4), j, radius) {
1116        Solve::Read(distance) => Some(distance),
1117        Solve::Window(_) | Solve::Unread => None,
1118    }
1119}
1120
1121/// [`locate_foot`] on native abscissae: a window exit moves the stencil to
1122/// the node whose abscissa is nearest the exit, within `FOOT_TRAVEL` nodes
1123/// and never back to a node already tried.
1124fn locate_foot_at(p: Vec3, nodes: &[Vec3], ts: &[f64], j: usize, radius: f64) -> Option<usize> {
1125    let n = nodes.len();
1126    if n < 4 || j == 0 || j + 1 >= n {
1127        return None;
1128    }
1129    let mut tried: Vec<usize> = Vec::new();
1130    let mut at = j;
1131    loop {
1132        let base = (at - 1).min(n - 4);
1133        match stencil_solve_at(p, nodes, ts, base, at, radius) {
1134            Solve::Read(_) => return Some(at),
1135            Solve::Unread => return None,
1136            Solve::Window(t) => {
1137                tried.push(at);
1138                let nearest = (0..n).min_by(|&a, &b| (ts[a] - t).abs().total_cmp(&(ts[b] - t).abs())).unwrap_or(at);
1139                let next = if t.is_finite() { nearest.clamp(1, n - 2) } else { at };
1140                if tried.contains(&next) || next.abs_diff(j) > FOOT_TRAVEL {
1141                    wall_decline(|| format!(
1142                        "foot search (native abscissae) from node {j} of {n}: tried {tried:?}, next {next} ({})",
1143                        if tried.contains(&next) { "already tried" } else { "beyond FOOT_TRAVEL" }
1144                    ));
1145                    return None;
1146                }
1147                at = next;
1148            }
1149        }
1150    }
1151}
1152
1153/// [`stencil_solve`] on the four nodes `base..base + 4` at their native
1154/// abscissae: the Newton (divided-difference) cubic in `t`, searched from
1155/// node `j`'s abscissa within one node either side; `Window` carries the
1156/// abscissa it left at.
1157fn stencil_solve_at(p: Vec3, nodes: &[Vec3], ts: &[f64], base: usize, j: usize, radius: f64) -> Solve {
1158    let finite = |v: Vec3| v.x.is_finite() && v.y.is_finite() && v.z.is_finite();
1159    let n = nodes.len();
1160    if n < 4 || j == 0 || j + 1 >= n || base + 4 > n || ts.len() != n || !radius.is_finite() || !finite(p) || !nodes.iter().all(|&c| finite(c)) {
1161        wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: unreadable input"));
1162        return Solve::Unread;
1163    }
1164    let [p0, p1, p2, p3] = [nodes[base], nodes[base + 1], nodes[base + 2], nodes[base + 3]];
1165    let [t0, t1, t2, t3] = [ts[base], ts[base + 1], ts[base + 2], ts[base + 3]];
1166    let d1 = p1.sub(p0).scale(1.0 / (t1 - t0));
1167    let d12 = p2.sub(p1).scale(1.0 / (t2 - t1));
1168    let d23 = p3.sub(p2).scale(1.0 / (t3 - t2));
1169    let d2 = d12.sub(d1).scale(1.0 / (t2 - t0));
1170    let d123 = d23.sub(d12).scale(1.0 / (t3 - t1));
1171    let d3 = d123.sub(d2).scale(1.0 / (t3 - t0));
1172    let curve = |t: f64| -> (Vec3, Vec3, Vec3) {
1173        let (a, b, c) = (t - t0, t - t1, t - t2);
1174        let point = p0.add(d1.scale(a)).add(d2.scale(a * b)).add(d3.scale(a * b * c));
1175        let first = d1.add(d2.scale(a + b)).add(d3.scale(b * c + a * c + a * b));
1176        let second = d2.scale(2.0).add(d3.scale(2.0 * (a + b + c)));
1177        (point, first, second)
1178    };
1179    let (low, high) = (ts[j - 1], ts[j + 1]);
1180    let start = ts[j];
1181    let mut t = start;
1182    let mut converged = false;
1183    for _ in 0..50 {
1184        let (c, c1, c2) = curve(t);
1185        let w = c.sub(p);
1186        let (g, slope) = (w.dot(c1), c1.dot(c1) + w.dot(c2));
1187        if !(g.is_finite() && slope.is_finite()) || slope == 0.0 {
1188            wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: slope {slope:e} g {g:e} at t {t}"));
1189            return Solve::Unread;
1190        }
1191        if g.abs() <= 16.0 * f64::EPSILON * (p.length() + c.length()) * c1.length() {
1192            converged = true;
1193            break;
1194        }
1195        let step = g / slope;
1196        let before = t;
1197        t -= step;
1198        if !(t >= low && t <= high) {
1199            wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: window exit t {before} -> {t} (window [{low}, {high}])"));
1200            return if t.is_finite() { Solve::Window(t) } else { Solve::Unread };
1201        }
1202        // The uniform reader's stop, 1e-14 · (1 + |s|) in node units from
1203        // the stencil's base, read in LOCAL node units here (one node = half
1204        // the window), so it does not depend on where the native t's origin
1205        // is or on its scale.
1206        let node = 0.5 * (high - low);
1207        if (step / node).abs() <= 1e-14 * (1.0 + ((t - t0) / node).abs()) {
1208            converged = true;
1209            break;
1210        }
1211    }
1212    if !converged {
1213        wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: no convergence in 50 steps, t {t}"));
1214        return Solve::Unread;
1215    }
1216    let distance = curve(t).0.sub(p).length() - radius;
1217    if distance.is_finite() {
1218        Solve::Read(distance)
1219    } else {
1220        wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: non-finite distance at t {t}"));
1221        Solve::Unread
1222    }
1223}
1224
1225/// The intervals the construction request refines (and, when it cannot,
1226/// reports): every interval whose DECLARED wall reading — as
1227/// `wall_interior_misses` returns it, `(left, declared, reading,
1228/// uncertainty)` — exceeds `model`. The one decision the request makes.
1229pub fn wall_model_missing(readings: &[(usize, f64, f64, f64)], model: f64) -> Vec<usize> {
1230    readings.iter().filter(|&&(_, declared, _, _)| !(declared <= model)).map(|&(left, _, _, _)| left).collect()
1231}
1232
1233/// Every fillet-wall interval's worst distance from the rolling ball's sweep,
1234/// read on the BUILT wall at the even fractions of the centre stencil
1235/// j/`subdivisions` (the centres at twice the probe density) and section
1236/// angles k/`probes` ([`declared_wall_probe`]), keyed by the interval's left
1237/// sample: each readable interval's largest DECLARED reading, largest reading
1238/// and largest uncertainty, and separately
1239/// every interval with an unreadable reading or a contact the stencil did not
1240/// solve. The wall shares the rails' `u` (one interpolation parameter for its
1241/// three rows).
1242#[allow(clippy::too_many_arguments)]
1243pub(super) fn wall_interior_misses(
1244    contacts: &crate::blend::chain::DenseContacts,
1245    samples: &[ChainSample],
1246    surface: &crate::NurbsSurface,
1247    low: f64,
1248    range: f64,
1249    radius: f64,
1250    subdivisions: usize,
1251    probes: usize,
1252    wrap: bool,
1253) -> (Vec<(usize, f64, f64, f64)>, Vec<usize>) {
1254    use std::collections::BTreeMap;
1255    // Each interval's centres at fractions 0, 1/k, …, 1: its stations at the
1256    // ends, the stencil's solved balls between.
1257    let mut nodes: BTreeMap<usize, (usize, Vec<Option<Vec3>>)> = BTreeMap::new();
1258    for (index, (left, next, fraction, _, _)) in contacts.solved.iter().enumerate() {
1259        let entry = nodes.entry(*left).or_insert_with(|| {
1260            let mut row = vec![None; subdivisions + 1];
1261            row[0] = Some(samples[*left].station.center);
1262            row[subdivisions] = Some(samples[*next].station.center);
1263            (*next, row)
1264        });
1265        let step = (fraction * subdivisions as f64).round() as usize;
1266        if (1..subdivisions).contains(&step) {
1267            entry.1[step] = contacts.centers.get(index).copied().flatten();
1268        }
1269    }
1270    let mut readable = Vec::new();
1271    let mut unreadable: Vec<usize> = contacts.unsolved_at.clone();
1272    for (&left, (next, row)) in &nodes {
1273        let Some(centres) = row.iter().copied().collect::<Option<Vec<Vec3>>>() else {
1274            unreadable.push(left);
1275            continue;
1276        };
1277        let (from, to) = (samples[left].parameter, samples[*next].parameter);
1278        let (mut declared, mut worst, mut spread) = (0.0_f64, 0.0_f64, 0.0_f64);
1279        let mut read = true;
1280        let prepared = PreparedWall::for_interval(&centres);
1281        'probes: for step in (2..subdivisions).step_by(2) {
1282            let global = from + (step as f64 / subdivisions as f64) * (to - from);
1283            let global = if wrap { global.rem_euclid(1.0) } else { global };
1284            let u = (global - low) / range;
1285            for k in 1..probes {
1286                let v = k as f64 / probes as f64;
1287                let reading = surface.evaluate(u, v).ok().and_then(|p| {
1288                    match &prepared {
1289                        Some(cache) => cache.read(p, step, step as f64 / subdivisions as f64, radius),
1290                        None => declared_wall_probe_located(p, &centres, step, step as f64 / subdivisions as f64, radius),
1291                    }
1292                });
1293                match reading {
1294                    Some((distance, gap)) => {
1295                        declared = declared.max(distance + gap);
1296                        worst = worst.max(distance);
1297                        spread = spread.max(gap);
1298                    }
1299                    None => {
1300                        read = false;
1301                        break 'probes;
1302                    }
1303                }
1304            }
1305        }
1306        if read {
1307            readable.push((left, declared, worst, spread));
1308        } else {
1309            unreadable.push(left);
1310        }
1311    }
1312    unreadable.sort_unstable();
1313    unreadable.dedup();
1314    (readable, unreadable)
1315}
1316
1317
1318fn build_closed_smooth_chain(
1319    solid: &BrepSolid,
1320    segments: &[ChainSegment<'_>],
1321    radius: f64,
1322    chamfer: bool,
1323    name: Option<&str>,
1324    budget: &ChainBudget,
1325    fold: FoldPolicy,
1326    bar: f64,
1327) -> Result<Rung, KernelRefusal> {
1328    let samples = match march_chain_typed(segments, radius, false, budget, fold) {
1329        Ok(samples) => samples,
1330        Err(ChainMarchError::Station(failure)) => return Ok(Rung::StationFailed(failure)),
1331        // Only local refinement reports incoherence; the march never does, so
1332        // this is its refusal exactly as `march_chain` would return it.
1333        Err(ChainMarchError::Incoherent(failure)) => return Err(failure.error),
1334        Err(ChainMarchError::Other(error)) => return Err(error),
1335    };
1336    CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(0));
1337    build_closed_chain_from_samples(solid, segments, radius, chamfer, name, budget, fold, bar, samples, 0)
1338}
1339
1340
1341thread_local! {
1342    /// The deepest local round any rung of the current ladder step attempted
1343    /// (reset as each rung's march is built from), so a rejected refinement
1344    /// reports the rounds it actually spent.
1345    static CHAIN_DEEPEST_ROUND: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1346}
1347
1348// BREP lane L: begin lcount234_chain_local_continue_20261016
1349/// Whether a rung's local refinement may run past [`REFINE_ROUNDS`] while it
1350/// still improves (`BREP_CHAIN_LOCAL_CONTINUE=1`; off by default until its
1351/// census promotes it). The ladder repeats its local rounds from scratch on
1352/// every rung.
1353fn local_continue_on() -> bool {
1354    switch!(live "BREP_CHAIN_LOCAL_CONTINUE", false)
1355}
1356
1357/// The most local rounds a rung may take with the switch on.
1358const LOCAL_CONTINUE_MAX_ROUNDS: usize = 4 * REFINE_ROUNDS;
1359
1360/// Rounds without a new best stencil reading before the rung is spent.
1361const LOCAL_CONTINUE_STALL_ROUNDS: usize = 3;
1362
1363thread_local! {
1364    /// The best stencil reading of the rung being refined, and its round.
1365    static CHAIN_LOCAL_BEST: std::cell::Cell<(f64, usize)> = const { std::cell::Cell::new((f64::INFINITY, 0)) };
1366}
1367
1368/// Whether a rung's local rounds are spent with the switch on: past
1369/// [`LOCAL_CONTINUE_MAX_ROUNDS`], or [`LOCAL_CONTINUE_STALL_ROUNDS`] rounds
1370/// since the best stencil reading. Counted in rounds, never in time. Round 0
1371/// reads the halfway point only, a different instrument from the dense stencil
1372/// every later round reads, so the best is kept from round 1 on.
1373fn local_rounds_spent(round: usize, deviation: f64) -> bool {
1374    if round == 0 {
1375        CHAIN_LOCAL_BEST.with(|best| best.set((f64::INFINITY, 0)));
1376        return false;
1377    }
1378    let (_, best_round) = CHAIN_LOCAL_BEST.with(|best| {
1379        let (reading, at) = best.get();
1380        if deviation < reading {
1381            best.set((deviation, round));
1382            (deviation, round)
1383        } else {
1384            (reading, at)
1385        }
1386    });
1387    round >= LOCAL_CONTINUE_MAX_ROUNDS || round - best_round >= LOCAL_CONTINUE_STALL_ROUNDS
1388}
1389// BREP lane L: end lcount234_chain_local_continue_20261016
1390
1391/// Fit, measure and build one rung from its stations. A plain (non-carve)
1392/// rung whose fitted rails miss the halfway contacts by more than `bar`
1393/// first REFINES LOCALLY: one continuation station into each failing interval
1394/// (`march::insert_chain_stations`), up to [`REFINE_ROUNDS`] rounds and never
1395/// past [`CHAIN_CARVE_MAX_PER_SEGMENT`] stations in a segment, then measures
1396/// again. Only a rung whose local rounds are spent is too coarse, and the
1397/// ladder climbs as it always has. A rung that passes at once is built from
1398/// exactly the stations it was built from before.
1399#[allow(clippy::too_many_arguments)]
1400fn build_closed_chain_from_samples(
1401    solid: &BrepSolid,
1402    segments: &[ChainSegment<'_>],
1403    radius: f64,
1404    chamfer: bool,
1405    name: Option<&str>,
1406    budget: &ChainBudget,
1407    fold: FoldPolicy,
1408    bar: f64,
1409    mut samples: Vec<ChainSample>,
1410    round: usize,
1411) -> Result<Rung, KernelRefusal> {
1412    // The rung, for the traces and the typed reports; each segment's own
1413    // count is the budget's.
1414    let per_segment = budget.rung;
1415    CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round)));
1416
1417    // Global rows from the in-segment samples (wrapped-overlap closed fit).
1418    let mut global: Vec<(f64, &ChainSample)> = samples
1419        .iter()
1420        .filter(|sample| (0..budget.count(sample.segment) as isize).contains(&sample.position))
1421        .map(|sample| (sample.parameter.rem_euclid(1.0), sample))
1422        .collect();
1423    global.sort_by(|a, b| a.0.total_cmp(&b.0));
1424    let count = global.len();
1425    let degree = FIT_DEGREE;
1426    let mut extended_params = Vec::new();
1427    let mut samples_cr = Vec::new();
1428    let mut samples_mid = Vec::new();
1429    let mut samples_cs = Vec::new();
1430    let mut push = |station: &Station, parameter: f64| {
1431        extended_params.push(parameter);
1432        samples_cr.push(Vec4::from_point(station.p1, 1.0));
1433        samples_cs.push(Vec4::from_point(station.p2, 1.0));
1434        samples_mid.push(Vec4 {
1435            x: station.apex.x * station.weight,
1436            y: station.apex.y * station.weight,
1437            z: station.apex.z * station.weight,
1438            w: station.weight,
1439        });
1440    };
1441    for offset in (1..=degree).rev() {
1442        let (parameter, sample) = &global[count - offset];
1443        push(&sample.station, parameter - 1.0);
1444    }
1445    for (parameter, sample) in &global {
1446        push(&sample.station, *parameter);
1447    }
1448    // Close the loop: repeat the first station at parameter 1, then the
1449    // wrap continuation.
1450    push(&global[0].1.station, global[0].0 + 1.0);
1451    for offset in 1..=degree {
1452        let (parameter, sample) = &global[offset];
1453        push(&sample.station, parameter + 1.0);
1454    }
1455    let low = extended_params[0];
1456    let high = *extended_params.last().unwrap();
1457    let range = high - low;
1458    let normalized: Vec<f64> = extended_params
1459        .iter()
1460        .map(|parameter| (parameter - low) / range)
1461        .collect();
1462    let seam_low = (0.0 - low) / range;
1463    let seam_high = (1.0 - low) / range;
1464    let fit_row = |row: &[Vec4]| -> Result<NurbsCurve, KernelRefusal> {
1465        let curve = fit::interpolate_homogeneous(row, degree, &normalized).or_refuse(KernelStage::Refine, "interpolate_homogeneous")?;
1466        let (_, tail) = curve.split(seam_low).or_refuse(KernelStage::Refine, "split")?;
1467        let (middle, _) = tail.split(seam_high).or_refuse(KernelStage::Refine, "split")?;
1468        Ok(middle)
1469    };
1470    let cr = fit_row(&samples_cr)?;
1471    let cs = fit_row(&samples_cs)?;
1472    let mid = if chamfer {
1473        None
1474    } else {
1475        Some(fit_row(&samples_mid)?)
1476    };
1477    let u_domain = cr.domain().or_refuse(KernelStage::Refine, "domain")?;
1478    let surface = crate::blend::rows::surface_from_rows(degree, &cr, &cs, mid.as_ref(), true)?;
1479
1480    // The CARVE.  A wall that folds carries a lens of parameter inside the
1481    // swept ball volume; the blend is that wall with the lens cut away along
1482    // the crease where the two sheets meet, and the crease becomes an edge of
1483    // the blend with two coedges on this one face.  Traced on the surface that
1484    // was just fitted — not on the ideal envelope — so the two kept sheets
1485    // meet EXACTLY on the curve the trim is built from (`blend/carve.rs`).
1486    // EVERY rung is measured before anything is built on it, carve or not: the
1487    // rails are interpolants through the stations, and between stations they
1488    // can leave the rolling ball's own contacts — and so the carriers they are
1489    // supposed to ride — by far more than the kernel's intersection-fit
1490    // contract. A carve pays for surgery only on an accurate rung; a plain
1491    // collar pays nothing more than the measurement unless it misses.
1492    let (halfway, halfway_failing) = rail_deviation(&samples, &cr, &cs, low, range, budget, bar)?;
1493    // A rung that local insertion has refined is judged on the dense stencil of
1494    // exact contacts, not the halfway point alone (the NX collar's rung 24 read
1495    // 1.943844e-6 halfway and 2.009538e-6 at 7/16 against 2e-6). A rung that
1496    // passes without insertion is read exactly as it always was.
1497    // A FILLET wall is also judged between its rails, on every rung (carve
1498    // included): the rails can pass while the wall's interior — its weighted
1499    // apex row interpolated between stations — stands off the rolling ball
1500    // (the 20-degree seam-split row's accepted wall read 2.4335e-6 on a 16 x 9
1501    // probe grid and 2.4430e-6 at its worst interval's midpoint, mid-section,
1502    // against 2e-6). A chamfer is not a rolling ball and is not judged
1503    // against one. One stencil of exact contacts serves rails and wall.
1504    let stencil = if round > 0 {
1505        Some(crate::blend::chain::chain_dense_contacts(segments, radius, budget, &samples, LOCAL_RAIL_STENCIL)?)
1506    } else {
1507        None
1508    };
1509    // The wall's own centres, at twice the rail stencil's density: its probes
1510    // sit at the rail stencil's fractions, and each is read at both densities
1511    // (`declared_wall_probe`). The rails keep their own stencil, read exactly
1512    // as before.
1513    let wall_stencil = if !chamfer && wall_verdict_on() {
1514        Some(crate::blend::chain::chain_dense_contacts(segments, radius, budget, &samples, 2 * LOCAL_RAIL_STENCIL)?)
1515    } else {
1516        None
1517    };
1518    let (mut deviation, mut failing, _stencil_reads) = if round > 0 {
1519        let contacts = stencil.as_ref().expect("the local path solves the stencil");
1520        let (dense, unreadable) = dense_rail_misses(contacts, &samples, &cr, &cs, low, range, true)?;
1521        let reads = dense.len() + unreadable.len() + contacts.unsolved;
1522        let failed_to_read: Vec<usize> = contacts.unsolved_at.iter().chain(&unreadable).copied().collect();
1523        let verdict = combine_rail_verdict((halfway, halfway_failing), &dense, &failed_to_read, bar);
1524        crate::blend::carve::carve_trace(format_args!(
1525            "blend chain local rails: rung {per_segment} round {round}: stencil verdict {:.9e} (halfway {halfway:.9e}), \
1526             {} failing interval(s), {} unsolved contact(s)",
1527            verdict.0, verdict.1.len(), contacts.unsolved
1528        ));
1529        (verdict.0, verdict.1, reads)
1530    } else {
1531        (halfway, halfway_failing, 0)
1532    };
1533    // The wall between the rails, joined FAIL-CLOSED: an interval whose wall
1534    // reads over `bar`, or cannot be read, fails exactly as a rail interval
1535    // does, and the ladder (local insertion, climb, the existing refusal)
1536    // decides as it always has. Nothing else about the rung changes: a wall
1537    // inside `bar` adds reads, never stations.
1538    let mut _wall_worst = 0.0_f64;
1539    let mut _wall_spread = 0.0_f64;
1540    let mut wall_readings: Vec<(usize, f64, f64, f64)> = Vec::new();
1541    if let Some(contacts) = wall_stencil.as_ref() {
1542        let (wall, unreadable) =
1543            wall_interior_misses(contacts, &samples, &surface, low, range, radius, 2 * LOCAL_RAIL_STENCIL, WALL_SECTION_PROBES, true);
1544        wall_readings = wall.clone();
1545        // Acceptance on the DECLARED reading against the unchanged bar.
1546        for &(left, declared, _, uncertainty) in &wall {
1547            if declared > bar {
1548                failing.push(left);
1549            }
1550            _wall_worst = _wall_worst.max(declared);
1551            _wall_spread = _wall_spread.max(uncertainty);
1552        }
1553        failing.extend_from_slice(&unreadable);
1554        failing.sort_unstable();
1555        failing.dedup();
1556        deviation = deviation.max(_wall_worst);
1557        crate::blend::carve::carve_trace(format_args!(
1558            "blend chain wall: rung {per_segment} round {round}: wall interior worst {_wall_worst:.9e} over {} \
1559             interval(s), {} unreadable, bar {bar:.3e}",
1560            wall.len(),
1561            unreadable.len()
1562        ));
1563    }
1564    if deviation > bar || !failing.is_empty() {
1565        let in_segment = |segment: usize| {
1566            samples
1567                .iter()
1568                .filter(|sample| sample.segment == segment && (0..budget.count(segment) as isize).contains(&sample.position))
1569                .count()
1570        };
1571        let within_ceiling = (0..segments.len()).all(|segment| {
1572            in_segment(segment) + failing.iter().filter(|&&index| samples[index].segment == segment).count()
1573                <= CHAIN_CARVE_MAX_PER_SEGMENT
1574        });
1575        crate::blend::carve::carve_trace(format_args!(
1576            "blend chain local rails: rung {per_segment} round {round} stations {} failing {} \
1577             worst {deviation:.9e} bar {bar:.9e} ceiling {}",
1578            samples.len(),
1579            failing.len(),
1580            if within_ceiling { "ok" } else { "reached" }
1581        ));
1582        // BREP lane L: begin lcount234_chain_local_continue_20261016
1583        let rounds_spent = if local_continue_on() {
1584            local_rounds_spent(round, deviation)
1585        } else {
1586            round >= REFINE_ROUNDS
1587        };
1588        // BREP lane L: end lcount234_chain_local_continue_20261016
1589        if fold != FoldPolicy::Refuse || rounds_spent || !within_ceiling {
1590            return Ok(Rung::TooCoarse { deviation });
1591        }
1592        // The insertion is the next round's attempt, whatever it returns.
1593        CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round + 1)));
1594        match insert_chain_stations(segments, radius, budget, &mut samples, &failing) {
1595            Ok(()) => {}
1596            Err(ChainMarchError::Station(failure)) => return Ok(Rung::StationFailed(failure)),
1597            // An inserted station that does not reach its retained right
1598            // neighbour's branch: this rung cannot be refined coherently, so it
1599            // is as coarse as its measured rails say, and the ladder decides.
1600            Err(ChainMarchError::Incoherent(failure)) => {
1601                crate::blend::carve::carve_trace(format_args!(
1602                    "blend chain local rails: rung {per_segment} round {round}: segment {} station \
1603                     at t {:.9} does not reach its retained right neighbour: {}",
1604                    failure.segment, failure.t, failure.error
1605                ));
1606                return Ok(Rung::TooCoarse { deviation });
1607            }
1608            Err(ChainMarchError::Other(error)) => return Err(error),
1609        }
1610        assign_chain_parameters(&mut samples, segments.len(), budget, false);
1611        return build_closed_chain_from_samples(
1612            solid, segments, radius, chamfer, name, budget, fold, bar, samples, round + 1,
1613        );
1614    }
1615    crate::blend::carve::carve_trace(format_args!(
1616        "blend chain: {per_segment} stations per segment leaves the rails {deviation:.6e} \
1617         from the rolling ball, inside {bar:.3e}"
1618    ));
1619    // The CONSTRUCTION request, plain fillet rungs only: an ACCEPTED wall is
1620    // refined toward `KernelTolerances::model` — the identity tolerance, the
1621    // same 1e-7 the pcurve construction floor refines to under its looser
1622    // acceptance — locally, in exactly the intervals whose DECLARED reading
1623    // (`declared_wall_probe`: the proxy reading plus its uncertainty from
1624    // stencil spread AND change with node density) is over it: one rule for
1625    // the acceptance verdict, this request and its report. An estimate with
1626    // its uncertainty, NOT a proven bound.
1627    // Acceptance is unchanged: the refined rung must pass it again, and every
1628    // retained station, branch guard and ceiling holds. A wall already inside
1629    // `model` everywhere inserts nothing and builds exactly as it did. When
1630    // refinement cannot run or does not build, THIS accepted rung stands and
1631    // says so, typed (`WallModelReport`); never silently.
1632    let model = crate::KernelTolerances::for_solid(solid, 1e-7).model;
1633    let stations_now = (0..segments.len())
1634        .map(|segment| {
1635            samples
1636                .iter()
1637                .filter(|sample| sample.segment == segment && (0..budget.count(segment) as isize).contains(&sample.position))
1638                .count()
1639        })
1640        .max()
1641        .unwrap_or(0);
1642    let mut unmet: Option<(f64, crate::BudgetReason)> = None;
1643    // What the request found short, named in its report: the detail, which
1644    // component the residual is the reading of, and how many intervals it
1645    // could not read (then the true worst is unknown).
1646    let mut request_detail: Option<String> = None;
1647    let mut request_component = crate::MeasuredComponent::Wall;
1648    let mut request_unread = 0usize;
1649    if !chamfer && fold == FoldPolicy::Refuse && model_request_on() {
1650        let wall_missing = wall_model_missing(&wall_readings, model);
1651        // The RAILS against the same request: the shipped support curves ARE
1652        // these rails (`chain_surgery` splits `cr`/`cs` into the support
1653        // edges), so a rail standing off the exact construction ships that
1654        // miss on its carrier. Read against the exact contacts the wall
1655        // reading already solved (j/32 of every interval); an interval whose
1656        // rail reads over `model`, or cannot be read, is short exactly as a
1657        // wall interval is. Acceptance (`bar`) is unchanged.
1658        let (rail_dense, rail_unread) = match wall_stencil.as_ref() {
1659            Some(contacts) => dense_rail_misses(contacts, &samples, &cr, &cs, low, range, true)?,
1660            None => (Vec::new(), Vec::new()),
1661        };
1662        // Per contact, keyed by the interval's left sample: distinct intervals.
1663        let rail_over: std::collections::BTreeSet<usize> =
1664            rail_dense.iter().filter(|&&(_, miss)| !(miss <= model)).map(|&(left, _)| left).collect();
1665        let rail_unread_intervals: std::collections::BTreeSet<usize> = rail_unread.iter().copied().collect();
1666        let rail_missing: Vec<usize> = rail_over.union(&rail_unread_intervals).copied().collect();
1667        let mut missing: Vec<usize> = wall_missing.iter().chain(&rail_missing).copied().collect();
1668        missing.sort_unstable();
1669        missing.dedup();
1670        if !missing.is_empty() {
1671            // The same declared reading, over the intervals short.
1672            let wall_short = wall_readings
1673                .iter()
1674                .filter(|reading| wall_missing.contains(&reading.0))
1675                .map(|&(_, declared, _, _)| declared)
1676                .fold(0.0_f64, f64::max);
1677            let rail_short = rail_dense.iter().filter(|&&(_, miss)| !(miss <= model)).map(|&(_, miss)| miss).fold(0.0_f64, f64::max);
1678            let short = wall_short.max(rail_short);
1679            request_component = if rail_short > wall_short { crate::MeasuredComponent::Rails } else { crate::MeasuredComponent::Wall };
1680            request_unread = rail_unread_intervals.len();
1681            request_detail = Some(format!(
1682                "short of {model:.3e}: rails {rail_short:.3e} off the exact contacts over {} interval(s) ({} unread), \
1683                 wall {wall_short:.3e} over {} interval(s)",
1684                rail_over.len(),
1685                rail_unread_intervals.len(),
1686                wall_missing.len()
1687            ));
1688            let within_ceiling = (0..segments.len()).all(|segment| {
1689                let present = samples
1690                    .iter()
1691                    .filter(|sample| sample.segment == segment && (0..budget.count(segment) as isize).contains(&sample.position))
1692                    .count();
1693                present + missing.iter().filter(|&&index| samples[index].segment == segment).count()
1694                    <= CHAIN_CARVE_MAX_PER_SEGMENT
1695            });
1696            crate::blend::carve::carve_trace(format_args!(
1697                "blend chain wall model: rung {per_segment} round {round}: {} interval(s) short of {model:.3e} \
1698                 (worst reading + spread {short:.3e}), ceiling {}",
1699                missing.len(),
1700                if within_ceiling { "ok" } else { "reached" }
1701            ));
1702            unmet = if round >= model_rounds_limit() {
1703                Some((short, crate::BudgetReason::RoundsSpent))
1704            } else if !within_ceiling {
1705                Some((short, crate::BudgetReason::StationCeiling))
1706            } else {
1707                let mut refined = samples.clone();
1708                // The insertion is the next round's attempt, whatever it returns.
1709                CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round + 1)));
1710                match insert_chain_stations(segments, radius, budget, &mut refined, &missing) {
1711                    Ok(()) => {
1712                        assign_chain_parameters(&mut refined, segments.len(), budget, false);
1713                        match build_closed_chain_from_samples(
1714                            solid, segments, radius, chamfer, name, budget, fold, bar, refined, round + 1,
1715                        ) {
1716                            Ok(Rung::Built(built)) => return Ok(Rung::Built(built)),
1717                            _ => Some((short, crate::BudgetReason::Rejected)),
1718                        }
1719                    }
1720                    Err(_) => {
1721                        // The insertion itself was the attempt.
1722                        CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round + 1)));
1723                        Some((short, crate::BudgetReason::Incoherent))
1724                    }
1725                }
1726            };
1727        }
1728    }
1729    // `BREP_DEBUG_CHAIN_DENSE_RAILS=k` (diagnostic only): the accepted rung's
1730    // rails against exact contacts at k-1 interior fractions of every interval,
1731    // where `rail_deviation` reads only the halfway one. Nothing reads it to
1732    // decide.
1733    if let Some(subdivisions) = std::env::var("BREP_DEBUG_CHAIN_DENSE_RAILS").ok().and_then(|value| value.parse::<usize>().ok()) {
1734        let contacts = crate::blend::chain::chain_dense_contacts(segments, radius, budget, &samples, subdivisions.max(2))?;
1735        let mut worst = (0.0_f64, 0usize, 0isize, 0.0_f64);
1736        let mut unreadable = 0usize;
1737        for (left, next, fraction, p1, p2) in &contacts.solved {
1738            let (from, to) = (samples[*left].parameter, samples[*next].parameter);
1739            let global = (from + fraction * (to - from)).rem_euclid(1.0);
1740            let seed = (global - low) / range;
1741            let reach = (to - from).abs() / range;
1742            match rail_pair_miss(closest_on_rail(&cr, *p1, seed, reach).unwrap_or(f64::NAN), closest_on_rail(&cs, *p2, seed, reach).unwrap_or(f64::NAN)) {
1743                Some(miss) if miss > worst.0 => worst = (miss, samples[*left].segment, samples[*left].position, *fraction),
1744                Some(_) => {}
1745                None => unreadable += 1,
1746            }
1747        }
1748        eprintln!(
1749            "blend chain dense rails: rung {per_segment} round {round}: {} contacts at {subdivisions} per interval, \
1750             worst {:.9e} (halfway reading {halfway:.9e}, bar {bar:.3e}) at segment {} position {} fraction {:.4}; {} unsolved, {unreadable} unreadable",
1751            contacts.solved.len(), worst.0, worst.1, worst.2, worst.3, contacts.unsolved
1752        );
1753    }
1754    let crease = if fold == FoldPolicy::Carve {
1755        // THE BAR IS THE KERNEL'S OWN CONTRACT FOR THE QUANTITY MEASURED. What
1756        // the fit is held to is "does this coedge's curve-on-surface, pushed
1757        // back to 3-D, still trace the same locus as the edge's 3-D curve?",
1758        // which is `pcurve_consistency` — not `intersection_fit`, which is the
1759        // accuracy of a fitted intersection CURVE and is what the re-marched
1760        // wall itself is held to (`carve_ladder`). Measured on the
1761        // 2026-09-02 collar the crease's pcurves reach 5.4e-6 against that
1762        // 4e-3, so the margin is three decades and the bar is not what decides
1763        // the case either way.
1764        let bar = crate::KernelTolerances::for_solid(solid, 1e-7).pcurve_consistency;
1765        let Some(carved) = crate::blend::carve::trace_wall_crease(&surface, radius.abs())? else {
1766            return Err(KernelRefusal::internal(KernelStage::Refine, "carve_no_fold", format!(
1767                "blend carve: the wall re-marched at {per_segment} stations per segment carries                  no fold to carve, but the march at {CHAIN_PER_SEGMENT} refused one"
1768            )));
1769        };
1770        Some(crate::blend::carve::fit_crease(&surface, &carved, bar)?)
1771    } else {
1772        None
1773    };
1774
1775    // Single-face sides (e.g. one cap around the whole rim) get ONE uv
1776    // fit in the rows' own normalized space — identical parameterization
1777    // to cr/cs, so the closed support piece and its pcurve agree exactly.
1778    let single_face = |side: usize| -> bool {
1779        let first_id = segments[0].mate(side).face.id;
1780        segments
1781            .iter()
1782            .all(|segment| segment.mate(side).face.id == first_id)
1783    };
1784    let mut whole_pcurves: [Option<NurbsCurve>; 2] = [None, None];
1785    for side in 0..2 {
1786        if !single_face(side) {
1787            continue;
1788        }
1789        let mut row = Vec::new();
1790        let select = |station: &Station| -> [f64; 2] {
1791            if side == 0 {
1792                station.uv1
1793            } else {
1794                station.uv2
1795            }
1796        };
1797        let mut push_uv = |station: &Station| {
1798            let uv = select(station);
1799            row.push(Vec4::from_point(Vec3::new(uv[0], uv[1], 0.0), 1.0));
1800        };
1801        for offset in (1..=degree).rev() {
1802            push_uv(&global[count - offset].1.station);
1803        }
1804        for (_, sample) in &global {
1805            push_uv(&sample.station);
1806        }
1807        push_uv(&global[0].1.station);
1808        for offset in 1..=degree {
1809            push_uv(&global[offset].1.station);
1810        }
1811        whole_pcurves[side] = Some(fit_row(&row)?);
1812    }
1813
1814    // Per-face pcurve fits over each segment's full sample window
1815    // (in-segment + overshoot), in global parameters.
1816    let mut pcurves1 = Vec::with_capacity(segments.len());
1817    let mut pcurves2 = Vec::with_capacity(segments.len());
1818    for segment in 0..segments.len() {
1819        let mut window: Vec<&ChainSample> = samples
1820            .iter()
1821            .filter(|sample| sample.segment == segment)
1822            .collect();
1823        window.sort_by(|a, b| a.parameter.total_cmp(&b.parameter));
1824        let params: Vec<f64> = window.iter().map(|sample| sample.parameter).collect();
1825        let low = params[0];
1826        let high = *params.last().unwrap();
1827        let normalized: Vec<f64> = params
1828            .iter()
1829            .map(|parameter| (parameter - low) / (high - low))
1830            .collect();
1831        let fit_uv = |select: &dyn Fn(&Station) -> [f64; 2]| -> Result<NurbsCurve, KernelRefusal> {
1832            let points: Vec<Vec4> = window
1833                .iter()
1834                .map(|sample| {
1835                    let uv = select(&sample.station);
1836                    Vec4::from_point(Vec3::new(uv[0], uv[1], 0.0), 1.0)
1837                })
1838                .collect();
1839            let curve = fit::interpolate_homogeneous(&points, degree, &normalized).or_refuse(KernelStage::Refine, "interpolate_homogeneous")?;
1840            // Re-express in GLOBAL parameters: the curve's [0,1] domain
1841            // corresponds to [low, high]; keep as-is and remember the
1842            // affine map through the window bounds.
1843            Ok(curve)
1844        };
1845        pcurves1.push((low, high, fit_uv(&|station| station.uv1)?));
1846        pcurves2.push((low, high, fit_uv(&|station| station.uv2)?));
1847    }
1848
1849    let wall_surface = unmet.as_ref().map(|_| surface.clone());
1850    let built = chain_surgery(
1851        solid,
1852        segments,
1853        ChainRows {
1854            surface,
1855            cr,
1856            cs,
1857            u_domain,
1858            fit_low: low,
1859            fit_range: range,
1860            pcurves1,
1861            pcurves2,
1862            whole_pcurves,
1863            crease,
1864        },
1865        name,
1866    )?;
1867    if let (Some((residual, reason)), Some(surface)) = (unmet, wall_surface) {
1868        crate::blend::record_wall_model_report(crate::blend::WallModelReport {
1869            name: name.map(str::to_string),
1870            surface,
1871            request: model,
1872            residual,
1873            detail: request_detail,
1874            budget: crate::ApproximationBudget {
1875                reason,
1876                // Rounds ATTEMPTED (the deepest any refinement of this rung
1877                // reached); the stations and residual are this shipped rung's.
1878                rounds_used: CHAIN_DEEPEST_ROUND.with(|deepest| deepest.get()).max(round),
1879                rounds_limit: model_rounds_limit(),
1880                stations: stations_now,
1881                station_limit: CHAIN_CARVE_MAX_PER_SEGMENT,
1882                mechanism: crate::BudgetMechanism::LocalRounds,
1883                measured_component: request_component,
1884                unread: request_unread,
1885            },
1886        });
1887    }
1888    Ok(Rung::Built(built))
1889}
1890
1891pub(super) struct ChainRows {
1892    pub(super) surface: NurbsSurface,
1893    pub(super) cr: NurbsCurve,
1894    pub(super) cs: NurbsCurve,
1895    pub(super) u_domain: [f64; 2],
1896    /// Affine map from the rows' fit space to GLOBAL chain parameters:
1897    /// global = fit_low + p * fit_range (the global fit normalised its
1898    /// wrap-extended parameters onto [0, 1] before interpolating).
1899    pub(super) fit_low: f64,
1900    pub(super) fit_range: f64,
1901    /// Per-segment (window_low, window_high, uv curve over [0,1]) in
1902    /// GLOBAL parameters.
1903    pub(super) pcurves1: Vec<(f64, f64, NurbsCurve)>,
1904    pub(super) pcurves2: Vec<(f64, f64, NurbsCurve)>,
1905    /// Whole-chain uv fits (rows' fit space) for single-face sides.
1906    pub(super) whole_pcurves: [Option<NurbsCurve>; 2],
1907    /// The crease a CARVED wall is cut along: the inner loop of the blend
1908    /// face, one edge carrying two coedges of that same face.
1909    pub(super) crease: Option<crate::blend::carve::CarvedCrease>,
1910}
1911
1912impl ChainRows {
1913    pub(super) fn to_global(&self, fit_parameter: f64) -> f64 {
1914        self.fit_low + fit_parameter * self.fit_range
1915    }
1916}
1917
1918/// Extract the pcurve portion for a global window [a, b] from a
1919/// segment's fitted uv curve, re-parameterised so its domain maps
1920/// affinely onto the portion (matching the split support edge).
1921pub(super) fn pcurve_portion(fitted: &(f64, f64, NurbsCurve), a: f64, b: f64) -> Result<NurbsCurve, KernelRefusal> {
1922    let (low, high, curve) = fitted;
1923    // The chain parameterisation wraps with period 1; pick the period
1924    // copy of the window that overlaps this segment's fit range.
1925    let to_local = |value: f64| {
1926        let mut best = value;
1927        for candidate in [value, value + 1.0, value - 1.0] {
1928            if candidate >= low - 1e-9 && candidate <= high + 1e-9 {
1929                best = candidate;
1930                break;
1931            }
1932        }
1933        ((best - low) / (high - low)).clamp(0.0, 1.0)
1934    };
1935    let mut local_a = to_local(a);
1936    let mut local_b = to_local(b);
1937    if local_a > local_b {
1938        std::mem::swap(&mut local_a, &mut local_b);
1939    }
1940    let epsilon = 1e-9;
1941    let (_, tail) = if local_a > epsilon {
1942        curve.split(local_a).or_refuse(KernelStage::Refine, "split")?
1943    } else {
1944        (curve.clone(), curve.clone())
1945    };
1946    let tail = if local_a > epsilon {
1947        tail
1948    } else {
1949        curve.clone()
1950    };
1951    let portion = if local_b < 1.0 - epsilon {
1952        tail.split(local_b).or_refuse(KernelStage::Refine, "split")?.0
1953    } else {
1954        tail
1955    };
1956    Ok(portion)
1957}
1958
1959/// The single boundary edge of a side's mate face(s) incident to a chain
1960/// vertex, EXCLUDING the two chain edges meeting there — i.e. the SEAM
1961/// (same face on both segments) or the SPOKE (face changes) that the
1962/// support curve must cross.  `None` when the chain simply flows through
1963/// (same face, no seam — e.g. a stadium cap rim vertex).
1964pub(super) fn cross_edge_at(
1965    solid: &BrepSolid,
1966    face_before: &FaceRecord,
1967    loop_before: usize,
1968    face_after: &FaceRecord,
1969    loop_after: usize,
1970    vertex: u64,
1971    before_edge: u64,
1972    after_edge: u64,
1973) -> Result<Option<u64>, KernelRefusal> {
1974    let mut found: Option<u64> = None;
1975    let mut consider = |face: &FaceRecord, loop_index: usize| -> Result<(), KernelRefusal> {
1976        for coedge in &face.loops[loop_index].coedges {
1977            if coedge.edge_id == before_edge || coedge.edge_id == after_edge {
1978                continue;
1979            }
1980            let edge = solid
1981                .edges
1982                .iter()
1983                .find(|edge| edge.id == coedge.edge_id)
1984                .ok_or(KernelRefusal::internal(KernelStage::Refine, "missing_edge", "blend: loop references missing edge"))?;
1985            if edge.start_vertex_id == vertex || edge.end_vertex_id == vertex {
1986                if found.is_some() && found != Some(edge.id) {
1987                    return Err(KernelRefusal::unsupported(KernelStage::Classify, "chain_cross_edges", "blend: multiple cross edges at a chain vertex"));
1988                }
1989                found = Some(edge.id);
1990            }
1991        }
1992        Ok(())
1993    };
1994    consider(face_before, loop_before)?;
1995    if !(face_after.id == face_before.id && loop_after == loop_before) {
1996        consider(face_after, loop_after)?;
1997    }
1998    Ok(found)
1999}
2000
2001/// The nearest periodic image of a seam boundary to `value` — the boundary a
2002/// crossing endpoint must be pinned to, read off its ADJACENT INTERIOR sample.
2003fn nearest_seam_image(value: f64, low: f64, high: f64) -> f64 {
2004    let period = high - low;
2005    low + ((value - low) / period).round() * period
2006}
2007
2008/// The mate-face pcurve of a support PIECE, built by projecting the piece's
2009/// 3D curve onto the (analytic) mate surface and fitting.  Because a chain
2010/// support rides EXACTLY on its mate carrier, the projection is exact; the
2011/// periodic track is unwrapped so it never jumps a period across the carrier
2012/// seam, and crossing endpoints are pinned ONTO the seam so the piece and the
2013/// trimmed seam edge close the loop in parameter space.
2014///
2015/// The carrier is closed in EITHER direction, and the crossed seam is not
2016/// always the u meridian.  A cylinder/cone/sphere is closed in u only, so its
2017/// seam is the u0 ≡ u1 meridian — but a TORUS is biperiodic, and a tube welded
2018/// through a plane crosses the torus' v0 ≡ v1 PARALLEL (its outer equator)
2019/// instead.  Pinning u there drags the endpoint a half-carrier away from its
2020/// own 3D vertex (the collar loop then closes on a uv corner that is nowhere
2021/// near the vertex, and the mate face's trim is garbage), so the pinned AXIS is
2022/// chosen GEOMETRICALLY: whichever closed direction's seam actually passes
2023/// through the endpoint.  A carrier closed in u only can only ever take the u
2024/// branch, exactly as before.
2025pub fn project_piece_pcurve(
2026    piece: &NurbsCurve,
2027    surface: &NurbsSurface,
2028    start_is_crossing: bool,
2029    end_is_crossing: bool,
2030) -> Result<NurbsCurve, KernelRefusal> {
2031    project_piece_pcurve_from(piece, surface, start_is_crossing, end_is_crossing, None)
2032}
2033
2034
2035/// A trim pcurve `old` as a GUIDE for [`project_piece_pcurve_from`]: at track
2036/// fraction `f` its uv at the same fraction of its own domain, closed
2037/// directions wrapped and open ones clamped into `surface`'s domain; `None`
2038/// where that uv is not finite.
2039pub fn pcurve_guide<'a>(old: &'a NurbsCurve, surface: &NurbsSurface) -> Result<impl Fn(f64) -> Option<[f64; 2]> + 'a, KernelRefusal> {
2040    let [o0, o1] = old.domain().or_refuse(KernelStage::Refine, "domain")?;
2041    let (closed_u, closed_v) = surface.closed_directions().or_refuse(KernelStage::Refine, "closed_directions")?;
2042    let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
2043    let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
2044    let into = move |value: f64, closed: bool, low: f64, high: f64| {
2045        if closed && high > low {
2046            low + (value - low).rem_euclid(high - low)
2047        } else {
2048            value.clamp(low, high)
2049        }
2050    };
2051    Ok(move |fraction: f64| {
2052        let uv = old.evaluate(o0 + (o1 - o0) * fraction).ok()?;
2053        let seed = [into(uv.x, closed_u, u0, u1), into(uv.y, closed_v, v0, v1)];
2054        seed.iter().all(|value| value.is_finite()).then_some(seed)
2055    })
2056}
2057
2058/// [`project_piece_pcurve`], every sample's foot sought from `guide` at its
2059/// fraction (a uv on the branch the piece is known to run on — a support
2060/// trim's own march pcurve) instead of from its neighbour's foot. A foot
2061/// continued from its neighbour stays wherever that neighbour's did: at a
2062/// STATIONARY edge of the carrier (an extrusion of a profile whose derivative
2063/// vanishes at its start, S_u = 0 along u = 0) a foot seeded on that edge has
2064/// no gradient to leave it by, and every later sample stayed there with it
2065/// (the stationary-start prism's refit: one foot, [0, 0.9], for the whole
2066/// rail, 6.0 off it at the far end). Without a guide, as before.
2067pub fn project_piece_pcurve_from(
2068    piece: &NurbsCurve,
2069    surface: &NurbsSurface,
2070    start_is_crossing: bool,
2071    end_is_crossing: bool,
2072    guide: Option<&dyn Fn(f64) -> Option<[f64; 2]>>,
2073) -> Result<NurbsCurve, KernelRefusal> {
2074    project_piece_pcurve_within(piece, surface, start_is_crossing, end_is_crossing, guide, &[])
2075}
2076
2077/// [`project_piece_pcurve_from`], its track first refined (two bisections)
2078/// in the dense interval holding each fraction of `refine_near` — where a
2079/// caller that read the SHIPPED curve again found it over the floor between
2080/// the fitter's own stencil points — and then fitted at the same floor.
2081/// The code of a support pcurve fit that misses the refinement floor.
2082pub const CHAIN_PCURVE_FLOOR_WHAT: &str = "chain_pcurve_floor";
2083
2084pub fn project_piece_pcurve_within(
2085    piece: &NurbsCurve,
2086    surface: &NurbsSurface,
2087    start_is_crossing: bool,
2088    end_is_crossing: bool,
2089    guide: Option<&dyn Fn(f64) -> Option<[f64; 2]>>,
2090    refine_near: &[f64],
2091) -> Result<NurbsCurve, KernelRefusal> {
2092    project_piece_pcurve_track(piece, surface, start_is_crossing, end_is_crossing, guide, refine_near, false, 1)
2093}
2094
2095/// [`project_piece_pcurve_within`], retried where it misses the floor on a
2096/// track that also samples the piece's own knots (lane L, 2026-10-16). A track
2097/// sampled uniformly in the piece's parameter cannot follow a rail whose own
2098/// knot spans are finer than its spacing — a closed march crowds its stations
2099/// where the rim's curvature jumps (G1 not G2 at its seam: rail spans of
2100/// 3.6e-5 against a track spacing of 2.4e-4, the fit stalled 1.7e-5 off). Only
2101/// for a caller whose floor miss is TERMINAL: a caller that answers the miss
2102/// itself (a ladder that refines its march) keeps its own answer. A fit
2103/// already on the floor never takes the second track; a retry that misses
2104/// returns the uniform refusal unchanged.
2105pub fn project_piece_pcurve_within_knot_retry(
2106    piece: &NurbsCurve,
2107    surface: &NurbsSurface,
2108    start_is_crossing: bool,
2109    end_is_crossing: bool,
2110    guide: Option<&dyn Fn(f64) -> Option<[f64; 2]>>,
2111    refine_near: &[f64],
2112) -> Result<NurbsCurve, KernelRefusal> {
2113    let floor_miss = |refusal: &KernelRefusal| matches!(&refusal.class, crate::RefusalClass::NonConvergence { what } if what == CHAIN_PCURVE_FLOOR_WHAT);
2114    let fit = |knot_aware: bool, ceiling_factor: usize| {
2115        project_piece_pcurve_track(piece, surface, start_is_crossing, end_is_crossing, guide, refine_near, knot_aware, ceiling_factor)
2116    };
2117    let uniform = match fit(false, 1) {
2118        Err(uniform) if floor_miss(&uniform) => uniform,
2119        other => return other,
2120    };
2121    match fit(true, 2) {
2122        Err(doubled) if floor_miss(&doubled) => {}
2123        Err(_) => return Err(uniform),
2124        fitted => return fitted,
2125    }
2126    // A rail that is only C1 where its spine's curvature jumps (a path
2127    // spline's short straight leads into its Hermite spans, G1 not G2)
2128    // carries a track whose fit converges only O(h²) toward each joint, and
2129    // the local refinement that grades samples there runs out of room: a
2130    // rail of 512 or more control points starts its uniform track AT the
2131    // ceiling and is never refined at all (a 10 m swept bar rounded r = 90:
2132    // 5.8e-4 off with nothing inserted), and the knot-aware track, crowded by
2133    // the march's own stations, can stop just over the floor (the same bar at
2134    // r = 45: 1.5e-7 at 8192 intervals) or diverge. Only then are the uniform
2135    // track and the knot-aware track each refined once more, in that order,
2136    // within four times the uniform ceiling. The floor is unchanged, and a
2137    // miss there keeps the uniform refusal.
2138    for knot_aware in [false, true] {
2139        match fit(knot_aware, 4) {
2140            Err(wider) if floor_miss(&wider) => {}
2141            Err(_) => return Err(uniform),
2142            fitted => return fitted,
2143        }
2144    }
2145    Err(uniform)
2146}
2147
2148/// [`project_piece_pcurve_within`]'s track and fit, the track sampled
2149/// uniformly in the piece's parameter, and with `knot_aware` at the piece's
2150/// interior knots too; its local repair stays within `ceiling_factor` times
2151/// the uniform ceiling.
2152#[allow(clippy::too_many_arguments)]
2153fn project_piece_pcurve_track(
2154    piece: &NurbsCurve,
2155    surface: &NurbsSurface,
2156    start_is_crossing: bool,
2157    end_is_crossing: bool,
2158    guide: Option<&dyn Fn(f64) -> Option<[f64; 2]>>,
2159    refine_near: &[f64],
2160    knot_aware: bool,
2161    ceiling_factor: usize,
2162) -> Result<NurbsCurve, KernelRefusal> {
2163    let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
2164    let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
2165    let (_, closed_v) = surface.closed_directions().or_refuse(KernelStage::Refine, "closed_directions")?;
2166    let period = u1 - u0;
2167    let period_v = v1 - v0;
2168    let [d0, d1] = piece.domain().or_refuse(KernelStage::Refine, "domain")?;
2169    // Dense reference projection; the pcurve is fit from an adaptively
2170    // thinned subset kept as coarse as tolerance allows.
2171    //
2172    // The track is as dense as the PIECE is, not a fixed 96. A carved wall's
2173    // re-marched rail carries hundreds of control points (574 on the
2174    // 2026-09-02 two-torus collar), and a pcurve fitted and checked at 97
2175    // samples of it was accepted 1.19e-3 off the rail it claims.
2176    // The knot-aware retry's track holds the piece's knots on top of the
2177    // uniform samples; its repair may use twice the uniform ceiling.
2178    let ceiling = ceiling_factor * PIECE_TRACK_CEILING;
2179    let uniform = (8 * piece.control_points.len()).clamp(96, PIECE_TRACK_CEILING);
2180    let mut fractions: Vec<f64> = (0..=uniform).map(|section| section as f64 / uniform as f64).collect();
2181    if knot_aware {
2182        // The piece's distinct interior knots, as fractions, merged in where no
2183        // uniform sample already sits within a millionth of the span.
2184        let span = d1 - d0;
2185        let mut knots: Vec<f64> = piece.knots.iter().copied().filter(|knot| *knot > d0 && *knot < d1).map(|knot| (knot - d0) / span).collect();
2186        knots.dedup();
2187        fractions.extend(knots);
2188        fractions.sort_by(|a, b| a.total_cmp(b));
2189        fractions.dedup_by(|b, a| (*b - *a).abs() <= 1e-6 / uniform as f64);
2190    }
2191    let dense = fractions.len() - 1;
2192    crate::blend::record_count("count.track.piece_samples", dense as u64 + 1);
2193    let mut proj_u = Vec::with_capacity(dense + 1);
2194    let mut proj_v = Vec::with_capacity(dense + 1);
2195    let mut point3 = Vec::with_capacity(dense + 1);
2196    let mut params = Vec::with_capacity(dense + 1);
2197    let mut previous_u: Option<f64> = None;
2198    // The foot each sample continues from: the track is ONE branch of the
2199    // carrier, so after the first sample each inversion starts from its
2200    // neighbour's foot rather than asking for the nearest point of the whole
2201    // surface, which on a carrier that comes back near itself is another sheet.
2202    let mut previous_foot: Option<[f64; 2]> = None;
2203    let mut feet: Vec<[f64; 2]> = Vec::with_capacity(dense + 1);
2204    let project_timer = crate::blend::BlendTimer::start("timing.track.project_ms");
2205    for section in 0..=dense {
2206        let fraction = fractions[section];
2207        // The uniform track keeps its own expression, bit for bit (the
2208        // product before the quotient); only knot-aware samples use the
2209        // fraction directly.
2210        let t = if knot_aware { d0 + (d1 - d0) * fraction } else { d0 + (d1 - d0) * section as f64 / dense as f64 };
2211        let point = piece.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?;
2212        let guide = guide.filter(|_| {
2213            true
2214        });
2215        // The guide's seed and the neighbour's foot are both tried and the
2216        // NEARER foot kept: the seeded projector is local and returns a
2217        // stalled Newton's iterate without saying so, so neither seed is
2218        // trusted alone (a foot on its carrier is nearer than any stall).
2219        let seeds: Vec<[f64; 2]> = guide.and_then(|guide| guide(fraction)).into_iter().chain(previous_foot).collect();
2220        let mut projection: Option<crate::projection::SurfaceProjection> = None;
2221        for seed in &seeds {
2222            let found = crate::projection::project_point_to_surface_from_seed(surface, point, *seed).or_refuse(KernelStage::Refine, "project_point_to_surface_from_seed")?;
2223            if projection.as_ref().map_or(true, |known| found.distance < known.distance) {
2224                projection = Some(found);
2225            }
2226        }
2227        let projection = match projection {
2228            Some(projection) => projection,
2229            None => crate::project_point_to_surface(surface, point).or_refuse(KernelStage::Refine, "project_point_to_surface")?,
2230        };
2231        previous_foot = Some([projection.u, projection.v]);
2232        feet.push([projection.u, projection.v]);
2233        let mut u = projection.u;
2234        if let Some(previous) = previous_u {
2235            while u - previous > period * 0.5 {
2236                u -= period;
2237            }
2238            while previous - u > period * 0.5 {
2239                u += period;
2240            }
2241        }
2242        previous_u = Some(u);
2243        proj_u.push(u);
2244        proj_v.push(projection.v);
2245        point3.push(point);
2246        params.push(fraction);
2247    }
2248    project_timer.stop();
2249    // A biperiodic carrier needs the SAME unwrap in v, or a track that walks up
2250    // to the v seam comes back as 0 at the far end and the fit swings across
2251    // the whole carrier.  Anchor the chain on the first INTERIOR sample and
2252    // pull index 0 onto it afterwards: an endpoint sitting exactly ON the seam
2253    // inverts to either boundary at the solver's whim, and letting that
2254    // coin flip anchor the chain would shift the whole piece a period.
2255    if closed_v {
2256        for index in 2..=dense {
2257            while proj_v[index] - proj_v[index - 1] > period_v * 0.5 {
2258                proj_v[index] -= period_v;
2259            }
2260            while proj_v[index - 1] - proj_v[index] > period_v * 0.5 {
2261                proj_v[index] += period_v;
2262            }
2263        }
2264        while proj_v[0] - proj_v[1] > period_v * 0.5 {
2265            proj_v[0] -= period_v;
2266        }
2267        while proj_v[1] - proj_v[0] > period_v * 0.5 {
2268            proj_v[0] += period_v;
2269        }
2270    }
2271    // Interior mean decides which meridian a crossing endpoint sits on, and
2272    // whether the whole track needs a full-period shift into the domain.
2273    let mean_u: f64 = proj_u[1..dense].iter().sum::<f64>() / (dense - 1) as f64;
2274    let seam_u = if mean_u - u0 > u1 - mean_u { u1 } else { u0 };
2275    // Pin a crossing endpoint onto the seam it actually crosses.  Each
2276    // candidate keeps the OTHER coordinate as projected, so the losing axis
2277    // moves the endpoint bodily off its own 3D vertex — the residual names the
2278    // winner with no surface-type special-casing.  u keeps the whole-track
2279    // mean; a v run can legitimately cover a full period, so its boundary is
2280    // read off the ADJACENT INTERIOR sample instead.  Both pins land in the
2281    // track's own (pre-shift) period, so the shift below carries them along
2282    // with the rest of the track.
2283    let pinned = |index: usize,
2284                  neighbour: usize,
2285                  proj_u: &[f64],
2286                  proj_v: &[f64]|
2287     -> Result<(f64, f64), KernelRefusal> {
2288        let point = point3[index];
2289        let u_error = surface
2290            .evaluate(seam_u, proj_v[index]).or_refuse(KernelStage::Refine, "evaluate")?
2291            .sub(point)
2292            .length();
2293        if closed_v {
2294            let seam_v = nearest_seam_image(proj_v[neighbour], v0, v1);
2295            let v_error = surface
2296                .evaluate(proj_u[index], seam_v).or_refuse(KernelStage::Refine, "evaluate")?
2297                .sub(point)
2298                .length();
2299            if v_error < u_error {
2300                return Ok((proj_u[index], seam_v));
2301            }
2302        }
2303        Ok((seam_u, proj_v[index]))
2304    };
2305    if start_is_crossing {
2306        let (u, v) = pinned(0, 1, &proj_u, &proj_v)?;
2307        proj_u[0] = u;
2308        proj_v[0] = v;
2309    }
2310    if end_is_crossing {
2311        let (u, v) = pinned(dense, dense - 1, &proj_u, &proj_v)?;
2312        proj_u[dense] = u;
2313        proj_v[dense] = v;
2314    }
2315    let mut shift = 0.0;
2316    while mean_u + shift > u1 + 1e-9 {
2317        shift -= period;
2318    }
2319    while mean_u + shift < u0 - 1e-9 {
2320        shift += period;
2321    }
2322    for u in proj_u.iter_mut() {
2323        *u += shift;
2324    }
2325    if closed_v {
2326        let mean_v: f64 = proj_v[1..dense].iter().sum::<f64>() / (dense - 1) as f64;
2327        let mut shift_v = 0.0;
2328        while mean_v + shift_v > v1 + 1e-9 {
2329            shift_v -= period_v;
2330        }
2331        while mean_v + shift_v < v0 - 1e-9 {
2332            shift_v += period_v;
2333        }
2334        for v in proj_v.iter_mut() {
2335            *v += shift_v;
2336        }
2337    }
2338    // Coarsest interpolation whose fitted pcurve reproduces the projected TRACK
2339    // to the kernel's pcurve refinement floor — the floor every other pcurve fit
2340    // is held to, and the one the shell vector-area bar is built from.
2341    //
2342    // It used to stop at 0.002 absolute ("half the validator's tolerance"),
2343    // which is `pcurve_consistency / 2` on any model under 20 units and so four
2344    // decades looser than any other trim: a torus face carrying a collar's rail
2345    // was accepted 1.19e-3 off it, and that one coedge was the whole of a
2346    // 1.94e-4 shell vector-area residual, 14.5x its face's bar.
2347    //
2348    // The deviation is measured against the projected track, not the piece's
2349    // 3D points: a pcurve lies on its surface by construction, so a piece that
2350    // is itself off the carrier would hold the ladder at its top however fine
2351    // the fit, and that is a RAIL defect for the march to answer, not this fit.
2352    let tolerance = crate::pcurve::PCURVE_REFINEMENT_TOLERANCE;
2353    // The ladder is the one verified fitter (`track_fit`), which checks every
2354    // rung at the MIDPOINTS between dense samples, projected on their own —
2355    // checked at the dense samples, the top rung, which interpolates every one
2356    // of them, reads zero by construction and passes whatever lies between (on
2357    // the 574-control-point collar rail it read 9.6e-15) — and breaks the fit,
2358    // C1, where the track crosses a knot line of the carrier.
2359    let at = |fraction: f64| piece.evaluate(d0 + (d1 - d0) * fraction);
2360    let mut track = crate::blend::track_fit::Track {
2361        fractions: params,
2362        uv: proj_u.iter().zip(&proj_v).map(|(u, v)| [*u, *v]).collect(),
2363        feet,
2364        breaks: Vec::new(),
2365    };
2366    let breaks = crate::blend::track_fit::curve_breaks(piece, d0, d1, true);
2367    let polish_timer = crate::blend::BlendTimer::start("timing.track.polish_ms");
2368    crate::blend::track_fit::polish_track(surface, &at, &mut track)?;
2369    polish_timer.stop();
2370    let crossings_timer = crate::blend::BlendTimer::start("timing.track.crossings_ms");
2371    crate::blend::track_fit::insert_knot_crossings(surface, &at, &mut track, &breaks)?;
2372    crossings_timer.stop();
2373    crate::blend::record_count("count.track.breaks", track.breaks.len() as u64);
2374    for &fraction in refine_near {
2375        for _ in 0..2 {
2376            let Some(index) = track.fractions.windows(2).position(|pair| pair[0] <= fraction && fraction <= pair[1]) else { break };
2377            if crate::blend::track_fit::refine_track_intervals(surface, &at, &mut track, &[index], ceiling)?.is_none() {
2378                break;
2379            }
2380        }
2381    }
2382    // Where the top rung still misses the floor, the track is refined ONLY in
2383    // the dense intervals whose out-of-sample checks missed (local insertion
2384    // concentrates the rail's stations, and a uniform dense track can leave one
2385    // sample per knot span where the rail turns hardest), within the dense
2386    // ceiling the track was built under; every other sample, the pinned ends
2387    // and the breaks are kept. The floor and the refusal below are unchanged.
2388    let fit_timer = crate::blend::BlendTimer::start("timing.track.fit_local_ms");
2389    let (fit, inserted) = crate::blend::track_fit::fit_track_locally(
2390        surface,
2391        &mut track,
2392        &at,
2393        tolerance,
2394        REFINE_ROUNDS,
2395        ceiling,
2396    )?;
2397    fit_timer.stop();
2398    crate::blend::record_count("count.track.fit_sections", fit.sections as u64);
2399    crate::blend::record_count("count.track.local_inserted", inserted as u64);
2400    if std::env::var("BREP_DEBUG_TRACK_FIT").is_ok() {
2401        eprintln!("TRACK_FIT closed-chain piece: {inserted} sample(s) inserted locally");
2402        eprintln!(
2403            "TRACK_FIT closed-chain piece: miss {:.3e} at {} samples of {} ({} breaks), on floor {}",
2404            fit.miss,
2405            fit.samples,
2406            track.fractions.len(),
2407            track.breaks.len(),
2408            fit.on_floor
2409        );
2410        // Where the miss sits, against what the piece is made of: an endpoint
2411        // pinned onto a seam reads at fraction 0 or 1; an interior miss names
2412        // the piece's knot span there and how that span compares with the
2413        // piece's mean (local insertion clusters spans at the crotch).
2414        if let Some(worst) = fit.worst {
2415            let parameter = d0 + (d1 - d0) * worst.fraction;
2416            let spans: Vec<[f64; 2]> = piece.knots.windows(2)
2417                .filter(|pair| pair[1] > pair[0] && pair[1] > d0 && pair[0] < d1)
2418                .map(|pair| [pair[0], pair[1]]).collect();
2419            let mean = (d1 - d0) / spans.len().max(1) as f64;
2420            let span = spans.iter().position(|pair| parameter >= pair[0] && parameter <= pair[1]);
2421            let width = span.map(|index| spans[index][1] - spans[index][0]);
2422            eprintln!(
2423                "TRACK_FIT closed-chain worst: fraction {:.9} parameter {:.9} (pinned start {start_is_crossing}, pinned end {end_is_crossing}) \
2424                 knot span {:?} of {} width {:?} vs mean {:.3e}; dense bracket [{:.9}, {:.9}] (interval {})",
2425                worst.fraction, parameter, span, spans.len(), width, mean,
2426                worst.bracket[0], worst.bracket[1], worst.interval
2427            );
2428        }
2429    }
2430    // A fit off the floor is refused, not handed on as the best rung. Before the
2431    // fitter broke at knot lines this ladder returned its best rung silently,
2432    // and on the 2026-09-02 two-torus collar that was 1.07e-7 to 8.46e-7 off at
2433    // the top rung on every collar that builds (measured 2026-09-17); broken,
2434    // each of them reaches the floor. What still misses is a rail the march tore
2435    // (2.7 to 3.3 on the oversized radii, a body refused or rejected anyway).
2436    if !fit.on_floor {
2437        if std::env::var("BREP_DEBUG_TRACK_FIT").is_ok() {
2438            // The piece's two ends against the carrier: a rail end that is
2439            // itself off the carrier holds the ladder however fine the fit.
2440            for (label, t) in [("start", d0), ("end", d1)] {
2441                if let Ok(point) = piece.evaluate(t) {
2442                    let standoff = crate::project_point_to_surface(surface, point).map(|p| p.distance).unwrap_or(f64::NAN);
2443                    eprintln!(
2444                        "TRACK_FIT closed-chain piece {label} ({:.9}, {:.9}, {:.9}) stands {standoff:.3e} off the carrier",
2445                        point.x, point.y, point.z
2446                    );
2447                }
2448            }
2449        }
2450        return Err(KernelRefusal::non_convergence(KernelStage::Refine, CHAIN_PCURVE_FLOOR_WHAT, format!(
2451            "{} a closed chain's support piece misses its pcurve by {:.3e} at {} samples, \
2452             against a floor of {tolerance:.1e}",
2453            crate::blend::PCURVE_OFF_FLOOR,
2454            fit.miss,
2455            fit.samples
2456        )));
2457    }
2458    Ok(fit.curve)
2459}
2460
2461
2462
2463/// Immutable interval input; only coefficients are filled lazily. The Newton
2464/// iterations, foot windows and decline ordering remain in the common reader.
2465pub struct PreparedWall<'a> {
2466    fine: &'a [Vec3],
2467    coarse: Vec<Vec3>,
2468    fine_stencils: StencilPreparation,
2469    coarse_stencils: StencilPreparation,
2470}
2471
2472#[derive(Clone, Copy)]
2473struct WallStart {
2474    curve: (Vec3, Vec3, Vec3),
2475    point_length: f64,
2476    tangent_length: f64,
2477    tangent_squared: f64,
2478}
2479impl WallStart {
2480    fn new(curve: (Vec3, Vec3, Vec3)) -> Self {
2481        Self { point_length: curve.0.length(), tangent_length: curve.1.length(),
2482            tangent_squared: curve.1.dot(curve.1), curve }
2483    }
2484}
2485
2486struct StencilPreparation {
2487    finite: bool,
2488    coefficients: std::cell::RefCell<Vec<Option<[Vec3; 4]>>>,
2489    // Every section probe starts at the same integer position of a stencil.
2490    // Cache that exact evaluation, not a converged foot of another probe.
2491    starts: std::cell::RefCell<Vec<[Option<WallStart>; 2]>>,
2492}
2493impl StencilPreparation {
2494    fn new(nodes: &[Vec3]) -> Self {
2495        Self { finite: wall_nodes_finite(nodes), coefficients: std::cell::RefCell::new(vec![None; nodes.len().saturating_sub(3)]),
2496            starts: std::cell::RefCell::new(vec![[None; 2]; nodes.len().saturating_sub(3)]) }
2497    }
2498    fn start(&self, base: usize, j: usize, curve: &impl Fn(f64) -> (Vec3, Vec3, Vec3)) -> Option<WallStart> {
2499        let offset = j.checked_sub(base)?;
2500        if !(1..=2).contains(&offset) { return None; }
2501        let mut entries = self.starts.borrow_mut();
2502        Some(*entries.get_mut(base)?[offset-1].get_or_insert_with(|| WallStart::new(curve(offset as f64))))
2503    }
2504    fn coefficients(&self, nodes: &[Vec3], base: usize) -> [Vec3; 4] {
2505        let mut entries = self.coefficients.borrow_mut();
2506        *entries[base].get_or_insert_with(|| wall_coefficients(nodes, base))
2507    }
2508}
2509
2510fn wall_nodes_finite(nodes: &[Vec3]) -> bool {
2511    nodes.iter().all(|c| c.x.is_finite() && c.y.is_finite() && c.z.is_finite())
2512}
2513
2514fn wall_coefficients(nodes: &[Vec3], base: usize) -> [Vec3; 4] {
2515    // Newton's divided differences on 0, 1, 2, 3, s in node units from `base`.
2516    let [p0, p1, p2, p3] = [nodes[base], nodes[base + 1], nodes[base + 2], nodes[base + 3]];
2517    let d1 = p1.sub(p0);
2518    let d2 = p2.sub(p1.scale(2.0)).add(p0).scale(0.5);
2519    let d3 = p3.sub(p2.scale(3.0)).add(p1.scale(3.0)).sub(p0).scale(1.0 / 6.0);
2520    [p0, d1, d2, d3]
2521}
2522
2523fn wall_coarse(fine: &[Vec3]) -> Vec<Vec3> {
2524    fine.iter().step_by(2).copied().collect()
2525}
2526
2527fn wall_preparation_on() -> bool {
2528    switch!(live "BREP_WALL_PREPARE", true)
2529}
2530
2531impl<'a> PreparedWall<'a> {
2532    pub(in crate::blend) fn for_interval(fine: &'a [Vec3]) -> Option<Self> {
2533        (wall_preparation_on() && wall_solve_reuse_on()).then(|| Self::new(fine))
2534    }
2535    fn new(fine: &'a [Vec3]) -> Self {
2536        let coarse = wall_coarse(fine);
2537        let fine_stencils = StencilPreparation::new(fine);
2538        let coarse_stencils = StencilPreparation::new(&coarse);
2539        Self { fine, coarse, fine_stencils, coarse_stencils }
2540    }
2541    pub(in crate::blend) fn read(&self, p: Vec3, j: usize, fraction: f64, radius: f64) -> Option<(f64, f64)> {
2542        let read = |at| declared_wall_probe_prepared(p, self.fine, at, radius, true, Some(self));
2543        match read(j) {
2544            Some(read) => Some(read),
2545            None => match centre_path_node(self.fine, fraction) {
2546                Some(located) if located != j => read(located),
2547                _ => None,
2548            },
2549        }
2550    }
2551}