Skip to main content

brep_kernel/blending/blend/edge/
open.rs

1use crate::{KernelRefusal, KernelStage, OrRefuse};
2use super::*;
3
4/// General OPEN-edge rolling-ball fillet or chamfer: §4.9 march +
5/// §6.9 surgery with transverse edges on the two end faces.
6pub fn blend_open_edge(
7    solid: &BrepSolid,
8    edge_id: u64,
9    radius: f64,
10    chamfer: bool,
11    name: Option<&str>,
12) -> Result<BrepSolid, KernelRefusal> {
13    // One blend operation: the reports of an earlier one, never consumed, are
14    // dropped as it starts (nested calls keep this operation's).
15    let _operation = crate::blend::BlendOperation::enter();
16    if !(radius > 0.0) || !radius.is_finite() {
17        return Err(KernelRefusal::input(KernelStage::Collect, "radius", "blend: radius must be positive"));
18    }
19    blend_open_edge_impl(solid, edge_id, &|_| radius, Some(radius), chamfer, name)
20}
21
22/// `constant`: the radius when the blend came in through a CONSTANT-radius
23/// entry point (`blend_open_edge`), `None` for a variable profile — the only
24/// provenance on which the wall is judged against one rolling ball.
25pub(super) fn blend_open_edge_impl(
26    solid: &BrepSolid,
27    edge_id: u64,
28    radius_at: &dyn Fn(f64) -> f64,
29    constant: Option<f64>,
30    chamfer: bool,
31    name: Option<&str>,
32) -> Result<BrepSolid, KernelRefusal> {
33    let edge = solid
34        .edges
35        .iter()
36        .find(|edge| edge.id == edge_id)
37        .ok_or_else(|| format!("blend: edge {edge_id} not found")).or_refuse(KernelStage::Refine, "ok_or_else")?;
38    if edge.start_vertex_id == edge.end_vertex_id {
39        return Err(KernelRefusal::input(KernelStage::Collect, "open_edge", "blend: blend_open_edge requires an open edge"));
40    }
41    let (first_face, first_loop, first_coedge) = locate_mate(solid, edge_id, None)?;
42    let (second_face, second_loop, second_coedge) =
43        locate_mate(solid, edge_id, Some((first_face.id, first_loop)))?;
44    let mid_radius = radius_at(edge.t0 + (edge.t1 - edge.t0) * 0.5);
45    let (rho1, rho2) = signed_radii(
46        edge,
47        first_face,
48        first_coedge,
49        second_face,
50        second_coedge,
51        mid_radius,
52    )?;
53    let first_mate = BlendMate {
54        face: first_face,
55        coedge: first_coedge,
56        loop_index: first_loop,
57        rho: rho1,
58    };
59    let second_mate = BlendMate {
60        face: second_face,
61        coedge: second_coedge,
62        loop_index: second_loop,
63        rho: rho2,
64    };
65    // End topology: boundary edges of both mates at each end vertex, the
66    // single face across the corner, and the support crossings.  When a
67    // prior fillet has already consumed one of the end corners, the support
68    // crossing can land at the very rim of the marched rows (the prior
69    // blend's transverse arc meets our contact line right at its base).
70    // March with a growing overshoot until every crossing lands strictly
71    // inside the fitted-row domain so the surgery can trim cleanly.
72    let debug = std::env::var("BREP_DEBUG_BLEND_MARCH").is_ok();
73    if debug {
74        let sp = edge.curve.evaluate(edge.t0);
75        let ep = edge.curve.evaluate(edge.t1);
76        eprintln!(
77            "OPEN edge {} v{}->v{} first_face {} second_face {} p0={:?} p1={:?}",
78            edge.id,
79            edge.start_vertex_id,
80            edge.end_vertex_id,
81            first_face.id,
82            second_face.id,
83            sp,
84            ep
85        );
86    }
87    // The rung's MEASUREMENT (before anything is built on it), over what it
88    // ships: each rail against its carrier's extension over its own crossing
89    // window (`rails_on_shipped_windows`, at the network lane's rail bar, half
90    // `intersection_fit`), and a constant-radius FILLET's wall over those
91    // windows' envelope against the rolling ball's own sweep (the declared
92    // reader the chains use, at `intersection_fit`).
93    let rail_bar = 0.5 * crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
94    let wall_bar = crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
95    let model = crate::KernelTolerances::for_solid(solid, 1e-7).model;
96    // Constant-radius PROVENANCE (the entry point), never sampled constancy:
97    // a variable profile can agree at any finite set of samples.
98    let wall_radius = constant.filter(|radius| radius.is_finite() && *radius > 0.0);
99    let wall_check = !chamfer && wall_radius.is_some() && crate::blend::station_refinement_on();
100    let compute = |overshoot_fraction: f64, station_count: usize| -> Result<(FittedRows, Vec<EndSurgery>, bool, OpenRungReading), KernelRefusal> {
101        // The open-edge surgery locates its ends by support crossings, not by
102        // the marched vertex stations; the snapped indices only break the fit
103        // where the carriers' extension starts (`fit_open_rows`).
104        let law = crate::blend::setback::active();
105        let (stations, vertex_indices, refinement, dense) = if let Some(law) = law {
106            // An asymmetric chamfer's stations: the setback law's sections at
107            // the march's own parameters, refined by doubling to its bar.
108            let parameters = |count: usize| {
109                open_station_parameters(edge, overshoot_fraction, [edge.t0, edge.t1], count, [false, false])
110            };
111            let (stations, vertex_indices) = crate::blend::setback::march_open(
112                solid, edge, &first_mate, &second_mate, &law, station_count, &parameters, rail_bar,
113            )?;
114            let refinement = StationRefinement { exit: StationRefineExit::Converged, ..Default::default() };
115            (stations, vertex_indices, refinement, OpenDenseCentres::default())
116        } else { march_open_stations_core(
117            edge,
118            &first_mate,
119            &second_mate,
120            radius_at,
121            overshoot_fraction,
122            [edge.t0, edge.t1],
123            station_count,
124            [false, false],
125            [false, false],
126            crate::blend::station_refinement_on().then_some(rail_bar),
127            if wall_check { OPEN_WALL_CENTRES } else { 0 },
128            true,
129        )? };
130        let parameters = station_parameters(&stations);
131        let rows = fit_open_rows(
132            &stations,
133            &parameters,
134            chamfer,
135            Some(vertex_indices),
136            extrusion_direction(edge, &first_mate, &second_mate),
137        )?;
138        // The fitted wall itself must not double back along a row
139        // (`fold::check_rows_loop`); terminal, as the march's fold verdicts.
140        crate::blend::fold::check_rows_loop(
141            &rows, &stations, &parameters, Some(vertex_indices), radius_at(0.5 * (edge.t0 + edge.t1)), vec![first_mate.face.id, second_mate.face.id], crate::solid_scale(solid),
142        )?;
143        let mut ends = Vec::with_capacity(2);
144        let mut in_range = true;
145        for (vertex, at_start) in [(edge.start_vertex_id, true), (edge.end_vertex_id, false)] {
146            let (end, side_in_range) = resolve_free_end(
147                solid,
148                edge_id,
149                &first_mate,
150                &second_mate,
151                &rows,
152                vertex,
153                at_start,
154            )?;
155            if debug {
156                eprintln!(
157                    "  [os {overshoot_fraction:.2}] end v{vertex} at_start={at_start} end_face={} first_boundary={}(t={:.4}) second_boundary={}(t={:.4}) cr={:.4} cs={:.4} in_range={side_in_range}",
158                    end.end_face_id,
159                    end.first_edge_id,
160                    end.first_edge_parameter,
161                    end.second_edge_id,
162                    end.second_edge_parameter,
163                    end.cr_parameter,
164                    end.cs_parameter,
165                );
166            }
167            in_range &= side_in_range;
168            ends.push(end);
169        }
170        // The measurement covers what SHIPS: each rail over its own crossing
171        // window (the `cr`/`cs` parameters `build_open_surgery` trims it to,
172        // any retained overshoot included), and the wall over the envelope of
173        // both windows -- not merely between the vertex stations.
174        let windows = [
175            shipped_window(&parameters, ends[0].cr_parameter, ends[1].cr_parameter),
176            shipped_window(&parameters, ends[0].cs_parameter, ends[1].cs_parameter),
177        ];
178        let (rails, rail_samples) =
179            rails_on_shipped_windows(&rows, &parameters, &stations, [&first_mate.face.surface, &second_mate.face.surface], windows);
180        let walls = match (wall_check, windows) {
181            (false, _) => Vec::new(),
182            (true, [Some(first), Some(second)]) => open_wall_readings_why(
183                &rows,
184                &parameters,
185                &stations,
186                [first[0].min(second[0]), first[1].max(second[1])],
187                &dense,
188                wall_radius.unwrap_or(f64::NAN),
189            ),
190            // No shipped window to read: no wall coverage, never acceptance.
191            (true, _) => vec![Err("no shipped window to read".to_string())],
192        };
193        let first_unread = walls.iter().find_map(|wall| wall.as_ref().err().cloned());
194        let walls: Vec<Option<f64>> = if wall_check && windows.iter().any(|window| window.is_none()) {
195            Vec::new()
196        } else {
197            walls.into_iter().map(|wall| wall.ok()).collect()
198        };
199        let reading = OpenRungReading {
200            station_count,
201            stations: stations.len(),
202            rails,
203            rail_samples,
204            walls,
205            first_unread,
206            refine_exit: refinement.exit,
207            inserted: refinement.inserted,
208        };
209        Ok((rows, ends, in_range, reading))
210    };
211
212    // Radius-aware seeded first attempt (occt-filleting-system-study §6(b)
213    // lesson 7): OCCT floors corner extensions at 1.5·max_radius
214    // (`ExtentTwoCorner`) instead of probing blindly.  Convert that floor to
215    // an overshoot fraction of THIS edge: the contact rails sit r·tan(α/2)
216    // from the edge (α = sign-adjusted angle between the mates' raw normals
217    // at mid-edge — the march's own `cos_alpha`), so seed with 1.5× the
218    // widest end radius's rail offset over the edge arc length, clamped to
219    // the ladder's proven [0.08, 0.45] envelope.  Deterministic; `None` when
220    // it degenerates or merely reproduces the ladder's first rung.
221    let seeded_fraction: Option<f64> = (|| {
222        let span = edge.t1 - edge.t0;
223        let mut length = 0.0f64;
224        let mut previous = edge.curve.evaluate(edge.t0).ok()?;
225        for index in 1..=16 {
226            let t = edge.t0 + span * index as f64 / 16.0;
227            let point = edge.curve.evaluate(t).ok()?;
228            length += point.sub(previous).length();
229            previous = point;
230        }
231        if !(length > 0.0) || !length.is_finite() {
232            return None;
233        }
234        let mid_t = edge.t0 + span * 0.5;
235        let uv1 = edge_uv_on_face(first_mate.coedge, edge, mid_t).ok()?;
236        let uv2 = edge_uv_on_face(second_mate.coedge, edge, mid_t).ok()?;
237        let n1 = raw_normal(&first_mate.face.surface, uv1[0], uv1[1]).ok()?;
238        let n2 = raw_normal(&second_mate.face.surface, uv2[0], uv2[1]).ok()?;
239        let cos_alpha =
240            (rho1.signum() * rho2.signum() * n1.dot(n2)).clamp(-1.0, 1.0);
241        // tan(α/2) = √((1−cosα)/(1+cosα)); the tangent-offset factor from
242        // the edge to each rail (box: α = π/2 → offset = r).
243        let tan_half = ((1.0 - cos_alpha).max(0.0) / (1.0 + cos_alpha).max(1e-9)).sqrt();
244        let end_radius = radius_at(edge.t0).abs().max(radius_at(edge.t1).abs());
245        let fraction = (1.5 * end_radius * tan_half / length).clamp(0.08, 0.45);
246        if !fraction.is_finite() || (fraction - 0.08).abs() < 1e-12 {
247            return None;
248        }
249        Some(fraction)
250    })();
251
252    // Retry with a growing overshoot; keep the first attempt whose crossings
253    // are all in range, else fall back to the widest march tried.  The seeded
254    // attempt is accepted ONLY when its crossings land in range — otherwise
255    // the blind ladder below runs exactly as before (including its
256    // fallback-to-first-Ok semantics), so the seed can improve the first
257    // landing but never change the fallback behaviour.
258    let choose = |station_count: usize| -> Result<(FittedRows, Vec<EndSurgery>, OpenRungReading), KernelRefusal> {
259    let mut chosen: Option<(FittedRows, Vec<EndSurgery>, OpenRungReading)> = None;
260    let mut last_error: Option<KernelRefusal> = None;
261    // A wall that FOLDS is the shape's answer, not this rung's: every wider
262    // overshoot marches the same centre curve through the same bend, so the
263    // ladder is left at the first fold rather than re-proving it four times.
264    if let Some(fraction) = seeded_fraction {
265        match compute(fraction, station_count) {
266            Ok((rows, ends, true, reading)) => chosen = Some((rows, ends, reading)),
267            Ok(_) => {}
268            Err(error) if crate::blend::is_wall_fold(&error) => return Err(error),
269            Err(error) => last_error = Some(error),
270        }
271    }
272    if chosen.is_none() {
273        for &overshoot_fraction in &[0.08f64, 0.16, 0.28, 0.45] {
274            match compute(overshoot_fraction, station_count) {
275                Ok((rows, ends, in_range, reading)) => {
276                    let fallback = chosen.is_none();
277                    if in_range {
278                        chosen = Some((rows, ends, reading));
279                        break;
280                    } else if fallback {
281                        chosen = Some((rows, ends, reading));
282                    }
283                }
284                Err(error) if crate::blend::is_wall_fold(&error) => return Err(error),
285                Err(error) => last_error = Some(error),
286            }
287        }
288    }
289    chosen.ok_or_else(|| {
290        last_error.unwrap_or_else(|| {
291            KernelRefusal::internal(
292                KernelStage::Refine,
293                "open_march",
294                "blend: open march failed at every overshoot",
295            )
296        })
297    })
298    };
299    // The LADDER: the open march's existing budget — STATIONS doubling to
300    // MAX_OPEN_STATIONS, each rung with its local refinement (REFINE_ROUNDS,
301    // REFINE_STATION_FACTOR) against the rail bar — climbed until a rung is
302    // ACCEPTED (rails and wall inside their bars), then, for a plain fillet,
303    // further toward `model` on the wall. A rung the request climbs to that
304    // fails acceptance is not taken: the accepted rung ships and says so,
305    // typed. A ladder that never accepts ships its top rung with a named note,
306    // as the network lane's open march does (a body that built before is not
307    // turned into a refusal here) -- but it is NOT an accepted rung: it ships
308    // with a typed `blend.wall_acceptance` report of its measured deficit.
309    // Acceptance is stated positively: every reading present, finite and
310    // inside its bar (a NaN or an empty coverage never passes).
311    let accepts = |reading: &OpenRungReading| {
312        reading.rails_read()
313            && reading.rails <= rail_bar
314            && (!wall_check || reading.worst_wall().is_some_and(|wall| wall <= wall_bar))
315    };
316    let meets_model = |reading: &OpenRungReading| reading.worst_wall().is_some_and(|wall| wall <= model);
317    let mut station_count = STATIONS;
318    let mut accepted: Option<(FittedRows, Vec<EndSurgery>, OpenRungReading)> = None;
319    // The top rung of a ladder that NEVER accepted: shipped as built, kept
320    // apart from `accepted` so it is never reported as an accepted parent.
321    let mut unaccepted: Option<(FittedRows, Vec<EndSurgery>, OpenRungReading)> = None;
322    let mut request_rungs = 0usize;
323    let mut unmet: Option<crate::BudgetReason> = None;
324    loop {
325        // A rung climbed to after acceptance is a request rung ATTEMPTED,
326        // whatever it returns.
327        if accepted.is_some() {
328            request_rungs += 1;
329        }
330        let chosen = choose(station_count);
331        let (rows, ends, reading) = match chosen {
332            Ok(chosen) => chosen,
333            // A request rung that cannot be built: the accepted rung stands.
334            Err(_) if accepted.is_some() => {
335                unmet = Some(crate::BudgetReason::Incoherent);
336                break;
337            }
338            Err(error) => return Err(error),
339        };
340        #[cfg(not(test))]
341        let reject_request = false;
342        crate::blend::carve::carve_trace(format_args!(
343            "blend open edge {}: {} stations a rung ({} in all), rails {:.3e} (bar {rail_bar:.3e}), wall {:.3e} (bar {wall_bar:.3e}){}",
344            edge.id, reading.station_count, reading.stations, reading.rails,
345            reading.worst_wall().unwrap_or(f64::INFINITY),
346            if accepted.is_some() { ", a request rung" } else { "" }
347        ));
348        let accepted_now = accepts(&reading) && !reject_request;
349        if accepted.is_none() {
350            if accepted_now {
351                let met = !wall_check || meets_model(&reading);
352                accepted = Some((rows, ends, reading));
353                if met {
354                    break;
355                }
356            } else if station_count < MAX_OPEN_STATIONS {
357                station_count *= 2;
358                continue;
359            } else {
360                crate::blend::record_blend_note(format!(
361                    "blend: open edge {} at {} stations a rung ({} in all) — the top of the open march's \
362                     ladder — still leaves its rails {:.3e} from their carriers (bar {rail_bar:.3e}) or its \
363                     wall off the rolling ball (bar {wall_bar:.3e}); the wall ships as built, unaccepted",
364                    edge.id, reading.station_count, reading.stations, reading.rails
365                ));
366                unaccepted = Some((rows, ends, reading));
367                break;
368            }
369        } else {
370            if !accepted_now {
371                unmet = Some(crate::BudgetReason::Rejected);
372                break;
373            }
374            let met = meets_model(&reading);
375            accepted = Some((rows, ends, reading));
376            if met {
377                unmet = None;
378                break;
379            }
380        }
381        // Accepted, short of `model`: one more rung if the budget allows.
382        if station_count < MAX_OPEN_STATIONS {
383            station_count *= 2;
384        } else {
385            unmet = Some(crate::BudgetReason::StationCeiling);
386            break;
387        }
388    }
389    let (shipped_accepted, (rows, ends, reading)) = match (accepted, unaccepted) {
390        (Some(rung), _) => (true, rung),
391        (None, Some(rung)) => (false, rung),
392        (None, None) => {
393            return Err(KernelRefusal::internal(KernelStage::Refine, "open_ladder", "blend: the open ladder ended without a rung"));
394        }
395    };
396    // What the shipped wall owes, typed: an UNACCEPTED rung its measured
397    // acceptance deficit (or that a reading could not be taken); an accepted
398    // fillet short of `model` its construction request.
399    let report: Option<(crate::BudgetReason, f64, f64, String)> = if !shipped_accepted {
400        Some(acceptance_deficit(&reading, rail_bar, wall_bar, wall_check, reading.rails_read(), "no rung of the open ladder was accepted"))
401    } else if wall_check && !meets_model(&reading) {
402        let reason = unmet.unwrap_or(crate::BudgetReason::StationCeiling);
403        // An accepted rung's every wall interval was read (acceptance needs it).
404        let declared = reading.worst_wall().unwrap_or(f64::INFINITY);
405        Some((reason, model, declared, String::new()))
406    } else {
407        None
408    };
409
410    let [start_end, finish_end] = match <[EndSurgery; 2]>::try_from(ends) {
411        Ok(pair) => pair,
412        Err(_) => return Err(KernelRefusal::internal(KernelStage::Sew, "open_surgery_ends", "blend: open surgery needs exactly two ends")),
413    };
414    // A crossing that only resolved on a looser rung of the tolerance ladder
415    // builds something master refused outright, so it must earn its answer
416    // (see [`SpokeCrossings`]).
417    let mut crossings = SpokeCrossings::default();
418    crossings.note(start_end.escalated || finish_end.escalated);
419    let mut result = solid.clone();
420    let mut take_id = fresh_id_source(solid);
421    let sewn = build_open_surgery(
422        solid,
423        &mut result,
424        &mut take_id,
425        edge,
426        &first_mate,
427        &second_mate,
428        rows,
429        [EndPlan::Free(start_end), EndPlan::Free(finish_end)],
430        name,
431    )?;
432    prune_orphan_vertices(&mut result);
433    // Extended end boundaries can leave a finite planar chart. Rebuild those
434    // charts before validating the surgery, rather than rejecting a correct
435    // edge because its projected pcurve was clamped to the old rectangle.
436    crate::blend::fit_planar_charts_to_trims(solid, &mut result)?;
437    check_snap_closure(solid, &result, sewn.snap)?;
438    let built = crossings.gate(result)?;
439    // The wall AS SEWN: the surgery may transpose the face (an exact
440    // extrusion), and a report is matched to its face by exact surface.
441    let sewn_surface = built
442        .shells
443        .iter()
444        .flat_map(|shell| &shell.faces)
445        .find(|face| face.id == sewn.blend_face_id)
446        .map(|face| face.surface.clone())
447        .ok_or(KernelRefusal::internal(KernelStage::Sew, "open_blend_face", "blend: the sewn open blend face is not in the built body"))?;
448    // A wall that SHIPS unaccepted, or short of its construction request,
449    // says so, typed, on the built body's wall (exact name and sewn surface).
450    if let Some((reason, bar, measured, deficit)) = report {
451        // The budget is the open march's GLOBAL station ladder (STATIONS
452        // doubling to MAX_OPEN_STATIONS), not local rounds: for a request,
453        // the rungs ATTEMPTED past the accepted one (a refused one included);
454        // for an unaccepted rung, the rungs climbed past the first. Each rung
455        // also ran its own local rail refinement, named in the detail.
456        let rungs_used = if shipped_accepted { request_rungs } else { (reading.station_count / STATIONS).trailing_zeros() as usize };
457        let mut detail = format!(
458            "the shipped rung's local rail refinement ended {:?} with {} stations inserted",
459            reading.refine_exit, reading.inserted
460        );
461        if !deficit.is_empty() {
462            detail = format!("{deficit}; {detail}");
463        }
464        crate::blend::record_wall_model_report(crate::blend::WallModelReport {
465            name: name.map(str::to_string),
466            surface: sewn_surface,
467            request: bar,
468            residual: measured,
469            detail: Some(detail),
470            budget: crate::ApproximationBudget {
471                reason,
472                rounds_used: rungs_used,
473                rounds_limit: OPEN_REQUEST_RUNGS,
474                stations: reading.stations,
475                station_limit: REFINE_STATION_FACTOR * (MAX_OPEN_STATIONS + 1),
476                mechanism: crate::BudgetMechanism::StationRungs,
477                measured_component: crate::MeasuredComponent::Wall,
478                unread: 0,
479            },
480        });
481    }
482    Ok(built)
483}
484
485/// An UNACCEPTED shipped rung's deficit, typed: `Unread` when any reading
486/// acceptance needs could not be taken (a non-finite rail, an empty shipped
487/// window, an unread or missing wall interval), else `Unaccepted`; the
488/// measured value and its bar are the readable component worst against its
489/// bar (rails against `rail_bar`, the wall against `wall_bar`; 0 against
490/// `rail_bar` when nothing could be read), always finite. The text names both
491/// readings against their bars, after `what` (what failed acceptance: the
492/// open ladder's every rung, or a network stripe's shipped windows).
493/// `rails_read` is the caller's verdict on whether the rails were READ (the
494/// open lane: [`OpenRungReading::rails_read`]; a network stripe also counts a
495/// validated collapsed rail as read with no samples).
496pub(in crate::blend) fn acceptance_deficit(
497    reading: &OpenRungReading,
498    rail_bar: f64,
499    wall_bar: f64,
500    wall_check: bool,
501    rails_read: bool,
502    what: &str,
503) -> (crate::BudgetReason, f64, f64, String) {
504    let rails = (rails_read && reading.rails.is_finite() && reading.rails >= 0.0).then_some(reading.rails);
505    let wall = if wall_check { reading.worst_wall() } else { None };
506    let unread = rails.is_none() || (wall_check && wall.is_none());
507    let mut worst = (0.0_f64, rail_bar);
508    for (value, bar) in [(rails, rail_bar), (wall, wall_bar)] {
509        if let Some(value) = value {
510            if value / bar > worst.0 / worst.1 {
511                worst = (value, bar);
512            }
513        }
514    }
515    let rail_text = match rails {
516        Some(value) => format!("rails {value:.3e} from their carriers (bar {rail_bar:.3e})"),
517        None => format!(
518            "rails UNREAD ({:?} over {} + {} samples) against bar {rail_bar:.3e}",
519            reading.rails, reading.rail_samples[0], reading.rail_samples[1]
520        ),
521    };
522    let wall_text = match (wall_check, wall) {
523        (false, _) => "the wall not judged (no constant-radius fillet provenance)".to_string(),
524        (true, Some(value)) => format!("wall {value:.3e} off the rolling ball (bar {wall_bar:.3e})"),
525        (true, None) => format!(
526            "wall UNREAD on {} of {} intervals against bar {wall_bar:.3e}{}",
527            reading.walls.iter().filter(|wall| !matches!(wall, Some(value) if value.is_finite())).count(),
528            reading.walls.len(),
529            reading.first_unread.as_deref().map(|why| format!(" (first: {why})")).unwrap_or_default()
530        ),
531    };
532    let reason = if unread { crate::BudgetReason::Unread } else { crate::BudgetReason::Unaccepted };
533    (reason, worst.1, worst.0, format!("{what}: {rail_text}, {wall_text}"))
534}
535
536/// Section probes per open wall interval (k/8 of the section), and centres
537/// per interval (probes at the even ones), as the chains read their walls.
538const OPEN_WALL_SECTIONS: usize = 8;
539pub(in crate::blend) const OPEN_WALL_CENTRES: usize = 32;
540/// The rungs the construction request may climb past the first accepted one:
541/// the open march's own ladder, STATIONS doubling to MAX_OPEN_STATIONS.
542pub(in crate::blend) const OPEN_REQUEST_RUNGS: usize = (MAX_OPEN_STATIONS / STATIONS).trailing_zeros() as usize;
543
544/// One open rung's measurement over what it SHIPS: its rung, its station
545/// count (refinement included), the rails' worst distance from their
546/// carriers over each rail's own crossing window and the samples read on
547/// each (0: no window), each wall interval's declared reading (`None`:
548/// unreadable) over the windows' envelope, and how the rung's own LOCAL rail
549/// refinement ended (its exit and the stations it inserted).
550#[derive(Clone, Debug)]
551pub(in crate::blend) struct OpenRungReading {
552    pub(in crate::blend) station_count: usize,
553    pub(in crate::blend) stations: usize,
554    pub(in crate::blend) rails: f64,
555    pub(in crate::blend) rail_samples: [usize; 2],
556    pub(in crate::blend) walls: Vec<Option<f64>>,
557    /// The first unread wall interval and why (diagnostic; `None` when every
558    /// interval read or the wall was not judged).
559    pub(in crate::blend) first_unread: Option<String>,
560    pub(in crate::blend) refine_exit: crate::blend::stations::StationRefineExit,
561    pub(in crate::blend) inserted: usize,
562}
563
564impl OpenRungReading {
565    /// Every rail READ: a finite, nonnegative worst distance from samples on
566    /// both rails' shipped windows. A NaN, an infinity (an unreadable foot)
567    /// or an empty window is never a reading.
568    pub(in crate::blend) fn rails_read(&self) -> bool {
569        self.rails.is_finite() && self.rails >= 0.0 && self.rail_samples.iter().all(|&samples| samples > 0)
570    }
571
572    /// Every wall interval READ (and at least one): `None` when any is not.
573    pub(in crate::blend) fn worst_wall(&self) -> Option<f64> {
574        if self.walls.is_empty() {
575            return None;
576        }
577        self.walls.iter().try_fold(0.0_f64, |worst, wall| match wall {
578            Some(declared) if declared.is_finite() && *declared >= 0.0 => Some(worst.max(*declared)),
579            _ => None,
580        })
581    }
582}
583
584/// The shipped window `[low, high]` of one rail between its two crossing
585/// parameters, within the rows' parameters (the surgery refuses a crossing
586/// outside them; the reading only never indexes past them). `None` when the
587/// window is empty or not finite: nothing ships there that could be read.
588pub(in crate::blend) fn shipped_window(parameters: &[f64], a: f64, b: f64) -> Option<[f64; 2]> {
589    let (&first, &last) = (parameters.first()?, parameters.last()?);
590    let (low, high) = (a.min(b).max(first), a.max(b).min(last));
591    (low.is_finite() && high.is_finite() && low < high).then_some([low, high])
592}
593
594/// The station interval holding `u` and `u`'s fraction of it.
595fn interval_at(parameters: &[f64], u: f64) -> Option<(usize, f64)> {
596    let last = parameters.len().checked_sub(2)?;
597    let interval = parameters.partition_point(|&parameter| parameter <= u).saturating_sub(1).min(last);
598    let (from, to) = (parameters[interval], parameters[interval + 1]);
599    (to > from).then(|| (interval, ((u - from) / (to - from)).clamp(0.0, 1.0)))
600}
601
602/// A point of `surface` and its unit normal when the surface is AFFINE in
603/// (u, v), its extension included: a plane (`analytic`) of degree 1 × 1 whose
604/// 2 × 2 net is a parallelogram with equal weights, to `1e-12·(1 + scale)`.
605/// Every point of such a surface, and of its linear extension, lies on the one
606/// plane through the corner with that normal.
607fn affine_plane(surface: &NurbsSurface) -> Option<(Vec3, Vec3)> {
608    let (origin, _, _) = affine_plane_frame(surface)?;
609    // The normal off the net's own corner differences.
610    let net = &surface.control_points;
611    let [p00, p01, p10] = [net[0][0].point().ok()?, net[0][1].point().ok()?, net[1][0].point().ok()?];
612    Some((origin, p10.sub(p00).cross(p01.sub(p00)).normalized().ok()?))
613}
614
615/// [`affine_plane`]'s surface as `S(u, v) = origin + (u − u₀)·s_u + (v − v₀)·s_v`:
616/// the net's corner and the two constant partial derivatives.
617pub(in crate::blend) fn affine_plane_frame(surface: &NurbsSurface) -> Option<(Vec3, Vec3, Vec3)> {
618    if !matches!(surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) || surface.degree_u != 1 || surface.degree_v != 1 {
619        return None;
620    }
621    let net = &surface.control_points;
622    if net.len() != 2 || net.iter().any(|row| row.len() != 2) {
623        return None;
624    }
625    let weight = net[0][0].w;
626    if !(weight > 0.0) || net.iter().flatten().any(|point| point.w != weight) {
627        return None;
628    }
629    let [p00, p01, p10, p11] = [net[0][0].point().ok()?, net[0][1].point().ok()?, net[1][0].point().ok()?, net[1][1].point().ok()?];
630    let scale = [p00, p01, p10, p11].iter().fold(0.0f64, |worst, point| worst.max(point.length()));
631    if p11.sub(p10).sub(p01.sub(p00)).length() > 1e-12 * (1.0 + scale) {
632        return None;
633    }
634    let [u0, u1] = surface.domain_u().ok()?;
635    let [v0, v1] = surface.domain_v().ok()?;
636    if !(u1 > u0 && v1 > v0) {
637        return None;
638    }
639    Some((p00, p10.sub(p00).scale(1.0 / (u1 - u0)), p01.sub(p00).scale(1.0 / (v1 - v0))))
640}
641
642/// Whether `curve` is AFFINE in its parameter: degree 1, two control points of
643/// equal weight (a `make_line`).
644fn affine_curve(curve: &NurbsCurve) -> bool {
645    curve.degree == 1
646        && curve.control_points.len() == 2
647        && curve.control_points[0].w > 0.0
648        && curve.control_points[0].w == curve.control_points[1].w
649}
650
651/// The worst distance of an affine rail from an affine carrier over `window`,
652/// read at the window's two ends: the signed distance is affine in the rail
653/// parameter, so its magnitude is convex and its maximum is at an end. `None`
654/// when either is not affine (the sampled reader's), or an end will not
655/// evaluate.
656pub(in crate::blend) fn affine_rail_standoff(rail: &NurbsCurve, carrier: &NurbsSurface, window: [f64; 2]) -> Option<f64> {
657    if !affine_curve(rail) {
658        return None;
659    }
660    let (origin, normal) = affine_plane(carrier)?;
661    let mut worst = 0.0f64;
662    for u in window {
663        let point = rail.evaluate(u).ok()?;
664        let off = point.sub(origin).dot(normal).abs();
665        if !off.is_finite() {
666            return None;
667        }
668        worst = worst.max(off);
669    }
670    Some(worst)
671}
672
673/// Lane N row 4 (2026-10-28): the exact revolution rows' reads in closed
674/// form. `BREP_EXACT_REVOLUTION_READS=1`/`on` turns them on, `=0`/`off`
675/// off; ON by default since lane N's promotion (2026-10-28).
676const EXACT_REVOLUTION_READS_DEFAULT: bool = true;
677
678pub(in crate::blend) fn exact_revolution_reads_on() -> bool {
679    switch!(live "BREP_EXACT_REVOLUTION_READS", EXACT_REVOLUTION_READS_DEFAULT)
680}
681
682
683/// A bound on `|S(pcurve(s)) − rail(s)|` over the whole parameter range when
684/// the shipped pair is an exact revolution row's (`exact_revolution_rows`):
685///
686/// * on the REVOLUTION carrier the pcurve is a uv line along one coordinate
687///   and the rail is the carrier's parallel circle at the held coordinate,
688///   continued to the line's range along its own conic pieces
689///   (`extend_conic_ends`) and re-parameterised to `[0, 1]`; that curve is
690///   rebuilt here from the pcurve's two ends and compared with the rail net
691///   for net — identical bases, so the homogeneous control differences
692///   bound the curves everywhere (`net_bound`);
693/// * on an AFFINE plane the pcurve carries the rail's own knots and the
694///   chart images of the rail's control points; the plane's image of the
695///   pcurve net is compared with the rail net the same way.
696///
697/// `None` when the pair is neither (the sampled read runs). The rail's
698/// standoff from the carrier and the pcurve's miss are each at most the
699/// bound (a point's distance to a surface is at most its distance to any
700/// point of it; the miss adds the standoff once more), so a bound within a
701/// third of the pcurve floor stands the trim by the march trim's own rule.
702pub(in crate::blend) fn exact_revolution_read_bound(rail: &NurbsCurve, carrier: &NurbsSurface, pcurve: &NurbsCurve) -> Option<f64> {
703    if let Some((origin, s_u, s_v)) = affine_plane_frame(carrier) {
704        // The plane's image of the pcurve net, weight for weight.
705        if pcurve.degree != rail.degree || pcurve.knots != rail.knots || pcurve.control_points.len() != rail.control_points.len() {
706            return None;
707        }
708        let ([u0, _], [v0, _]) = (carrier.domain_u().ok()?, carrier.domain_v().ok()?);
709        let image: Vec<Vec4> = pcurve
710            .control_points
711            .iter()
712            .map(|control| {
713                let (u, v) = (control.x / control.w, control.y / control.w);
714                let point = origin.add(s_u.scale(u - u0)).add(s_v.scale(v - v0));
715                Vec4 { x: point.x * control.w, y: point.y * control.w, z: point.z * control.w, w: control.w }
716            })
717            .collect();
718        return crate::blend::stations::net_bound(&rail.control_points, &image);
719    }
720    if !matches!(carrier.analytic(), Some(crate::AnalyticSurface::RuledRevolution { .. } | crate::AnalyticSurface::Revolution { .. } | crate::AnalyticSurface::Torus { .. } | crate::AnalyticSurface::Sphere { .. })) {
721        return None;
722    }
723    if !affine_curve(pcurve) {
724        return None;
725    }
726    let [q0, q1] = pcurve.domain().ok()?;
727    let (a, b) = (pcurve.evaluate(q0).ok()?, pcurve.evaluate(q1).ok()?);
728    let ([u0, u1], [v0, v1]) = (carrier.domain_u().ok()?, carrier.domain_v().ok()?);
729    let (circle, from, to) = if a.y.to_bits() == b.y.to_bits() && a.x != b.x && a.y >= v0 && a.y <= v1 {
730        (carrier.iso_curve_v(a.y).ok()?, a.x, b.x)
731    } else if a.x.to_bits() == b.x.to_bits() && a.y != b.y && a.x >= u0 && a.x <= u1 {
732        (carrier.iso_curve_u(a.x).ok()?, a.y, b.y)
733    } else {
734        return None;
735    };
736    let [c0, c1] = circle.domain().ok()?;
737    let reversed = to < from;
738    let circle = if reversed { circle.reversed().ok()? } else { circle };
739    let on_curve = |along: f64| if reversed { c0 + c1 - along } else { along };
740    let (lo, hi) = (on_curve(from), on_curve(to));
741    if !(hi > lo) {
742        return None;
743    }
744    let segment = super::support::extend_conic_ends(&circle, lo, hi).ok()?;
745    let [r0, r1] = segment.domain().ok()?;
746    let degree = segment.degree;
747    let mut knots = segment.knots.clone();
748    for knot in knots.iter_mut() {
749        *knot = ((*knot - r0) / (r1 - r0)).clamp(0.0, 1.0);
750    }
751    for knot in knots.iter_mut().take(degree + 1) {
752        *knot = 0.0;
753    }
754    let count = knots.len();
755    for knot in knots.iter_mut().skip(count - degree - 1) {
756        *knot = 1.0;
757    }
758    if rail.degree != degree || rail.knots != knots || rail.control_points.len() != segment.control_points.len() {
759        return None;
760    }
761    crate::blend::stations::net_bound(&rail.control_points, &segment.control_points)
762}
763
764/// Each shipped rail's worst distance from its carrier over ITS OWN window
765/// ([`shipped_window`]): both window ends exactly and the quarter points of
766/// every station span inside it, each against the carrier's EXTENSION
767/// (`extended_foot_distance`, seeded by the stations' own contact uv) --
768/// a finite planar chart clamps its projection, so retained overshoot past a
769/// vertex would read a miss that is not there. `(worst, samples per rail)`;
770/// any unreadable sample (a failed evaluation, an infinite foot) makes the
771/// worst NaN, which [`OpenRungReading::rails_read`] never admits.
772pub(in crate::blend) fn rails_on_shipped_windows(
773    rows: &FittedRows,
774    parameters: &[f64],
775    stations: &[Station],
776    carriers: [&NurbsSurface; 2],
777    windows: [Option<[f64; 2]>; 2],
778) -> (f64, [usize; 2]) {
779    read_rail_windows([&rows.cr, &rows.cs], parameters, stations, carriers, windows,
780        rows.exact_extrusion, certified_rail_bounds(rows, carriers), None)
781}
782
783/// An exact revolution row's rails, bounded in closed form
784/// (`exact_revolution_read_bound`) when the reads lane is on: the standoff
785/// over any window is at most the bound.
786fn certified_rail_bounds(rows: &FittedRows, carriers: [&NurbsSurface; 2]) -> [Option<f64>; 2] {
787    if rows.revolution_axis.is_none() || !exact_revolution_reads_on() {
788        return [None, None];
789    }
790    [
791        exact_revolution_read_bound(&rows.cr, carriers[0], &rows.cr_pcurve),
792        exact_revolution_read_bound(&rows.cs, carriers[1], &rows.cs_pcurve),
793    ]
794}
795
796fn read_rail_windows(
797    rails: [&NurbsCurve; 2], parameters: &[f64], stations: &[Station],
798    carriers: [&NurbsSurface; 2], windows: [Option<[f64; 2]>; 2], affine: bool,
799    certified: [Option<f64>; 2],
800    mut memo: Option<&mut RailFeet>,
801) -> (f64, [usize; 2]) {
802    let mut worst = 0.0_f64;
803    let mut samples = [0usize; 2];
804    for (side, (rail, carrier)) in [(rails[0], carriers[0]), (rails[1], carriers[1])].into_iter().enumerate() {
805        let Some([low, high]) = windows[side] else { continue };
806        // An exact extrusion's straight rail on a plane: the ends carry the
807        // worst (`affine_rail_standoff`), the samples between them cannot.
808        if let Some(off) = affine.then(|| affine_rail_standoff(rail, carrier, [low, high])).flatten() {
809            crate::blend::record_count("count.read.affine_rails", 1);
810            samples[side] += 2;
811            if !worst.is_nan() && off > worst {
812                worst = off;
813            }
814            continue;
815        }
816        // An exact revolution row's rail: its net bound against the carrier's
817        // own circle (or the plane's image of its pcurve) is its standoff's
818        // bound over every window.
819        if let Some(bound) = certified[side] {
820            crate::blend::record_count("count.read.revolution_rails", 1);
821            samples[side] += 1;
822            if !worst.is_nan() && bound > worst {
823                worst = bound;
824            }
825            continue;
826        }
827        let mut at = vec![low, high];
828        for pair in parameters.windows(2) {
829            for fraction in [0.25, 0.5, 0.75] {
830                let u = pair[0] + (pair[1] - pair[0]) * fraction;
831                if u > low && u < high {
832                    at.push(u);
833                }
834            }
835        }
836        for u in at {
837            let cached = memo.as_ref().and_then(|memo| memo.values[side].get(&u.to_bits()).copied());
838            let off = if let Some(off) = cached {
839                if let Some(memo) = memo.as_mut() { memo.hits += 1; }
840                crate::blend::record_count("count.read.rail_foot_reused", 1);
841                off
842            } else {
843            if let Some(memo) = memo.as_mut() {
844                memo.reads += 1;
845                crate::blend::record_count("count.read.rail_foot_fresh", 1);
846            }
847            let off = interval_at(parameters, u)
848                .and_then(|(interval, fraction)| {
849                    let (left, right) = (&stations[interval], &stations[interval + 1]);
850                    let (a, b) = if side == 0 { (left.uv1, right.uv1) } else { (left.uv2, right.uv2) };
851                    let seed = [a[0] + fraction * (b[0] - a[0]), a[1] + fraction * (b[1] - a[1])];
852                    let point = rail.evaluate(u).ok()?;
853                    crate::blend::stations::extended_foot_distance(carrier, point, seed).ok()
854                })
855                .filter(|off| off.is_finite())
856                .unwrap_or(f64::NAN);
857            if off.is_finite() {
858                if let Some(memo) = memo.as_mut() { memo.values[side].insert(u.to_bits(), off); }
859            }
860            off
861            };
862            samples[side] += 1;
863            if !worst.is_nan() && (off.is_nan() || off > worst) {
864                worst = off;
865            }
866        }
867    }
868    (worst, samples)
869}
870
871/// A construction-local rail reader. It owns an immutable snapshot of every
872/// input to a foot reading; only the requested windows can change. Native
873/// parameter bits identify a sample, so nearby endpoints never share a foot.
874/// The network keeps this reader from its chosen rung through shipped-window
875/// acceptance, then drops it. Failed/nonfinite feet are never reused.
876pub(in crate::blend) struct RailWindowReader {
877    rails: [NurbsCurve; 2],
878    carriers: [NurbsSurface; 2],
879    parameters: Vec<f64>,
880    stations: Vec<Station>,
881    affine: bool,
882    certified: [Option<f64>; 2],
883    feet: RailFeet,
884}
885
886#[derive(Default)]
887struct RailFeet {
888    values: [rustc_hash::FxHashMap<u64, f64>; 2],
889    reads: u64,
890    hits: u64,
891}
892
893impl RailWindowReader {
894    pub(in crate::blend) fn new(rows: &FittedRows, parameters: &[f64], stations: &[Station], carriers: [&NurbsSurface; 2]) -> Self {
895        Self {
896            rails: [rows.cr.clone(), rows.cs.clone()],
897            carriers: [carriers[0].clone(), carriers[1].clone()],
898            parameters: parameters.to_vec(), stations: stations.to_vec(),
899            affine: rows.exact_extrusion, certified: certified_rail_bounds(rows, carriers), feet: RailFeet::default(),
900        }
901    }
902
903    pub(in crate::blend) fn read(&mut self, windows: [Option<[f64; 2]>; 2]) -> (f64, [usize; 2]) {
904        read_rail_windows([&self.rails[0], &self.rails[1]], &self.parameters, &self.stations,
905            [&self.carriers[0], &self.carriers[1]], windows, self.affine, self.certified, Some(&mut self.feet))
906    }
907}
908
909pub(in crate::blend) fn network_rail_reuse_on() -> bool {
910    // The private halving diagnostic compares every requested foot against
911    // its reference algorithm, including repeats. Preserve that coverage.
912    std::env::var("BREP_NETWORK_RAIL_REUSE").map_or(true, |value| value != "0" && value != "off")
913}
914
915/// The JUNCTION stencil across the station between interval `left` and
916/// `left + 1`: `left_nodes` (33 exact centres of `left`) from node 16 to 32,
917/// then `right_nodes` (33 of `left + 1`) from node 1 to 16, the shared
918/// station at node 16. Its native abscissae come from `station_ts` (the
919/// edge parameters the centres were solved at): `None` when the two native
920/// widths are bitwise equal -- uniform nodes, read by the ordinary reader --
921/// else each node's t, interior nodes by the dense solves' own arithmetic
922/// t_i + (t_{i+1} − t_i)·j/32 and the shared station at its STORED t. Err
923/// when a station t is not finite or a width is not strictly positive.
924pub(in crate::blend) fn junction_stencil(
925    left_nodes: &[Vec3],
926    right_nodes: &[Vec3],
927    station_ts: &[f64],
928    left: usize,
929) -> Result<(Vec<Vec3>, Option<Vec<f64>>), String> {
930    let half = OPEN_WALL_CENTRES / 2;
931    if left_nodes.len() != OPEN_WALL_CENTRES + 1 || right_nodes.len() != OPEN_WALL_CENTRES + 1 || left + 2 >= station_ts.len() {
932        return Err(format!("interval {left}: junction needs two {}-node intervals and their three station parameters", OPEN_WALL_CENTRES + 1));
933    }
934    let (t0, t1, t2) = (station_ts[left], station_ts[left + 1], station_ts[left + 2]);
935    let (w_left, w_right) = (t1 - t0, t2 - t1);
936    if !(t0.is_finite() && t1.is_finite() && t2.is_finite() && w_left > 0.0 && w_right > 0.0 && w_left.is_finite() && w_right.is_finite()) {
937        return Err(format!("interval {left}: junction station parameters {t0}, {t1}, {t2} are not finite and strictly increasing"));
938    }
939    let nodes: Vec<Vec3> = left_nodes[half..].iter().chain(&right_nodes[1..=half]).copied().collect();
940    if w_left.to_bits() == w_right.to_bits() {
941        return Ok((nodes, None));
942    }
943    let abscissae: Vec<f64> = (half..=OPEN_WALL_CENTRES)
944        .map(|j| if j == OPEN_WALL_CENTRES { t1 } else { t0 + w_left * j as f64 / OPEN_WALL_CENTRES as f64 })
945        .chain((1..=half).map(|j| t1 + w_right * j as f64 / OPEN_WALL_CENTRES as f64))
946        .collect();
947    Ok((nodes, Some(abscissae)))
948}
949
950/// One wall probe on a stencil: the ordinary uniform reader when it has no
951/// native abscissae (an interval's own nodes, or a junction of equal native
952/// widths), the native-abscissa reader when it has them.
953pub(in crate::blend) fn read_on_stencil(point: Vec3, nodes: &[Vec3], abscissae: Option<&[f64]>, step: usize, radius: f64) -> Result<(f64, f64), String> {
954    match abscissae {
955        None => crate::blend::chain::declared_wall_probe_why(point, nodes, step, radius),
956        Some(ts) => crate::blend::chain::declared_wall_probe_at_why(point, nodes, ts, step, radius),
957    }
958}
959
960/// Every interval's largest DECLARED wall reading (`chain::declared_wall_probe`,
961/// reading + uncertainty) on the open fillet `rows`, against the exact ball
962/// centres the march solved at j/32 of each interval ([`OpenDenseCentres`]),
963/// or, for each unread interval, WHY: its station
964/// interval and which component failed (no dense row, a dense row of the
965/// wrong size, an exact centre the march did not solve, a wall point the
966/// surface would not evaluate, a probe the declared reader declined, no probe
967/// in the shipped part, or a non-finite reading). The cause is diagnostic.
968///
969/// Read on the DECLARED SHIPPED REGION `window` only: an interval it overlaps
970/// is probed at its even stencil fractions that lie inside the window and at
971/// each window end inside the interval; a probe outside the window is not on
972/// the shipped wall and is not read. A window END whose nearest even stencil
973/// node falls outside 2..=30 -- an end within a node of the interval's own
974/// station, as the original bore's shipped spans were, 1e-16 from their
975/// vertex stations -- has its foot at the interval's end node, where
976/// `crate::blend::chain::closed::declared_wall_probe` cannot read (the stencil
977/// cannot follow a foot out of its own interval). It is read on a JUNCTION
978/// stencil instead: the neighbouring interval's last half and this one's
979/// first half (or this one's last half and the next one's first), the same
980/// exact centres meeting at the shared station, with the probe at its
981/// middle node. Two intervals of unequal native width (local insertions)
982/// give the junction unequal node spacing, so it is then read by the
983/// native-abscissa reader (`chain::declared_wall_probe_at_why`) on the
984/// edge parameters the centres were solved at; of equal width, by the
985/// ordinary reader. With no neighbour it is read as before.
986/// The wall reading of an EXACT extrusion's rows, read directly: the wall is
987/// the ball's sweep along the centre line, so every point of the shipped
988/// surface stands exactly the radius off that line, and the reading is how
989/// far it does not. One entry per interval overlapping `window`, probes at
990/// the interval's quarters inside the window and at the window's ends, over
991/// the section at k/8 (the ball-resolve reader's sections). Never for fitted
992/// rows: those are read against the exact centres between their stations
993/// ([`open_wall_readings_why`]).
994pub(in crate::blend) fn exact_extrusion_wall_readings(
995    rows: &FittedRows,
996    parameters: &[f64],
997    window: [f64; 2],
998    radius: f64,
999) -> Vec<Result<f64, String>> {
1000    let intervals = parameters.len().saturating_sub(1);
1001    let overlapped: Vec<usize> =
1002        (0..intervals).filter(|&interval| parameters[interval + 1] > window[0] && parameters[interval] < window[1]).collect();
1003    let line = match (rows.exact_extrusion, rows.center.as_ref()) {
1004        (true, Some(center)) => center.domain().and_then(|[a, b]| Ok((center.evaluate(a)?, center.evaluate(b)?))),
1005        (false, _) => Err("the rows are not an exact extrusion".to_string()),
1006        (true, None) => Err("the exact rows carry no centre line".to_string()),
1007    };
1008    let (anchor, direction) = match line.and_then(|(a, b)| b.sub(a).normalized().map(|d| (a, d))) {
1009        Ok(line) => line,
1010        Err(error) => return overlapped.iter().map(|interval| Err(format!("interval {interval}: {error}"))).collect(),
1011    };
1012    let Ok([v_low, v_high]) = rows.surface.domain_v() else {
1013        return overlapped.iter().map(|interval| Err(format!("interval {interval}: wall surface v domain unreadable"))).collect();
1014    };
1015    overlapped
1016        .into_iter()
1017        .map(|interval| -> Result<f64, String> {
1018            let (from, to) = (parameters[interval], parameters[interval + 1]);
1019            let inside = |u: f64| u >= window[0] && u <= window[1];
1020            let mut probes: Vec<f64> =
1021                (1..4).map(|step| from + (to - from) * step as f64 / 4.0).filter(|u| inside(*u)).collect();
1022            probes.extend(window.into_iter().filter(|end| *end > from && *end < to));
1023            if probes.is_empty() {
1024                return Err(format!("interval {interval}: no probe in its shipped part of [{:.17}, {:.17}]", window[0], window[1]));
1025            }
1026            let mut worst = 0.0_f64;
1027            for u in probes {
1028                for k in 1..OPEN_WALL_SECTIONS {
1029                    let v = v_low + (v_high - v_low) * k as f64 / OPEN_WALL_SECTIONS as f64;
1030                    let point = rows.surface.evaluate(u, v).map_err(|error| format!("interval {interval}: wall point (u {u:.9}, v {v:.6}) unreadable: {error}"))?;
1031                    let offset = point.sub(anchor);
1032                    let standoff = offset.sub(direction.scale(offset.dot(direction))).length();
1033                    let reading = (standoff - radius).abs();
1034                    if !reading.is_finite() {
1035                        return Err(format!("interval {interval}: wall point (u {u:.9}, v {v:.6}) reads {reading}"));
1036                    }
1037                    worst = worst.max(reading);
1038                }
1039            }
1040            Ok(worst)
1041        })
1042        .collect()
1043}
1044
1045/// The wall reading of an EXACT REVOLUTION's rows
1046/// (`support::exact_revolution_rows`), read directly: the wall is the ball's
1047/// sweep along the centre CIRCLE, so every point of the shipped surface
1048/// stands exactly the radius off that circle, and the reading is how far it
1049/// does not. The distance to the circle is closed-form in the point's
1050/// meridian half-plane: `hypot(ρ − R_c, h − h_c)` for the point's radial
1051/// distance ρ and axial height h about the rows' axis. Same probes as
1052/// [`exact_extrusion_wall_readings`]: one entry per interval overlapping
1053/// `window`, the interval's quarters inside the window and the window's
1054/// ends, over the section at k/8.
1055pub(in crate::blend) fn exact_revolution_wall_readings(
1056    rows: &FittedRows,
1057    parameters: &[f64],
1058    window: [f64; 2],
1059    radius: f64,
1060) -> Vec<Result<f64, String>> {
1061    let intervals = parameters.len().saturating_sub(1);
1062    let overlapped: Vec<usize> =
1063        (0..intervals).filter(|&interval| parameters[interval + 1] > window[0] && parameters[interval] < window[1]).collect();
1064    let circle = match (rows.revolution_axis, rows.center.as_ref()) {
1065        (Some((origin, axis)), Some(center)) => center.domain().and_then(|[a, _]| center.evaluate(a)).map(|point| (origin, axis, point)),
1066        (None, _) => Err("the rows are not an exact revolution".to_string()),
1067        (Some(_), None) => Err("the exact rows carry no centre circle".to_string()),
1068    };
1069    let (origin, axis, centre_radius, centre_height) = match circle {
1070        Ok((origin, axis, point)) => {
1071            let offset = point.sub(origin);
1072            let height = offset.dot(axis);
1073            (origin, axis, offset.sub(axis.scale(height)).length(), height)
1074        }
1075        Err(error) => return overlapped.iter().map(|interval| Err(format!("interval {interval}: {error}"))).collect(),
1076    };
1077    let Ok([v_low, v_high]) = rows.surface.domain_v() else {
1078        return overlapped.iter().map(|interval| Err(format!("interval {interval}: wall surface v domain unreadable"))).collect();
1079    };
1080    overlapped
1081        .into_iter()
1082        .map(|interval| -> Result<f64, String> {
1083            let (from, to) = (parameters[interval], parameters[interval + 1]);
1084            let inside = |u: f64| u >= window[0] && u <= window[1];
1085            let mut probes: Vec<f64> =
1086                (1..4).map(|step| from + (to - from) * step as f64 / 4.0).filter(|u| inside(*u)).collect();
1087            probes.extend(window.into_iter().filter(|end| *end > from && *end < to));
1088            if probes.is_empty() {
1089                return Err(format!("interval {interval}: no probe in its shipped part of [{:.17}, {:.17}]", window[0], window[1]));
1090            }
1091            let mut worst = 0.0_f64;
1092            for u in probes {
1093                for k in 1..OPEN_WALL_SECTIONS {
1094                    let v = v_low + (v_high - v_low) * k as f64 / OPEN_WALL_SECTIONS as f64;
1095                    let point = rows.surface.evaluate(u, v).map_err(|error| format!("interval {interval}: wall point (u {u:.9}, v {v:.6}) unreadable: {error}"))?;
1096                    let offset = point.sub(origin);
1097                    let height = offset.dot(axis);
1098                    let radial = offset.sub(axis.scale(height)).length();
1099                    let standoff = (radial - centre_radius).hypot(height - centre_height);
1100                    let reading = (standoff - radius).abs();
1101                    if !reading.is_finite() {
1102                        return Err(format!("interval {interval}: wall point (u {u:.9}, v {v:.6}) reads {reading}"));
1103                    }
1104                    worst = worst.max(reading);
1105                }
1106            }
1107            Ok(worst)
1108        })
1109        .collect()
1110}
1111
1112pub(in crate::blend) fn open_wall_readings_why(
1113    rows: &FittedRows,
1114    parameters: &[f64],
1115    stations: &[Station],
1116    window: [f64; 2],
1117    dense: &OpenDenseCentres,
1118    radius: f64,
1119) -> Vec<Result<f64, String>> {
1120    let intervals = parameters.len().saturating_sub(1);
1121    let overlapped: Vec<usize> =
1122        (0..intervals).filter(|&interval| parameters[interval + 1] > window[0] && parameters[interval] < window[1]).collect();
1123    let Ok([v_low, v_high]) = rows.surface.domain_v() else {
1124        return overlapped.iter().map(|interval| Err(format!("interval {interval}: wall surface v domain unreadable"))).collect();
1125    };
1126    // The exact centres of one interval at j/32, its stations at both ends.
1127    let nodes_of = |interval: usize| -> Result<Vec<Vec3>, String> {
1128        let inner = dense.centres.get(interval).ok_or_else(|| format!("interval {interval}: no dense centre row"))?;
1129        if dense.subdivisions != OPEN_WALL_CENTRES || inner.len() + 1 != OPEN_WALL_CENTRES {
1130            return Err(format!("interval {interval}: dense row {} centres at {} subdivisions", inner.len(), dense.subdivisions));
1131        }
1132        let mut centres = Vec::with_capacity(OPEN_WALL_CENTRES + 1);
1133        centres.push(stations[interval].center);
1134        for (j, centre) in inner.iter().enumerate() {
1135            centres.push(centre.ok_or_else(|| format!("interval {interval}: exact centre {} of {OPEN_WALL_CENTRES} unsolved", j + 1))?);
1136        }
1137        centres.push(stations[interval + 1].center);
1138        Ok(centres)
1139    };
1140    let half = OPEN_WALL_CENTRES / 2;
1141    // The junction stencil across the station between `left` and `left + 1`:
1142    // left's nodes half..=32, then right's nodes 1..=half; the station is node
1143    // `half`. With each node's NATIVE abscissa (the edge parameter its exact
1144    // centre was solved at, `OpenDenseCentres::station_ts`), and `None` when
1145    // the two intervals' native widths are bitwise equal: the nodes are then
1146    // uniform and the ordinary reader reads them, bit for bit.
1147    let junction = |left: usize| -> Result<(Vec<Vec3>, Option<Vec<f64>>), String> {
1148        if dense.station_ts.len() != parameters.len() {
1149            return Err(format!("interval {left}: junction without the native station parameters"));
1150        }
1151        junction_stencil(&nodes_of(left)?, &nodes_of(left + 1)?, &dense.station_ts, left)
1152    };
1153    overlapped
1154        .into_iter()
1155        .map(|interval| -> Result<f64, String> {
1156            let centres = nodes_of(interval)?;
1157            let (from, to) = (parameters[interval], parameters[interval + 1]);
1158            let inside = |u: f64| u >= window[0] && u <= window[1];
1159            // (u, stencil node, the stencil: None = this interval's own;
1160            // a junction's nodes with its native abscissae when unequal).
1161            let mut probes: Vec<(f64, usize, Option<(Vec<Vec3>, Option<Vec<f64>>)>)> = (2..OPEN_WALL_CENTRES)
1162                .step_by(2)
1163                .map(|step| (from + (to - from) * step as f64 / OPEN_WALL_CENTRES as f64, step))
1164                .filter(|(u, _)| inside(*u))
1165                .map(|(u, step)| (u, step, None))
1166                .collect();
1167            for end in window {
1168                if end > from && end < to {
1169                    let fraction = (end - from) / (to - from);
1170                    let nearest = 2 * ((fraction * OPEN_WALL_CENTRES as f64 / 2.0).round() as usize);
1171                    #[cfg(not(test))]
1172                    let junction_off = false;
1173                    if junction_off {
1174                        probes.push((end, nearest.clamp(2, OPEN_WALL_CENTRES - 2), None));
1175                    } else if nearest < 2 && interval > 0 {
1176                        probes.push((end, half, Some(junction(interval - 1)?)));
1177                    } else if nearest > OPEN_WALL_CENTRES - 2 && interval + 1 < intervals {
1178                        probes.push((end, half, Some(junction(interval)?)));
1179                    } else {
1180                        probes.push((end, nearest.clamp(2, OPEN_WALL_CENTRES - 2), None));
1181                    }
1182                }
1183            }
1184            if probes.is_empty() {
1185                return Err(format!("interval {interval}: no probe in its shipped part of [{:.17}, {:.17}]", window[0], window[1]));
1186            }
1187            let mut declared = 0.0_f64;
1188            for (u, step, stencil) in probes {
1189                let (nodes, abscissae, what) = match &stencil {
1190                    Some((nodes, None)) => (nodes, None, "junction"),
1191                    Some((nodes, Some(ts))) => (nodes, Some(ts), "native-abscissa junction"),
1192                    None => (&centres, None, "interval"),
1193                };
1194                for k in 1..OPEN_WALL_SECTIONS {
1195                    let v = v_low + (v_high - v_low) * k as f64 / OPEN_WALL_SECTIONS as f64;
1196                    let point = rows.surface.evaluate(u, v).map_err(|error| format!("interval {interval}: wall point (u {u:.9}, v {v:.6}) unreadable: {error}"))?;
1197                    // The interval's own stencil reads from the probe's node,
1198                    // then (declined) from where its fraction reaches along the
1199                    // centre path (a stationary section); a junction keeps its
1200                    // own dispatch.
1201                    let read = if stencil.is_none() {
1202                        crate::blend::chain::declared_wall_probe_located_why(point, nodes, step, (u - from) / (to - from), radius)
1203                    } else {
1204                        read_on_stencil(point, nodes, abscissae.map(|ts| ts.as_slice()), step, radius)
1205                    };
1206                    let (reading, uncertainty) = read.map_err(|why| {
1207                        format!(
1208                            "interval {interval}: declared reader declined probe node {step} of the {what} stencil, section {k}/{OPEN_WALL_SECTIONS} \
1209                             (u {u:.17}): {why}"
1210                        )
1211                    })?;
1212                    declared = declared.max(reading + uncertainty);
1213                }
1214            }
1215            if declared.is_finite() { Ok(declared) } else { Err(format!("interval {interval}: non-finite reading {declared}")) }
1216        })
1217        .collect()
1218}
1219
1220
1221/// A fresh id allocator seeded past the vertex, edge, face, loop and coedge IDs.
1222/// Solid and shell IDs are outside this allocation domain. Shared by
1223/// a whole group of stripes so their vertices, edges and coedges cannot
1224/// collide.
1225pub(in crate::blend) fn fresh_id_source(solid: &BrepSolid) -> impl FnMut() -> u64 {
1226    let mut next_id = solid
1227        .vertices
1228        .iter()
1229        .map(|vertex| vertex.id)
1230        .chain(solid.edges.iter().map(|edge| edge.id))
1231        .chain(
1232            solid
1233                .shells
1234                .iter()
1235                .flat_map(|shell| &shell.faces)
1236                .flat_map(|face| {
1237                    face.loops
1238                        .iter()
1239                        .map(|loop_record| loop_record.id)
1240                        .chain(face.loops.iter().flat_map(|loop_record| {
1241                            loop_record.coedges.iter().map(|coedge| coedge.id)
1242                        }))
1243                        .chain(std::iter::once(face.id))
1244                }),
1245        )
1246        .max()
1247        .unwrap_or(0)
1248        + 1;
1249    move || {
1250        let id = next_id;
1251        next_id += 1;
1252        id
1253    }
1254}
1255
1256
1257/// May a declined support refit fall back on the march's own trim pcurve?
1258/// Only when that trim, read independently as shipped
1259/// (`read_shipped_pcurve`: miss, rail standoff, samples, worst), meets the
1260/// floor ON its rail's branch: its miss PLUS the rail's standoff from the
1261/// carrier at the trim's foot within `floor`. A trim on another branch of the
1262/// carrier tracks its own foot perfectly (miss 0) while that foot stands far
1263/// off the rail, so a miss alone would ship it; an unreadable trim never
1264/// stands.
1265pub(in crate::blend) fn march_trim_stands(read: &Result<(f64, f64, usize, f64), KernelRefusal>, floor: f64) -> bool {
1266    matches!(read, Ok((miss, standoff, _, _)) if *miss + *standoff <= floor)
1267}
1268
1269/// Slice 1b of the surgery lane: the support trim of a
1270/// straight rail on a PLANE, exact. The feet of the rail's two ends on the
1271/// plane (the kernel's closed-form projection) joined by a degree-1 pcurve
1272/// on the rail's own parameter range, so the surgery reads it at the rail's
1273/// parameter as it reads every trim; read once as shipped
1274/// (`read_shipped_pcurve`) and kept only when it stands within the pcurve
1275/// floor by the march trim's own rule (`march_trim_stands`: miss plus rail
1276/// standoff). `None` hands the trim to the refit road, as a march trim that
1277/// does not stand would be.
1278fn exact_planar_trim(rail: &NurbsCurve, surface: &NurbsSurface, d0: f64, d1: f64) -> Result<Option<NurbsCurve>, KernelRefusal> {
1279    if !matches!(surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) || !(d1 > d0) {
1280        return Ok(None);
1281    }
1282    let feet_timing = crate::blend::BlendTimer::start("timing.surgery.trim.exact.feet_ms");
1283    let mut control = Vec::with_capacity(2);
1284    for t in [d0, d1] {
1285        let point = rail.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?;
1286        let foot = crate::project_point_to_surface(surface, point).or_refuse(KernelStage::Refine, "project")?;
1287        control.push(crate::Vec4::from_point(crate::Vec3::new(foot.u, foot.v, 0.0), 1.0));
1288    }
1289    let line = NurbsCurve::new(1, vec![d0, d0, d1, d1], control).or_refuse(KernelStage::Refine, "new")?;
1290    feet_timing.stop();
1291    let read_timing = crate::blend::BlendTimer::start("timing.surgery.trim.exact.read_ms");
1292    let read = match affine_trim_read(rail, surface, &line, d0, d1) {
1293        Some(read) => {
1294            crate::blend::record_count("count.read.affine_trims", 1);
1295            Ok(read)
1296        }
1297        None => crate::blend::track_fit::read_shipped_pcurve(surface, &|t| rail.evaluate(t), &line, d0, d1),
1298    };
1299    read_timing.stop();
1300    Ok(march_trim_stands(&read, crate::pcurve::PCURVE_REFINEMENT_TOLERANCE).then_some(line))
1301}
1302
1303/// [`read_shipped_pcurve`](crate::blend::track_fit::read_shipped_pcurve)'s
1304/// `(miss, standoff, samples, worst)` for a degree-1 `pcurve` on an AFFINE
1305/// plane against an affine rail, read at `d0` and `d1` only: the pcurve's
1306/// image, the rail and the rail's foot on the plane are all affine in the
1307/// rail parameter, so the miss (image to foot) and the standoff (rail to foot)
1308/// are norms of affine functions, convex, and largest at an end. `None` when
1309/// any of the three is not affine, or an end will not evaluate.
1310fn affine_trim_read(rail: &NurbsCurve, surface: &NurbsSurface, pcurve: &NurbsCurve, d0: f64, d1: f64) -> Option<(f64, f64, usize, f64)> {
1311    if !affine_curve(rail) || !affine_curve(pcurve) {
1312        return None;
1313    }
1314    let (origin, normal) = affine_plane(surface)?;
1315    let (mut miss, mut standoff, mut worst) = (0.0f64, 0.0f64, d0);
1316    for t in [d0, d1] {
1317        let point = rail.evaluate(t).ok()?;
1318        let foot = point.sub(normal.scale(point.sub(origin).dot(normal)));
1319        let uv = pcurve.evaluate(t).ok()?;
1320        let image = crate::blend::track_fit::carrier_point(surface, uv.x, uv.y).ok()?;
1321        let (residual, off) = (image.sub(foot).length(), point.sub(foot).length());
1322        if !(residual.is_finite() && off.is_finite()) {
1323            return None;
1324        }
1325        if residual > miss {
1326            (miss, worst) = (residual, t);
1327        }
1328        standoff = standoff.max(off);
1329    }
1330    Some((miss, standoff, 2, worst))
1331}
1332
1333/// Sew ONE stripe into `result`.
1334///
1335/// `solid` is the ORIGINAL topology every stripe was marched against (the
1336/// row-coincidence detection reads it); `result` is the shared evolving
1337/// solid, and `take_id` the shared id allocator — a group of stripes meeting
1338/// at a corner must create their rim vertices and cross-section arcs from one
1339/// counter, and must see each other's work.
1340///
1341/// Each end is either free (terminate on the face across the corner) or a
1342/// corner stop; see [`EndPlan`].  Pruning orphaned vertices is the caller's
1343/// job, once, after every stripe of the group is in.
1344pub(in crate::blend) fn build_open_surgery(
1345    solid: &BrepSolid,
1346    result: &mut BrepSolid,
1347    take_id: &mut dyn FnMut() -> u64,
1348    edge: &EdgeRecord,
1349    first: &BlendMate,
1350    second: &BlendMate,
1351    rows: FittedRows,
1352    ends: [EndPlan; 2],
1353    name: Option<&str>,
1354) -> Result<SewnStripe, KernelRefusal> {
1355    build_open_surgery_with_tail(solid, result, take_id, edge, first, second, rows, ends, name, [None, None])
1356}
1357
1358/// [`build_open_surgery`] for a stripe whose finish end rolled onto tangent
1359/// neighbours (`crate::blend::rollover::stopped_end_tail`, switch, default
1360/// off): after the pristine sewing, each rolled side's rail is split at its
1361/// crossing vertex, the part past it and the cap's leg move from the mate's
1362/// loop into the neighbour's — where they replace the run of the crossed
1363/// tangent edge from the crossing to the sharp vertex, which is deleted —
1364/// and the part past it gets its pcurve on the neighbour. The mate keeps the
1365/// rail up to the crossing and the rest of the tangent edge. With no rolled
1366/// side the sewing is exactly [`build_open_surgery`]'s.
1367#[allow(clippy::too_many_arguments)]
1368pub(in crate::blend) fn build_open_surgery_with_tail(
1369    solid: &BrepSolid,
1370    result: &mut BrepSolid,
1371    take_id: &mut dyn FnMut() -> u64,
1372    edge: &EdgeRecord,
1373    first: &BlendMate,
1374    second: &BlendMate,
1375    rows: FittedRows,
1376    ends: [EndPlan; 2],
1377    name: Option<&str>,
1378    tail: [Option<crate::blend::rollover::TailSplice<'_>>; 2],
1379) -> Result<SewnStripe, KernelRefusal> {
1380    let [start_end, finish_end] = ends;
1381
1382    // Trim the support rows to the crossing window.
1383    // A POLE end stops EXACTLY on the row's own end (the march puts the
1384    // pole's station there and overshoots no further), so there is nothing to
1385    // split off on that side.  Only equality: a stop PAST the row's end — a
1386    // free end's crossing the rows never reached — still fails the split and
1387    // refuses, rather than building a rail out to wherever the rows stop.
1388    let trim_row = |row: &NurbsCurve, a: f64, b: f64| -> Result<NurbsCurve, KernelRefusal> {
1389        let [low, high] = row.domain().or_refuse(KernelStage::Refine, "domain")?;
1390        let tail = if a == low { row.clone() } else { row.split(a).or_refuse(KernelStage::Refine, "split")?.1 };
1391        if b == high {
1392            return Ok(tail);
1393        }
1394        let (middle, _) = tail.split(b).or_refuse(KernelStage::Refine, "split")?;
1395        Ok(middle)
1396    };
1397    let kind = |plan: &EndPlan| match plan {
1398        EndPlan::Free(_) => "free",
1399        EndPlan::Corner(_) => "corner",
1400        EndPlan::Miter(_) => "miter",
1401        EndPlan::Cap(_) => "cap",
1402    };
1403    let describe_trim = |error: KernelRefusal| {
1404        error.with_message(|error| {
1405            format!(
1406                "{error} (edge {} rows trimmed for a {} start at cr {:.6}/cs {:.6} and a {} finish \
1407                 at cr {:.6}/cs {:.6})",
1408                edge.id,
1409                kind(&start_end),
1410                start_end.cr_parameter(),
1411                start_end.cs_parameter(),
1412                kind(&finish_end),
1413                finish_end.cr_parameter(),
1414                finish_end.cs_parameter()
1415            )
1416        })
1417    };
1418    // A rail whose two stops are one point within `consumed_band` has no strip
1419    // to trim: the blend takes that mate down to a single point along this
1420    // edge.  That is a FULL-WIDTH corner — the shared face of a miter whose
1421    // radius is the side face's width, every face of a star at full width, the
1422    // middle edge of a channel whose two corner setbacks meet.  No rail edge is
1423    // built; the mate loses the blended edge instead of having it replaced, and
1424    // the rail's two rim vertices are one vertex, which the orchestrator
1425    // identifies (`SewnStripe::identified`) once every stripe is in.  A stripe
1426    // free at BOTH ends has no corner to collapse onto, so it refuses.
1427    let band = consumed_band(solid);
1428    let collapses = |row: &NurbsCurve, a: f64, b: f64| -> Result<bool, KernelRefusal> {
1429        let from = row.evaluate(a).or_refuse(KernelStage::Refine, "evaluate")?;
1430        Ok(row.evaluate(b).or_refuse(KernelStage::Refine, "evaluate")?.sub(from).length() <= band
1431            && row.evaluate(0.5 * (a + b)).or_refuse(KernelStage::Refine, "evaluate")?.sub(from).length() <= band)
1432    };
1433    let cr_collapsed = collapses(&rows.cr, start_end.cr_parameter(), finish_end.cr_parameter())?;
1434    let cs_collapsed = collapses(&rows.cs, start_end.cs_parameter(), finish_end.cs_parameter())?;
1435    if cr_collapsed || cs_collapsed {
1436        let unsupported = if start_end.free().is_some() && finish_end.free().is_some() {
1437            Some("neither end is a corner")
1438        } else if first.face.id == second.face.id {
1439            Some("both rails lie on one face")
1440        } else if matches!(start_end, EndPlan::Cap(_)) || matches!(finish_end, EndPlan::Cap(_)) {
1441            Some("a capped end has no corner to share the point with")
1442        } else {
1443            None
1444        };
1445        if let Some(reason) = unsupported {
1446            return Err(KernelRefusal::unsupported(KernelStage::Sew, super::RAIL_COLLAPSE_WHAT, format!(
1447                "{RAIL_COLLAPSE_UNSUPPORTED} edge {}'s rail shrinks to a point and {reason}",
1448                edge.id
1449            )));
1450        }
1451    }
1452    // The support pcurve the rows carry interpolates the stations' (u, v) and
1453    // is read nowhere between them: on the 20-degree crossing's notched open
1454    // exit arc it stood 2.98e-5 off the rail it trims (q1 = 9cd8c3163 + the
1455    // section-fit fix, read against the exact cylinders). Inside the crossing
1456    // window — on the face, never on a carrier's extension — it is refitted
1457    // to the trimmed rail's own projected track at the pcurve floor and read
1458    // again as shipped (`refit_closed_support_pcurve`, the closed edge's).
1459    // A rail that overruns a PLANE carrier's chart (the rib-base fin top's
1460    // rails run 0.303 past it) is on the plane's extension, which the chart
1461    // clamps: there the refit and both reads would measure the clamp, and the
1462    // trim is instead rebuilt from its edge on the widened chart and verified
1463    // at the floor by `fit_planar_charts_to_trims`, which every lane that
1464    // sews these stripes runs.
1465    let trim_rail = |collapsed: bool,
1466                     row: &NurbsCurve,
1467                     pcurve: &NurbsCurve,
1468                     surface: &NurbsSurface,
1469                     a: f64,
1470                     b: f64|
1471     -> Result<Option<(NurbsCurve, NurbsCurve)>, KernelRefusal> {
1472        if collapsed {
1473            return Ok(None);
1474        }
1475        let rows_timing = crate::blend::BlendTimer::start("timing.surgery.trim.rows_ms");
1476        let rail = trim_row(row, a, b).map_err(describe_trim)?;
1477        let interpolated = trim_row(pcurve, a, b)?;
1478        rows_timing.stop();
1479        {
1480            let overrun_timing = crate::blend::BlendTimer::start("timing.surgery.trim.overrun_ms");
1481            let [d0, d1] = rail.domain().or_refuse(KernelStage::Refine, "domain")?;
1482            let overrun = crate::blend::planar_chart_overrun(surface, &|t| rail.evaluate(t), d0, d1)?;
1483            overrun_timing.stop();
1484            if overrun.is_some_and(|excursion| excursion > band) {
1485                return Ok(Some((rail, interpolated)));
1486            }
1487        }
1488        let [d0, d1] = rail.domain().or_refuse(KernelStage::Refine, "domain")?;
1489        // Slice 1b: an exact extrusion row's rail on a
1490        // plane ships the exact line in uv, read once; the refit road below
1491        // is for what it declines.
1492        if rows.exact_extrusion {
1493            if let Some(line) = exact_planar_trim(&rail, surface, d0, d1)? {
1494                crate::blend::record_count("count.surgery.exact_trim", 1);
1495                return Ok(Some((rail, line)));
1496            }
1497        }
1498        // The exact REVOLUTION rows' own trims are exact by construction
1499        // (the carrier's uv line, the plane's affine image of the rail):
1500        // read once as shipped by the march trim's rule (`march_trim_stands`)
1501        // and kept; whatever does not stand takes the refit road below.
1502        if rows.revolution_axis.is_some() {
1503            // Lane N row 4: the pair bounded in closed form stands without a
1504            // sample (`exact_revolution_read_bound` on the UNCUT row and
1505            // pcurve, whose restrictions to [a, b] these are: miss + standoff
1506            // within three bounds).
1507            if exact_revolution_reads_on() {
1508                let cert_timing = crate::blend::BlendTimer::start("timing.surgery.trim.exact.cert_ms");
1509                let bound = exact_revolution_read_bound(row, surface, pcurve);
1510                cert_timing.stop();
1511                if bound.is_some_and(|bound| 3.0 * bound <= crate::pcurve::PCURVE_REFINEMENT_TOLERANCE) {
1512                    crate::blend::record_count("count.surgery.exact_revolution_trim_certified", 1);
1513                    return Ok(Some((rail, interpolated)));
1514                }
1515            }
1516            let read_timing = crate::blend::BlendTimer::start("timing.surgery.trim.exact.read_ms");
1517            let read = crate::blend::track_fit::read_shipped_pcurve(surface, &|t| rail.evaluate(t), &interpolated, d0, d1);
1518            read_timing.stop();
1519            if march_trim_stands(&read, crate::pcurve::PCURVE_REFINEMENT_TOLERANCE) {
1520                crate::blend::record_count("count.surgery.exact_revolution_trim", 1);
1521                return Ok(Some((rail, interpolated)));
1522            }
1523            crate::blend::record_count("count.surgery.exact_revolution_trim_declined", 1);
1524        }
1525        // The march's OWN trim pcurve, read independently at the rail's own
1526        // parameter against the same floor (`read_shipped_pcurve`): what a
1527        // declined refit may fall back to, and the standoff a refit on the
1528        // rail's own branch must match.
1529        // The feet of each pcurve against the rail are sought once and
1530        // shared between the reads below (`FootMemo`): the march trim's for
1531        // its own read and the branch comparison, the refit's for the
1532        // refit's own read, the branch comparison and the absolute bound.
1533        let mut march_feet = crate::blend::track_fit::FootMemo::default();
1534        let mut refit_feet = crate::blend::track_fit::FootMemo::default();
1535        let march_read_timing = crate::blend::BlendTimer::start("timing.surgery.trim.read.march_ms");
1536        let march_read = crate::blend::track_fit::read_shipped_pcurve_memo(surface, &|t| rail.evaluate(t), &interpolated, d0, d1, &mut march_feet);
1537        march_read_timing.stop();
1538        let floor = crate::pcurve::PCURVE_REFINEMENT_TOLERANCE;
1539        let declined = |why: KernelRefusal| -> Result<Option<(NurbsCurve, NurbsCurve)>, KernelRefusal> {
1540            // Kept ONLY when the march's trim stands on its own read
1541            // (`march_trim_stands`); otherwise the refusal stands.
1542            let stands = march_trim_stands(&march_read, floor);
1543            if stands {
1544                Ok(Some((rail.clone(), interpolated.clone())))
1545            } else {
1546                Err(why)
1547            }
1548        };
1549        let refit_timing = crate::blend::BlendTimer::start("timing.surgery.trim.refit_ms");
1550        let refit = super::closed::refit_closed_support_pcurve_read(&rail, &interpolated, surface, &mut refit_feet);
1551        refit_timing.stop();
1552        let _reads_timing = crate::blend::BlendTimer::start("timing.surgery.trim.reads_ms");
1553        match refit {
1554            Ok((fitted, refit_read)) => {
1555                // A refit tracks ITS OWN projected track; a track that took
1556                // another branch of the carrier tracks itself perfectly while
1557                // its foot stands far off the rail (the stationary-start
1558                // prism's coedge read 6.0 off its edge). Its foot standoff
1559                // must be the rail's own standoff on the march trim's branch.
1560                // BOTH reads are required: an unreadable refit read declines
1561                // the refit (the march trim then stands only on its own read
1562                // within the floor), and an unreadable march read cannot
1563                // establish that the refit is on the rail's branch, so it
1564                // refuses. Never shipped on an unknown.
1565                // The two are compared POINTWISE, at the same rail
1566                // parameters (`standoff_excess`), never as two maxima read at
1567                // each curve's own knots.
1568                // The refit's read is the shipped curve's own, handed back by
1569                // the refit (the same `read_shipped_pcurve` on the same
1570                // inputs, once).
1571                let (march_standoff, refit_standoff) = match (&march_read, Ok::<_, KernelRefusal>(refit_read)) {
1572                    (_, Err(error)) => return declined(error),
1573                    (Err(error), Ok(_)) => {
1574                        return Err(KernelRefusal::non_convergence(KernelStage::Refine, "support_refit_branch_unread", format!(
1575                            "blend: a support trim's refit cannot be shown to stand on its rail's branch: the march's own \
1576                             trim is unreadable ({})",
1577                            error.message
1578                        )));
1579                    }
1580                    (Ok((_, march_standoff, _, _)), Ok((_, refit_standoff, _, _))) => (*march_standoff, refit_standoff),
1581                };
1582                let excess_timing = crate::blend::BlendTimer::start("timing.surgery.trim.read.excess_ms");
1583                let excess = crate::blend::track_fit::standoff_excess_memo(
1584                    surface, &|t| rail.evaluate(t), &interpolated, &fitted, d0, d1, &mut march_feet, &mut refit_feet,
1585                );
1586                excess_timing.stop();
1587                let excess = match excess {
1588                    Ok(excess) => excess,
1589                    Err(error) => return declined(error),
1590                };
1591                if !(excess <= floor) {
1592                    return declined(KernelRefusal::non_convergence(KernelStage::Refine, "support_refit_branch", format!(
1593                        "blend: a support trim's refit stands up to {excess:.3e} farther off its rail than the march's own trim \
1594                         at the same rail parameter (largest standoffs {refit_standoff:.3e} and {march_standoff:.3e}): it took \
1595                         another branch of the carrier"
1596                    )));
1597                }
1598                // ABSOLUTE: the comparison above is relative to the march
1599                // trim, so a refit that follows an off-branch march trim
1600                // passes it. The refit's foot must also stand within the floor
1601                // of the rail's own deviation from its carrier, read by the
1602                // nearest-point projector at the same parameters
1603                // (`standoff_over_nearest`) -- the rail's approximation the
1604                // lane reports, never more.
1605                let nearest_timing = crate::blend::BlendTimer::start("timing.surgery.trim.read.nearest_ms");
1606                let absolute = crate::blend::track_fit::standoff_over_nearest_memo(surface, &|t| rail.evaluate(t), &fitted, d0, d1, &mut refit_feet);
1607                nearest_timing.stop();
1608                let absolute = match absolute {
1609                    Ok(absolute) => absolute,
1610                    Err(error) => return declined(error),
1611                };
1612                if !(absolute <= floor) {
1613                    return declined(KernelRefusal::non_convergence(KernelStage::Refine, "support_refit_off_rail", format!(
1614                        "blend: a support trim's refit stands up to {absolute:.3e} farther off its rail than the rail stands \
1615                         off its carrier: its foot is not the rail's nearest point"
1616                    )));
1617                }
1618                Ok(Some((rail, fitted)))
1619            }
1620            Err(error) => declined(error),
1621        }
1622    };
1623    let trim_timing = crate::blend::BlendTimer::start("timing.surgery.trim_rails_ms");
1624    let cr_rail = trim_rail(
1625        cr_collapsed,
1626        &rows.cr,
1627        &rows.cr_pcurve,
1628        &first.face.surface,
1629        start_end.cr_parameter(),
1630        finish_end.cr_parameter(),
1631    )?;
1632    let cs_rail = trim_rail(
1633        cs_collapsed,
1634        &rows.cs,
1635        &rows.cs_pcurve,
1636        &second.face.surface,
1637        start_end.cs_parameter(),
1638        finish_end.cs_parameter(),
1639    )?;
1640    trim_timing.stop();
1641    // A collapsed rail's domain is its two stops, which are one point.
1642    let cr_domain = match &cr_rail {
1643        Some((cr, _)) => cr.domain().or_refuse(KernelStage::Refine, "domain")?,
1644        None => [start_end.cr_parameter(), finish_end.cr_parameter()],
1645    };
1646    let cs_domain = match &cs_rail {
1647        Some((cs, _)) => cs.domain().or_refuse(KernelStage::Refine, "domain")?,
1648        None => [start_end.cs_parameter(), finish_end.cs_parameter()],
1649    };
1650    // A rail's end points, read off the trimmed rail or, collapsed, the row.
1651    let cr_at = |parameter: f64| match &cr_rail {
1652        Some((cr, _)) => cr.evaluate(parameter),
1653        None => rows.cr.evaluate(parameter),
1654    };
1655    let cs_at = |parameter: f64| match &cs_rail {
1656        Some((cs, _)) => cs.evaluate(parameter),
1657        None => rows.cs.evaluate(parameter),
1658    };
1659    let old_start = edge.start_vertex_id;
1660    let old_finish = edge.end_vertex_id;
1661
1662    // Classify each of the four support crossings.  A crossing that lands at
1663    // the FAR endpoint of the boundary edge it meets (the end away from the
1664    // corner) means a prior fillet already consumed that whole boundary: the
1665    // new blend reuses the existing vertex there and the boundary edge is
1666    // deleted (its role is taken over by the new transverse curve on the
1667    // prior blend face).  An interior crossing is the pristine case — a fresh
1668    // vertex with the boundary trimmed to it.
1669    //
1670    // Consumed means within `consumed_band` — the slack `check_support_extent`
1671    // refuses past, so a rail between the two is not possible.
1672    let classify =
1673        |boundary_id: u64, boundary_param: f64, corner: u64| -> Result<RimResolution, KernelRefusal> {
1674            let boundary = result
1675                .edges
1676                .iter()
1677                .find(|candidate| candidate.id == boundary_id)
1678                .ok_or(KernelRefusal::internal(KernelStage::Sew, "end_boundary_edge", "blend: end boundary edge missing during surgery"))?;
1679            let span = (boundary.t1 - boundary.t0).abs().max(1e-12);
1680            let far_vertex = if boundary.start_vertex_id == corner {
1681                Some((boundary.end_vertex_id, boundary.t1, boundary.t0))
1682            } else if boundary.end_vertex_id == corner {
1683                Some((boundary.start_vertex_id, boundary.t0, boundary.t1))
1684            } else {
1685                None
1686            };
1687            if let Some((far_id, far_t, near_t)) = far_vertex {
1688                // A consumed boundary is a COINCIDENCE — a prior fillet's rim
1689                // vertex is exactly where this rail crosses — and the operands
1690                // were healed before the march, so it holds to solver
1691                // precision.  It is not "near the far end": a fillet whose
1692                // radius is 1e-3 short of the face's width crosses 1e-3 from
1693                // the far vertex and must keep that sliver, or the face is
1694                // snapped a full 1e-3 out of true (the oversized-radius limit
1695                // cases and issue 1177 measure exactly that).  Measured in
1696                // model units, never in the boundary's parameter — a unit
1697                // parameter on a 20-long edge would call 2e-3 a coincidence.
1698                let far_point = result
1699                    .vertices
1700                    .iter()
1701                    .find(|candidate| candidate.id == far_id)
1702                    .map(|candidate| candidate.point)
1703                    .ok_or(KernelRefusal::internal(KernelStage::Sew, "far_vertex", "blend: consumed boundary far vertex missing"))?;
1704                let crossing = boundary.curve.evaluate_extended(boundary_param).or_refuse(KernelStage::Refine, "evaluate_extended")?;
1705                let _ = span;
1706                let past_far = crossing.sub(far_point).length();
1707                if past_far <= band {
1708                    // Sanity: the reused vertex must exist.
1709                    if !result
1710                        .vertices
1711                        .iter()
1712                        .any(|candidate| candidate.id == far_id)
1713                    {
1714                        return Err(KernelRefusal::internal(KernelStage::Sew, "far_vertex", "blend: consumed boundary far vertex missing"));
1715                    }
1716                    return Ok(RimResolution::Consumed(far_id));
1717                }
1718                // A crossing BEYOND the far vertex is a rail that runs off
1719                // its face: the blend is wider than the face by more than the
1720                // band a snap may close, and trimming the boundary there would
1721                // extend it into air.  `check_support_extent` refuses this
1722                // before the march on every face the exact tool understands;
1723                // this is the refusal for the rest.  It is not the whole
1724                // answer: a crossing the solve CLAMPS to the far vertex reads
1725                // as consumed here, and `detect_row_coincidence` is what sees
1726                // that row leave the face.  Measured on the census: it fires on
1727                // a wall wider than its closed chain's arc (0.5 past) and on the
1728                // r = 10.001 pinch past an earlier round (2e-3 past), both of
1729                // which refused later in the surgery before.
1730                if (boundary_param - far_t) * (far_t - near_t) > 0.0 {
1731                    return Err(KernelRefusal::unsupported(KernelStage::Sew, "blend_wider_than_face", format!(
1732                        "{BLEND_WIDER_THAN_FACE} its rail crosses edge {boundary_id} {past_far:.3e} \
1733                         past that edge's far vertex, and a rail within {band:.3e} of it is the \
1734                         most this surgery snaps onto the edge"
1735                    )));
1736                }
1737            }
1738            Ok(RimResolution::Fresh)
1739        };
1740    // A CORNER end has no boundary to classify: the ball's tangency vertex is
1741    // the rim, and the boundary edge that used to reach the sharp corner is
1742    // the neighbouring stripe's own blended edge, which that stripe replaces.
1743    let resolve_side = |plan: &EndPlan,
1744                        side_first: bool,
1745                        corner: u64|
1746     -> Result<RimResolution, KernelRefusal> {
1747        if let Some(vertex) = plan.planned_rim(side_first) {
1748            return Ok(RimResolution::Corner(vertex));
1749        }
1750        match plan {
1751            EndPlan::Free(free) => classify(
1752                if side_first {
1753                    free.first_edge_id
1754                } else {
1755                    free.second_edge_id
1756                },
1757                if side_first {
1758                    free.first_edge_parameter
1759                } else {
1760                    free.second_edge_parameter
1761                },
1762                corner,
1763            ),
1764            EndPlan::Corner(_) | EndPlan::Miter(_) | EndPlan::Cap(_) => {
1765                Err(KernelRefusal::internal(KernelStage::Sew, "rim_vertices", "blend: planned end without rim vertices"))
1766            }
1767        }
1768    };
1769    let crossings_timing = crate::blend::BlendTimer::start("timing.surgery.crossings_ms");
1770    let start_first = resolve_side(&start_end, true, old_start)?;
1771    let start_second = resolve_side(&start_end, false, old_start)?;
1772    let finish_first = resolve_side(&finish_end, true, old_finish)?;
1773    let finish_second = resolve_side(&finish_end, false, old_finish)?;
1774    crossings_timing.stop();
1775    let _topology_timing = crate::blend::BlendTimer::start("timing.surgery.topology_ms");
1776
1777    // Manifold pairing: the blend's use of the first support row must oppose
1778    // F1's use of the blended edge (see the blend-loop construction below).
1779    let first_use_forward = first.coedge.forward;
1780    let blend_cr_forward = !first_use_forward;
1781
1782    // Curve-level coincidence (OCCT PR #1449 lesson 3): when BOTH of a mate's
1783    // crossings are endpoint-consumed AND the trimmed support row retraces the
1784    // existing edge joining the two far vertices, that mate face is FULLY
1785    // consumed — the surgery sews the blend face straight onto the existing
1786    // edge and drops the zero-width face, instead of creating a coincident
1787    // fresh support edge that would leave a sliver strip (the r = face-width
1788    // class).  Each side is detected independently; any ambiguity keeps the
1789    // pristine path (fail-safe).  `row_traversed_from_start`: the blend loop
1790    // walks cr in station order iff `blend_cr_forward`, and cs in the
1791    // OPPOSITE order (see the two loop branches below).
1792    // A stripe with a CORNER end has no boundary edges at that end to be
1793    // coincident with, so the detection only runs on stripes that are free at
1794    // both ends.  (Fail-safe: not detecting a coincidence keeps the pristine
1795    // path, which is what a corner stop wants anyway.)
1796    let (sew_first, sew_second) = match (start_end.free(), finish_end.free(), &cr_rail, &cs_rail) {
1797        (Some(start_free), Some(finish_free), Some((cr, _)), Some((cs, _))) => (
1798            detect_row_coincidence(
1799                solid,
1800                first,
1801                edge.id,
1802                start_free.first_edge_id,
1803                finish_free.first_edge_id,
1804                start_first.is_consumed(),
1805                start_first.existing().unwrap_or(0),
1806                finish_first.is_consumed(),
1807                finish_first.existing().unwrap_or(0),
1808                cr,
1809                blend_cr_forward,
1810                band,
1811            )?,
1812            detect_row_coincidence(
1813                solid,
1814                second,
1815                edge.id,
1816                start_free.second_edge_id,
1817                finish_free.second_edge_id,
1818                start_second.is_consumed(),
1819                start_second.existing().unwrap_or(0),
1820                finish_second.is_consumed(),
1821                finish_second.existing().unwrap_or(0),
1822                cs,
1823                !blend_cr_forward,
1824                band,
1825            )?,
1826        ),
1827        _ => (None, None),
1828    };
1829    // One face hosting both sides (the blended edge used twice by one face)
1830    // cannot be dropped for one side while the other still splices into it —
1831    // ambiguous, keep the pristine path for both.
1832    let (sew_first, sew_second): (Option<RowSew>, Option<RowSew>) =
1833        if first.face.id == second.face.id {
1834            (None, None)
1835        } else {
1836            (sew_first, sew_second)
1837        };
1838
1839    // Resolve the four rim vertices: reuse the existing vertex for a consumed
1840    // side, else create a fresh vertex at the support-row endpoint.
1841    let mut resolve = |rim: &RimResolution, point: Result<Vec3, String>| -> Result<u64, KernelRefusal> {
1842        match rim.existing() {
1843            Some(id) => Ok(id),
1844            None => {
1845                let id = take_id();
1846                result.vertices.push(VertexRecord { id, point: point.or_refuse(KernelStage::Refine, "point")? });
1847                Ok(id)
1848            }
1849        }
1850    };
1851    let w1a = resolve(&start_first, cr_at(cr_domain[0]))?;
1852    let w1b = resolve(&finish_first, cr_at(cr_domain[1]))?;
1853    let w2a = resolve(&start_second, cs_at(cs_domain[0]))?;
1854    let w2b = resolve(&finish_second, cs_at(cs_domain[1]))?;
1855    // How far the consumed rims and sewn rows moved a rail onto what already
1856    // existed — what `check_snap_closure` measures the body against.
1857    let mut snap = [&sew_first, &sew_second]
1858        .into_iter()
1859        .flatten()
1860        .fold(0.0f64, |worst, sew| worst.max(sew.deviation));
1861    for (rim, vertex, row_end) in [
1862        (&start_first, w1a, cr_at(cr_domain[0]).or_refuse(KernelStage::Refine, "cr_at")?),
1863        (&finish_first, w1b, cr_at(cr_domain[1]).or_refuse(KernelStage::Refine, "cr_at")?),
1864        (&start_second, w2a, cs_at(cs_domain[0]).or_refuse(KernelStage::Refine, "cs_at")?),
1865        (&finish_second, w2b, cs_at(cs_domain[1]).or_refuse(KernelStage::Refine, "cs_at")?),
1866    ] {
1867        if !rim.is_consumed() {
1868            continue;
1869        }
1870        let point = result
1871            .vertices
1872            .iter()
1873            .find(|candidate| candidate.id == vertex)
1874            .ok_or(KernelRefusal::internal(KernelStage::Sew, "rim_vertex", "blend: consumed rim vertex missing"))?
1875            .point;
1876        snap = snap.max(row_end.sub(point).length());
1877    }
1878
1879    // Support edges: a sewn side reuses the EXISTING coincident edge (no
1880    // fresh edge — OCCT's `SetExistingEdge` move); a pristine side gets the
1881    // fitted row as a fresh edge.
1882    // A collapsed side builds no edge at all.
1883    let cr_edge_id = match (&sew_first, &cr_rail) {
1884        (Some(sew), _) => Some(sew.edge_id),
1885        (None, None) => None,
1886        (None, Some((cr, _))) => {
1887            let id = take_id();
1888            result.edges.push(EdgeRecord {
1889                id,
1890                curve: cr.clone(),
1891                t0: cr_domain[0],
1892                t1: cr_domain[1],
1893                start_vertex_id: w1a,
1894                end_vertex_id: w1b,
1895                degenerate: false,
1896                name: None,
1897            });
1898            Some(id)
1899        }
1900    };
1901    let cs_edge_id = match (&sew_second, &cs_rail) {
1902        (Some(sew), _) => Some(sew.edge_id),
1903        (None, None) => None,
1904        (None, Some((cs, _))) => {
1905            let id = take_id();
1906            result.edges.push(EdgeRecord {
1907                id,
1908                curve: cs.clone(),
1909                t0: cs_domain[0],
1910                t1: cs_domain[1],
1911                start_vertex_id: w2a,
1912                end_vertex_id: w2b,
1913                degenerate: false,
1914                name: None,
1915            });
1916            Some(id)
1917        }
1918    };
1919    // The edge closing each end of the blend face: the §6.9 transverse curve
1920    // on the end face for a free end, or — at a corner — the end
1921    // cross-section arc the corner patch was already given, committed by the
1922    // caller and merely referenced here.
1923    let mut commit_split = |plan: &EndPlan, second_rim: u64, corner: u64| -> Result<Option<super::split_floor::SplitCommit>, KernelRefusal> {
1924        match plan.free().and_then(|free| free.split.as_ref()) {
1925            Some(split) => super::split_floor::commit_split_end(result, &mut *take_id, split, second_rim, corner).map(Some),
1926            None => Ok(None),
1927        }
1928    };
1929    let start_split = commit_split(&start_end, w2a, old_start)?;
1930    let finish_split = commit_split(&finish_end, w2b, old_finish)?;
1931    let mut commit_end_edge = |plan: &EndPlan,
1932                               first_rim: u64,
1933                               second_rim: u64|
1934     -> Result<Option<u64>, KernelRefusal> {
1935        match plan {
1936            EndPlan::Corner(_) | EndPlan::Miter(_) | EndPlan::Cap(_) => Ok(None),
1937            EndPlan::Free(free) => {
1938                let id = take_id();
1939                let domain = free.transverse_curve.domain().or_refuse(KernelStage::Refine, "domain")?;
1940                result.edges.push(EdgeRecord {
1941                    id,
1942                    curve: free.transverse_curve.clone(),
1943                    t0: domain[0],
1944                    t1: domain[1],
1945                    start_vertex_id: first_rim,
1946                    end_vertex_id: second_rim,
1947                    degenerate: false,
1948                    name: None,
1949                });
1950                Ok(Some(id))
1951            }
1952        }
1953    };
1954    let transverse_a_id = commit_end_edge(&start_end, w1a, start_split.as_ref().map_or(w2a, |split| split.q1_vertex))?;
1955    let transverse_b_id = commit_end_edge(&finish_end, w1b, finish_split.as_ref().map_or(w2b, |split| split.q1_vertex))?;
1956
1957    // Replace the blended edge in each PRISTINE mate's loop — the blend
1958    // face's loop direction is forced by manifold pairing with F1's use of
1959    // the blended edge (`first_use_forward`, captured above).  A sewn mate is
1960    // dropped whole below; nothing to splice.  A COLLAPSED side has no rail to
1961    // put there: the mate simply loses the blended edge, and its loop closes
1962    // through the rim vertices the orchestrator identifies.
1963    for (mate, rail, sewn) in [
1964        (first, cr_edge_id.zip(cr_rail.as_ref()), sew_first.is_some()),
1965        (second, cs_edge_id.zip(cs_rail.as_ref()), sew_second.is_some()),
1966    ] {
1967        if sewn {
1968            continue;
1969        }
1970        let face = result
1971            .shells
1972            .iter_mut()
1973            .flat_map(|shell| &mut shell.faces)
1974            .find(|face| face.id == mate.face.id)
1975            .ok_or(KernelRefusal::internal(KernelStage::Sew, "mate_face", "blend: mate face lost during surgery"))?;
1976        let loop_record = &mut face.loops[mate.loop_index];
1977        let position = loop_record
1978            .coedges
1979            .iter()
1980            .position(|coedge| coedge.edge_id == edge.id)
1981            .ok_or(KernelRefusal::internal(KernelStage::Sew, "edge_coedge", "blend: edge coedge lost during surgery"))?;
1982        let Some((new_edge_id, (_, pcurve_forward))) = rail else {
1983            loop_record.coedges.remove(position);
1984            continue;
1985        };
1986        let old_forward = loop_record.coedges[position].forward;
1987        loop_record.coedges[position] = CoedgeRecord {
1988            id: loop_record.coedges[position].id,
1989            edge_id: new_edge_id,
1990            forward: old_forward,
1991            pcurve: if old_forward {
1992                pcurve_forward.clone()
1993            } else {
1994                pcurve_forward.reversed().or_refuse(KernelStage::Refine, "reversed")?
1995            },
1996        };
1997    }
1998
1999    // A capped end's legs: on each mate, the leg runs from the rail's rim
2000    // vertex to the sharp vertex, where the continuing edge still starts.
2001    // It goes between the rail coedge and that continuing coedge, with the
2002    // sense that walks rim -> vertex when the rail ends at the rim.
2003    for (plan, at_start) in [(&start_end, true), (&finish_end, false)] {
2004        let EndPlan::Cap(cap) = plan else {
2005            continue;
2006        };
2007        for (mate, rail_edge_id, leg, rim) in [
2008            (first, cr_edge_id, &cap.first_leg, if at_start { w1a } else { w1b }),
2009            (second, cs_edge_id, &cap.second_leg, if at_start { w2a } else { w2b }),
2010        ] {
2011            // Refused above: a capped end never meets a collapsed rail.
2012            let rail_edge_id = rail_edge_id.ok_or(KernelRefusal::internal(KernelStage::Sew, "end_rail", "blend: a capped end lost its rail"))?;
2013            let face = result
2014                .shells
2015                .iter_mut()
2016                .flat_map(|shell| &mut shell.faces)
2017                .find(|face| face.id == mate.face.id)
2018                .ok_or(KernelRefusal::internal(KernelStage::Sew, "mate_face", "blend: mate face lost during cap splice"))?;
2019            let loop_record = &mut face.loops[mate.loop_index];
2020            let count = loop_record.coedges.len();
2021            let rail_at = loop_record
2022                .coedges
2023                .iter()
2024                .position(|coedge| coedge.edge_id == rail_edge_id)
2025                .ok_or(KernelRefusal::internal(KernelStage::Sew, "rail_coedge", "blend: rail coedge lost during cap splice"))?;
2026            // Which side of the rail coedge is this end?  The rail coedge
2027            // traverses rim-to-rim; the capped end is at its traversal END
2028            // when walking forward means station order and this is the
2029            // finish end, etc.  Decide by geometry: the neighbour whose
2030            // traversal touches the sharp vertex.
2031            let rail_forward = loop_record.coedges[rail_at].forward;
2032            let end_is_traversal_end = if rail_forward { !at_start } else { at_start };
2033            let (insert_at, forward, pcurve) = if end_is_traversal_end {
2034                // rail ... rim -> [leg rim->vertex] -> continuing edge
2035                (rail_at + 1, true, leg.1.clone())
2036            } else {
2037                // continuing edge -> [leg vertex->rim] -> rim ... rail
2038                (rail_at, false, leg.1.reversed().or_refuse(KernelStage::Refine, "reversed")?)
2039            };
2040            let _ = (count, rim);
2041            loop_record.coedges.insert(
2042                insert_at,
2043                CoedgeRecord {
2044                    id: take_id(),
2045                    edge_id: leg.0,
2046                    forward,
2047                    pcurve,
2048                },
2049            );
2050        }
2051    }
2052
2053    // Drop consumed boundary edges from the mate loop they share with the
2054    // blended edge: the fresh support coedge already begins at the reused far
2055    // vertex, so removing the fully-covered boundary keeps the loop closed.
2056    // A SEWN mate's whole loop collapses (the face is dropped below), so its
2057    // consumed boundaries are only recorded for deletion, never spliced.
2058    let mut consumed_edges: Vec<u64> = Vec::new();
2059    let start_free = start_end.free();
2060    let finish_free = finish_end.free();
2061    for (mate, sewn, sides) in [
2062        (
2063            first,
2064            sew_first.is_some(),
2065            [
2066                (&start_first, start_free.map(|free| free.first_edge_id)),
2067                (&finish_first, finish_free.map(|free| free.first_edge_id)),
2068            ],
2069        ),
2070        (
2071            second,
2072            sew_second.is_some(),
2073            [
2074                (&start_second, start_free.map(|free| free.second_edge_id)),
2075                (&finish_second, finish_free.map(|free| free.second_edge_id)),
2076            ],
2077        ),
2078    ] {
2079        for (cross, boundary_id) in sides {
2080            if !cross.is_consumed() {
2081                continue;
2082            }
2083            let Some(boundary_id) = boundary_id else {
2084                continue;
2085            };
2086            if !sewn {
2087                let face = result
2088                    .shells
2089                    .iter_mut()
2090                    .flat_map(|shell| &mut shell.faces)
2091                    .find(|face| face.id == mate.face.id)
2092                    .ok_or(KernelRefusal::internal(KernelStage::Sew, "mate_face", "blend: mate face lost during surgery"))?;
2093                face.loops[mate.loop_index]
2094                    .coedges
2095                    .retain(|coedge| coedge.edge_id != boundary_id);
2096            }
2097            if !consumed_edges.contains(&boundary_id) {
2098                consumed_edges.push(boundary_id);
2099            }
2100        }
2101    }
2102    // Lesson 7: zero-span leftovers of a collapsing loop go with their face.
2103    for sew in [&sew_first, &sew_second].into_iter().flatten() {
2104        for id in &sew.collapsed_edges {
2105            if !consumed_edges.contains(id) {
2106                consumed_edges.push(*id);
2107            }
2108        }
2109    }
2110
2111    // Locate the corner junction on each end face BEFORE trimming (the two
2112    // boundary coedges that meet at the old corner vertex, stepping over the
2113    // pole between them where the end face's apex IS that vertex) — edge ids
2114    // alone are ambiguous on two-coedge cap loops, so the meeting must be at
2115    // the corner.
2116    // (end, transverse_id, corner, first_consumed, second_consumed) -> plan.
2117    // Only FREE ends appear here: a corner stop rebuilds nothing on a third
2118    // face, because the corner patch is what closes it.
2119    let mut end_plans = Vec::with_capacity(2);
2120    for (end, transverse_id, corner, first_consumed, second_consumed) in [
2121        (
2122            start_end.free(),
2123            transverse_a_id,
2124            old_start,
2125            start_first.is_consumed(),
2126            start_second.is_consumed(),
2127        ),
2128        (
2129            finish_end.free(),
2130            transverse_b_id,
2131            old_finish,
2132            finish_first.is_consumed(),
2133            finish_second.is_consumed(),
2134        ),
2135    ] {
2136        let (Some(end), Some(transverse_id)) = (end, transverse_id) else {
2137            continue;
2138        };
2139        if end.split.is_some() {
2140            continue;
2141        }
2142        let face = result
2143            .shells
2144            .iter()
2145            .flat_map(|shell| &shell.faces)
2146            .find(|face| face.id == end.end_face_id)
2147            .ok_or(KernelRefusal::internal(KernelStage::Sew, "end_face", "blend: end face lost during surgery"))?;
2148        // Key on stable coedge ids (not indices) so processing one end can't
2149        // invalidate another that shares this face.
2150        let Some(located) = locate_end_corner(
2151            &result,
2152            face,
2153            corner,
2154            end.first_edge_id,
2155            end.second_edge_id,
2156        ) else {
2157            return Err(KernelRefusal::internal(KernelStage::Sew, "end_face_corner", "blend: end-face corner (adjacent boundary coedges) not found"));
2158        };
2159        // The apex the transverse curve cuts off goes with the boundaries the
2160        // blend consumes.
2161        for pole in &located.pole_edge_ids {
2162            if !consumed_edges.contains(pole) {
2163                consumed_edges.push(*pole);
2164            }
2165        }
2166        end_plans.push((
2167            end.end_face_id,
2168            transverse_id,
2169            end.transverse_end_pcurve.clone(),
2170            located,
2171            first_consumed,
2172            second_consumed,
2173        ));
2174    }
2175
2176    let split_corners = |end: Option<&EndSurgery>, corner: u64, result: &BrepSolid| -> Result<Option<[super::support::EndCorner; 2]>, KernelRefusal> {
2177        match end.and_then(|end| end.split.as_ref().map(|split| (end, split))) {
2178            Some((end, split)) => super::split_floor::locate_split_corners(result, end, split, corner).map(Some),
2179            None => Ok(None),
2180        }
2181    };
2182    let start_split_corners = split_corners(start_free, old_start, result)?;
2183    let finish_split_corners = split_corners(finish_free, old_finish, result)?;
2184    if (start_split_corners.is_some() && (start_first.is_consumed() || start_second.is_consumed()))
2185        || (finish_split_corners.is_some() && (finish_first.is_consumed() || finish_second.is_consumed()))
2186    {
2187        return Err(KernelRefusal::unsupported(KernelStage::Sew, "split_floor_consumed", "blend: a two-face end whose rail consumes its boundary"));
2188    }
2189
2190    // Trim the boundary edges at their support crossings.  A consumed side is
2191    // deleted instead of trimmed; a CORNER side touches no boundary at all.
2192    for (rim_resolution, boundary, corner, rim) in [
2193        (
2194            &start_first,
2195            start_free.map(|free| (free.first_edge_id, free.first_edge_parameter)),
2196            old_start,
2197            w1a,
2198        ),
2199        (
2200            &start_second,
2201            start_free.map(|free| (free.second_edge_id, free.second_edge_parameter)),
2202            old_start,
2203            w2a,
2204        ),
2205        (
2206            &finish_first,
2207            finish_free.map(|free| (free.first_edge_id, free.first_edge_parameter)),
2208            old_finish,
2209            w1b,
2210        ),
2211        (
2212            &finish_second,
2213            finish_free.map(|free| (free.second_edge_id, free.second_edge_parameter)),
2214            old_finish,
2215            w2b,
2216        ),
2217    ] {
2218        if !rim_resolution.trims_boundary() {
2219            continue;
2220        }
2221        let Some((boundary_id, boundary_param)) = boundary else {
2222            continue;
2223        };
2224        trim_edge_at(result, boundary_id, boundary_param, corner, rim)?;
2225    }
2226
2227    // Rebuild each end face's corner: drop the consumed boundary coedge(s) and
2228    // splice in the transverse coedge between the (trimmed) boundaries.
2229    for (end_face, transverse_id, transverse_end_pcurve, located, first_consumed, second_consumed) in
2230        end_plans
2231    {
2232        let forward = located.x_is_first;
2233        let pcurve = if forward {
2234            transverse_end_pcurve
2235        } else {
2236            transverse_end_pcurve.reversed().or_refuse(KernelStage::Refine, "reversed")?
2237        };
2238        let (x_consumed, y_consumed) = if located.x_is_first {
2239            (first_consumed, second_consumed)
2240        } else {
2241            (second_consumed, first_consumed)
2242        };
2243        let transverse_coedge = CoedgeRecord {
2244            id: take_id(),
2245            edge_id: transverse_id,
2246            forward,
2247            pcurve,
2248        };
2249        splice_end_corner(
2250            result,
2251            end_face,
2252            &located,
2253            transverse_coedge,
2254            x_consumed,
2255            y_consumed,
2256        )?;
2257    }
2258
2259    // Blend face: cr fwd -> TB -> cs rev -> TA rev in (t, z) space.  Both rows
2260    // share one parameterisation, so a collapsed cr reads its sense across the
2261    // strip the cs rail still spans (a stripe with BOTH rails collapsed has no
2262    // area; the orchestrator drops it with the edges that bound it).
2263    let (mid_u, station_uv) = match (&cr_rail, &cs_rail) {
2264        (Some((_, cr_pcurve)), _) => {
2265            let mid_u = (cr_domain[0] + cr_domain[1]) * 0.5;
2266            (mid_u, cr_pcurve.evaluate(mid_u).or_refuse(KernelStage::Refine, "evaluate")?)
2267        }
2268        (None, Some(_)) => {
2269            let mid_u = (cs_domain[0] + cs_domain[1]) * 0.5;
2270            (mid_u, rows.cr_pcurve.evaluate(mid_u).or_refuse(KernelStage::Refine, "evaluate")?)
2271        }
2272        (None, None) => (cr_domain[0], rows.cr_pcurve.evaluate(cr_domain[0]).or_refuse(KernelStage::Refine, "evaluate")?),
2273    };
2274    let blend_normal = raw_normal(&rows.surface, mid_u, 0.0)?;
2275    let n1 = raw_normal(&first.face.surface, station_uv.x, station_uv.y)?;
2276    let out1 = if first.face.same_sense {
2277        n1
2278    } else {
2279        n1.scale(-1.0)
2280    };
2281    let same_sense = blend_normal.dot(out1) >= 0.0;
2282    let loop_id = take_id();
2283    // Traversal senses of the blend's support coedges.  A fresh support edge
2284    // is parameterized in station order, so the sense is the loop's walking
2285    // direction (`blend_cr_forward` for cr, its opposite for cs); a SEWN
2286    // side's sense comes from the detection (the existing edge's own
2287    // parameter direction relative to that same walk — equal to the dropped
2288    // face's old sense, preserving manifold pairing with the survivor).  The
2289    // pcurves always follow the LOOP's walking direction and are unchanged.
2290    let cr_forward = sew_first
2291        .as_ref()
2292        .map_or(blend_cr_forward, |sew| sew.forward);
2293    let cs_forward = sew_second
2294        .as_ref()
2295        .map_or(!blend_cr_forward, |sew| sew.forward);
2296    // The two end slots of the blend loop.  `natural_forward` is the sense the
2297    // loop walks a transverse edge stored first-rim -> second-rim; a CORNER
2298    // arc was already committed in the walk direction (so the corner patch can
2299    // take it the other way round), so it is always used forward.
2300    // A slot is one coedge for a free end (the transverse curve) or a corner
2301    // end (the section arc), and one or two for a miter end (the seam, then
2302    // the sibling's section when the seam left the sibling first).  A corner
2303    // arc was committed in the walk direction; a miter edge records its own
2304    // sense along the walk.
2305    let mut end_slot = |plan: &EndPlan,
2306                        free_edge_id: Option<u64>,
2307                        natural_forward: bool|
2308     -> Result<Vec<CoedgeRecord>, KernelRefusal> {
2309        match plan {
2310            EndPlan::Corner(end) => Ok(vec![CoedgeRecord {
2311                id: take_id(),
2312                edge_id: end.arc_edge_id,
2313                forward: true,
2314                pcurve: end.arc_blend_pcurve.clone(),
2315            }]),
2316            EndPlan::Cap(end) => Ok(vec![CoedgeRecord {
2317                id: take_id(),
2318                edge_id: end.arc_edge_id,
2319                forward: true,
2320                pcurve: end.arc_blend_pcurve.clone(),
2321            }]),
2322            EndPlan::Miter(end) => end
2323                .edges
2324                .iter()
2325                .map(|(edge_id, forward, pcurve)| {
2326                    Ok(CoedgeRecord {
2327                        id: take_id(),
2328                        edge_id: *edge_id,
2329                        forward: *forward,
2330                        pcurve: pcurve.clone(),
2331                    })
2332                })
2333                .collect(),
2334            EndPlan::Free(free) => {
2335                let edge_id =
2336                    free_edge_id.ok_or(KernelRefusal::internal(KernelStage::Sew, "transverse_edge", "blend: free end without its transverse edge"))?;
2337                Ok(vec![if natural_forward {
2338                    CoedgeRecord {
2339                        id: take_id(),
2340                        edge_id,
2341                        forward: true,
2342                        pcurve: free.transverse_blend_pcurve.clone(),
2343                    }
2344                } else {
2345                    CoedgeRecord {
2346                        id: take_id(),
2347                        edge_id,
2348                        forward: false,
2349                        pcurve: free.transverse_blend_pcurve.reversed().or_refuse(KernelStage::Refine, "reversed")?,
2350                    }
2351                }])
2352            }
2353        }
2354    };
2355    let start_slot = end_slot(&start_end, transverse_a_id, !blend_cr_forward)?;
2356    let finish_slot = end_slot(&finish_end, transverse_b_id, blend_cr_forward)?;
2357    let start_slot = match (start_free, &start_split, transverse_a_id) {
2358        (Some(end), Some(commit), Some(id)) => super::split_floor::split_slot(end, end.split.as_ref().expect("planned"), commit, id, !blend_cr_forward, &mut *take_id)?,
2359        _ => start_slot,
2360    };
2361    let finish_slot = match (finish_free, &finish_split, transverse_b_id) {
2362        (Some(end), Some(commit), Some(id)) => super::split_floor::split_slot(end, end.split.as_ref().expect("planned"), commit, id, blend_cr_forward, &mut *take_id)?,
2363        _ => finish_slot,
2364    };
2365    for (end, commit, id, corners, corner, forward) in [
2366        (start_free, &start_split, transverse_a_id, &start_split_corners, old_start, !blend_cr_forward),
2367        (finish_free, &finish_split, transverse_b_id, &finish_split_corners, old_finish, blend_cr_forward),
2368    ] {
2369        if let (Some(end), Some(commit), Some(id), Some(corners)) = (end, commit, id, corners) {
2370            super::split_floor::finish_split_end(result, &mut *take_id, end, end.split.as_ref().expect("planned"), commit, id, corners, corner, forward, name)?;
2371        }
2372    }
2373    // A collapsed rail has no coedge: the end slots on either side of it meet
2374    // at its one rim point.
2375    let coedges = if blend_cr_forward {
2376        let mut coedges = Vec::new();
2377        if let Some(cr_edge_id) = cr_edge_id {
2378            coedges.push(CoedgeRecord {
2379                id: take_id(),
2380                edge_id: cr_edge_id,
2381                forward: cr_forward,
2382                pcurve: crate::sweep_topology::parameter_line(
2383                    cr_domain[0],
2384                    0.0,
2385                    cr_domain[1],
2386                    0.0,
2387                ).or_refuse(KernelStage::Refine, "parameter_line")?,
2388            });
2389        }
2390        coedges.extend(finish_slot);
2391        if let Some(cs_edge_id) = cs_edge_id {
2392            coedges.push(CoedgeRecord {
2393                id: take_id(),
2394                edge_id: cs_edge_id,
2395                forward: cs_forward,
2396                pcurve: cs_blend_pcurve_reversed(&cs_domain)?,
2397            });
2398        }
2399        coedges.extend(start_slot);
2400        coedges
2401    } else {
2402        let mut coedges = Vec::new();
2403        if let Some(cr_edge_id) = cr_edge_id {
2404            coedges.push(CoedgeRecord {
2405                id: take_id(),
2406                edge_id: cr_edge_id,
2407                forward: cr_forward,
2408                pcurve: crate::sweep_topology::parameter_line(
2409                    cr_domain[1],
2410                    0.0,
2411                    cr_domain[0],
2412                    0.0,
2413                ).or_refuse(KernelStage::Refine, "parameter_line")?,
2414            });
2415        }
2416        coedges.extend(start_slot);
2417        if let Some(cs_edge_id) = cs_edge_id {
2418            coedges.push(CoedgeRecord {
2419                id: take_id(),
2420                edge_id: cs_edge_id,
2421                forward: cs_forward,
2422                pcurve: crate::sweep_topology::parameter_line(
2423                    cs_domain[0],
2424                    1.0,
2425                    cs_domain[1],
2426                    1.0,
2427                ).or_refuse(KernelStage::Refine, "parameter_line")?,
2428            });
2429        }
2430        coedges.extend(finish_slot);
2431        coedges
2432    };
2433    let blend_face_id = take_id();
2434    let mut blend_face = FaceRecord {
2435        id: blend_face_id,
2436        surface: rows.surface,
2437        same_sense,
2438        loops: vec![LoopRecord {
2439            id: loop_id,
2440            coedges,
2441        }],
2442        name: name.map(|value| value.to_string()),
2443    };
2444    if rows.exact_extrusion {
2445        transpose_face(&mut blend_face)?;
2446    }
2447    let shell_index = result
2448        .shells
2449        .iter()
2450        .position(|shell| shell.faces.iter().any(|face| face.id == first.face.id))
2451        .ok_or(KernelRefusal::internal(KernelStage::Sew, "mate_shell", "blend: mate shell lost during surgery"))?;
2452    // Drop the fully-consumed mate faces (lesson 3): their loops collapsed
2453    // between the sewn edge and the blend; the consumed boundaries and
2454    // lesson-7 leftovers are deleted below, the sewn edge lives on shared by
2455    // the blend face and the surviving neighbour.
2456    for (mate, sew) in [(first, &sew_first), (second, &sew_second)] {
2457        if sew.is_some() {
2458            for shell in &mut result.shells {
2459                shell.faces.retain(|face| face.id != mate.face.id);
2460            }
2461        }
2462    }
2463    result.shells[shell_index].faces.push(blend_face);
2464
2465    result.edges.retain(|candidate| candidate.id != edge.id);
2466    // Delete the boundary edges a prior fillet's corner had left behind that
2467    // this blend fully consumed.
2468    result
2469        .edges
2470        .retain(|candidate| !consumed_edges.contains(&candidate.id));
2471    // Each collapsed rail's two rims are one vertex.
2472    let mut identified = Vec::new();
2473    for (collapsed, from, to) in [(cr_collapsed, w1a, w1b), (cs_collapsed, w2a, w2b)] {
2474        if collapsed && from != to {
2475            identified.push((from, to));
2476        }
2477    }
2478    // The stopped-end rollover's sides: the rail past the crossing and the
2479    // cap's leg chain move onto the neighbours, and the end footprint is
2480    // re-traced on every face it touches.
2481    let mut cr_edge_id = cr_edge_id;
2482    let mut cs_edge_id = cs_edge_id;
2483    if tail.iter().any(Option::is_some) {
2484        let EndPlan::Cap(cap) = &finish_end else {
2485            return Err(KernelRefusal::unsupported(KernelStage::Sew, "stopped_end_rollover", "blend stopped-end rollover: the rolled stripe's finish end is not a cap, which is the only end this lane closes on the neighbours"));
2486        };
2487        let mut footprint = StoppedEndFootprint::default();
2488        // The cap plane at the finish vertex: through the sharp vertex, normal
2489        // the edge's tangent there; the fillet lies on the -tangent side.
2490        {
2491            let sharp = result.vertices.iter().find(|vertex| vertex.id == cap.sharp_vertex).map(|vertex| vertex.point)
2492                .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, "stopped_end_rollover", "blend stopped-end rollover: the sharp vertex vanished"))?;
2493            let d = edge.curve.derivatives(edge.t1, 1).or_refuse(KernelStage::Refine, "derivatives")?;
2494            footprint.plane = (sharp, d[1].normalized().or_refuse(KernelStage::Refine, "normalized")?);
2495            footprint.sharp_vertex = cap.sharp_vertex;
2496        }
2497        for (side, splice) in tail.into_iter().enumerate() {
2498            let Some(splice) = splice else { continue };
2499            let (mate, rail_edge_id, rim, sewn) = if side == 0 {
2500                (first, cr_edge_id, w1b, sew_first.is_some())
2501            } else {
2502                (second, cs_edge_id, w2b, sew_second.is_some())
2503            };
2504            let Some(rail_edge_id) = rail_edge_id.filter(|_| !sewn) else {
2505                return Err(KernelRefusal::unsupported(KernelStage::Sew, "stopped_end_rollover", "blend stopped-end rollover: a rolled side's rail collapsed or sewed onto an existing edge, which this lane does not split"));
2506            };
2507            let part_on_mate = roll_side_footprint(result, take_id, mate, &splice, rail_edge_id, rim, cap.sharp_vertex, &mut footprint)?;
2508            if side == 0 { cr_edge_id = Some(part_on_mate); } else { cs_edge_id = Some(part_on_mate); }
2509        }
2510        retrace_stopped_end_footprint(result, take_id, footprint)?;
2511    }
2512    Ok(SewnStripe {
2513        cr_edge_id,
2514        cs_edge_id,
2515        blend_face_id,
2516        consumed: [sew_first.is_some(), sew_second.is_some()],
2517        snap,
2518        identified,
2519    })
2520}
2521
2522/// A stopped-end rollover's footprint on the solid, gathered side by side
2523/// and re-traced once ([`retrace_stopped_end_footprint`]).
2524#[derive(Default)]
2525struct StoppedEndFootprint {
2526    /// The new boundary of the footprint, per face: (face, edge, from, to,
2527    /// pcurve from -> to on that face).
2528    pieces: Vec<(u64, u64, u64, u64, NurbsCurve)>,
2529    /// The faces whose loops change: the mates and every face a piece lies on.
2530    faces: Vec<u64>,
2531    /// The cap plane: (sharp point, unit edge tangent at the vertex). The
2532    /// fillet lies on the side opposite the tangent.
2533    plane: (Vec3, Vec3),
2534    sharp_vertex: u64,
2535}
2536
2537/// One rolled side, after the pristine sewing: the rail is split at the
2538/// crossing vertex (on the crossed tangent edge) and the tangent edge there;
2539/// the pristine splice's rail far part and first leg piece leave the mate's
2540/// loop (they belong to the neighbours), and the footprint's new boundary on
2541/// the neighbours — the far part with its pcurve on the neighbour by
2542/// projection, and the cap's leg chain — is recorded for the re-trace.
2543/// Returns the rail part left on the mate.
2544#[allow(clippy::too_many_arguments)]
2545fn roll_side_footprint(
2546    result: &mut BrepSolid,
2547    take_id: &mut dyn FnMut() -> u64,
2548    mate: &BlendMate,
2549    splice: &crate::blend::rollover::TailSplice<'_>,
2550    rail_edge_id: u64,
2551    rim_vertex: u64,
2552    sharp_vertex: u64,
2553    footprint: &mut StoppedEndFootprint,
2554) -> Result<u64, KernelRefusal> {
2555    let what = "stopped_end_rollover";
2556    let not_built = |message: String| KernelRefusal::unsupported(KernelStage::Sew, what, format!("blend stopped-end rollover: {message}"));
2557    let _ = sharp_vertex;
2558    let rolled = splice.rolled;
2559    let crossing_vertex = take_id();
2560    result.vertices.push(VertexRecord { id: crossing_vertex, point: rolled.point });
2561    let rail_parts = crate::blend::rollover_surgery::split_edge_at_vertices(result, rail_edge_id, &[(crossing_vertex, rolled.point)], take_id)?;
2562    let [rail_near, rail_far] = [rail_parts[0], rail_parts[1]];
2563    let rail_far_edge = result.edges.iter().find(|edge| edge.id == rail_far).cloned()
2564        .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, what, "blend stopped-end rollover: the rail's far part vanished"))?;
2565    if rail_far_edge.end_vertex_id != rim_vertex {
2566        return Err(not_built(format!("the rail's far part ends at vertex {} rather than the finish rim {rim_vertex}", rail_far_edge.end_vertex_id)));
2567    }
2568    // The crossed tangent edge, or the part of it the cap's leg chain left
2569    // holding the crossing (the chain may have split it already).
2570    let holds_crossing = |result: &BrepSolid, id: u64| -> Result<bool, KernelRefusal> {
2571        let Some(edge) = result.edges.iter().find(|edge| edge.id == id) else { return Ok(false) };
2572        let foot = crate::project_point_to_curve(&edge.curve, rolled.point).or_refuse(KernelStage::Refine, "project_point_to_curve")?;
2573        Ok(foot.distance <= 1e-6 && foot.u > edge.t0.min(edge.t1) && foot.u < edge.t0.max(edge.t1))
2574    };
2575    let crossed = if result.edges.iter().any(|edge| edge.id == rolled.edge_id) {
2576        rolled.edge_id
2577    } else {
2578        let candidates: Vec<u64> = result.edges.iter().map(|edge| edge.id).collect();
2579        let mut found = None;
2580        for id in candidates {
2581            if holds_crossing(result, id)? {
2582                found = Some(id);
2583                break;
2584            }
2585        }
2586        found.ok_or_else(|| not_built(format!("no part of tangent edge {} holds the crossing any more", rolled.edge_id)))?
2587    };
2588    crate::blend::rollover_surgery::split_edge_at_vertices(result, crossed, &[(crossing_vertex, rolled.point)], take_id)?;
2589    // The neighbour's pcurve of the rail's far part, by projection.
2590    let neighbour_surface = result
2591        .shells
2592        .iter()
2593        .flat_map(|shell| &shell.faces)
2594        .find(|face| face.id == rolled.neighbour_face_id)
2595        .map(|face| face.surface.clone())
2596        .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, what, "blend stopped-end rollover: the neighbour face vanished"))?;
2597    let far_pcurve = {
2598        const SAMPLES: usize = 24;
2599        let [t0, t1] = [rail_far_edge.t0, rail_far_edge.t1];
2600        let mut uvs = Vec::with_capacity(SAMPLES + 1);
2601        let mut ts = Vec::with_capacity(SAMPLES + 1);
2602        for k in 0..=SAMPLES {
2603            let t = t0 + (t1 - t0) * k as f64 / SAMPLES as f64;
2604            let point = rail_far_edge.curve.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?;
2605            let projection = crate::project_point_to_surface(&neighbour_surface, point).or_refuse(KernelStage::Refine, "project_point_to_surface")?;
2606            uvs.push(Vec3::new(projection.u, projection.v, 0.0));
2607            ts.push(t);
2608        }
2609        // Clamped over the rail part's own parameter interval (the edge's).
2610        crate::fit::interpolate_curve(&uvs, 3, &ts).or_refuse(KernelStage::Refine, "interpolate_curve")?
2611    };
2612    // The pristine splice's artefacts leave the mate's loop.
2613    let leg_edge_id = splice.legs.first().map(|piece| piece.edge_id)
2614        .ok_or_else(|| not_built("a rolled side has no cap leg".to_string()))?;
2615    let mate_face = result
2616        .shells
2617        .iter_mut()
2618        .flat_map(|shell| shell.faces.iter_mut())
2619        .find(|face| face.id == mate.face.id)
2620        .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, what, "blend stopped-end rollover: the mate face vanished"))?;
2621    mate_face.loops[mate.loop_index].coedges.retain(|coedge| coedge.edge_id != rail_far && coedge.edge_id != leg_edge_id);
2622    footprint.pieces.push((rolled.neighbour_face_id, rail_far, crossing_vertex, rim_vertex, far_pcurve));
2623    for piece in &splice.legs {
2624        footprint.pieces.push((piece.face_id, piece.edge_id, piece.from, piece.to, piece.pcurve.clone()));
2625    }
2626    for face_id in [mate.face.id, rolled.neighbour_face_id].into_iter().chain(splice.legs.iter().map(|piece| piece.face_id)) {
2627        if !footprint.faces.contains(&face_id) {
2628            footprint.faces.push(face_id);
2629        }
2630    }
2631    Ok(rail_near)
2632}
2633
2634/// Re-trace the footprint: an existing edge of an affected face whose both
2635/// ends lie on the footprint's new boundary and whose midpoint lies on the
2636/// fillet's side of the cap plane is INTERIOR to the footprint and deleted
2637/// (F10: edge 46 between the crossing and the cap leg's exit, edge 68
2638/// between its crossing and vertex 34); then every affected loop is traced
2639/// afresh through its remaining coedges and the new pieces — each vertex
2640/// of the new boundary has exactly one way on — the first closed trace
2641/// keeping the loop, every further one its own face on the same carrier
2642/// (F10: face 13's triangle beyond the cap plane).
2643fn retrace_stopped_end_footprint(
2644    result: &mut BrepSolid,
2645    take_id: &mut dyn FnMut() -> u64,
2646    footprint: StoppedEndFootprint,
2647) -> Result<(), KernelRefusal> {
2648    let what = "stopped_end_rollover";
2649    let not_built = |message: String| KernelRefusal::unsupported(KernelStage::Sew, what, format!("blend stopped-end rollover: {message}"));
2650    let (sharp_point, tangent) = footprint.plane;
2651    let mut boundary_vertices: Vec<u64> = vec![footprint.sharp_vertex];
2652    for (_, _, from, to, _) in &footprint.pieces {
2653        for vertex in [*from, *to] {
2654            if !boundary_vertices.contains(&vertex) {
2655                boundary_vertices.push(vertex);
2656            }
2657        }
2658    }
2659    let piece_edges: Vec<u64> = footprint.pieces.iter().map(|piece| piece.1).collect();
2660    // Interior edges, among those on the affected faces.
2661    let mut interior: Vec<u64> = Vec::new();
2662    for face in result.shells.iter().flat_map(|shell| &shell.faces).filter(|face| footprint.faces.contains(&face.id)) {
2663        for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
2664            let Some(edge) = result.edges.iter().find(|edge| edge.id == coedge.edge_id) else { continue };
2665            if piece_edges.contains(&edge.id) || interior.contains(&edge.id) {
2666                continue;
2667            }
2668            if !(boundary_vertices.contains(&edge.start_vertex_id) && boundary_vertices.contains(&edge.end_vertex_id)) {
2669                continue;
2670            }
2671            let mid = edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)).or_refuse(KernelStage::Refine, "evaluate")?;
2672            if mid.sub(sharp_point).dot(tangent) < 0.0 {
2673                interior.push(edge.id);
2674            }
2675        }
2676    }
2677    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
2678        eprintln!("stopped-end rollover: footprint faces {:?}, interior edges {:?}, boundary vertices {:?}", footprint.faces, interior, boundary_vertices);
2679    }
2680    let edge_ends: std::collections::HashMap<u64, (u64, u64)> = result.edges.iter().map(|edge| (edge.id, (edge.start_vertex_id, edge.end_vertex_id))).collect();
2681    let mut new_faces: Vec<FaceRecord> = Vec::new();
2682    // Face names the result uses (the app keys faces by name; this model
2683    // already carries `_1` splits of its own): a remnant takes a free suffix.
2684    let mut taken: Vec<String> = result.shells.iter().flat_map(|shell| &shell.faces).filter_map(|face| face.name.clone()).collect();
2685    for face_id in footprint.faces.clone() {
2686        let face = result
2687            .shells
2688            .iter_mut()
2689            .flat_map(|shell| shell.faces.iter_mut())
2690            .find(|face| face.id == face_id)
2691            .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, what, format!("blend stopped-end rollover: face {face_id} vanished")))?;
2692        let pieces: Vec<&(u64, u64, u64, u64, NurbsCurve)> = footprint.pieces.iter().filter(|piece| piece.0 == face_id).collect();
2693        let mut rebuilt_loops: Vec<LoopRecord> = Vec::new();
2694        for loop_record in &face.loops {
2695            let touched = loop_record.coedges.iter().any(|coedge| interior.contains(&coedge.edge_id))
2696                || loop_record.coedges.iter().any(|coedge| {
2697                    edge_ends.get(&coedge.edge_id).is_some_and(|(a, b)| boundary_vertices.contains(a) || boundary_vertices.contains(b))
2698                });
2699            if !touched {
2700                rebuilt_loops.push(loop_record.clone());
2701                continue;
2702            }
2703            // Directed remaining coedges (direction fixed, with their place in
2704            // the old loop) and undirected pieces.
2705            let n = loop_record.coedges.len();
2706            let mut remaining: Vec<(CoedgeRecord, u64, u64, usize)> = Vec::new();
2707            for (index, coedge) in loop_record.coedges.iter().enumerate() {
2708                if interior.contains(&coedge.edge_id) {
2709                    continue;
2710                }
2711                let (start, end) = edge_ends.get(&coedge.edge_id).copied()
2712                    .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, what, format!("blend stopped-end rollover: coedge {} names a missing edge {}", coedge.id, coedge.edge_id)))?;
2713                let (from, to) = if coedge.forward { (start, end) } else { (end, start) };
2714                remaining.push((coedge.clone(), from, to, index));
2715            }
2716            let mut loose: Vec<&(u64, u64, u64, u64, NurbsCurve)> = pieces.clone();
2717            // Trace closed walks: start at a remaining coedge, follow the
2718            // continuation at each vertex — the old loop's own successor when
2719            // it is there (a periodic face's loop passes its seam vertex
2720            // twice), else the unique way on.
2721            while !remaining.is_empty() {
2722                // Start on a coedge that is not a degenerate self-loop (a
2723                // periodic face's pole edge runs from a vertex to itself).
2724                let start_at = remaining.iter().position(|(_, from, to, _)| from != to).unwrap_or(0);
2725                let (first, from0, to0, index0) = remaining.remove(start_at);
2726                let mut walk: Vec<CoedgeRecord> = vec![first];
2727                let mut at = to0;
2728                let mut previous = index0;
2729                let mut guard = 0usize;
2730                loop {
2731                    guard += 1;
2732                    if guard > 4096 {
2733                        return Err(not_built(format!("face {face_id}: the re-trace does not close")));
2734                    }
2735                    let mut next_remaining: Vec<usize> = remaining.iter().enumerate().filter(|(_, (_, from, _, _))| *from == at).map(|(k, _)| k).collect();
2736                    let successor_is_start = (previous + 1) % n == index0;
2737                    if at == from0 && (successor_is_start || next_remaining.is_empty()) {
2738                        // Back at the start along the old loop's own order (a
2739                        // seam vertex passed twice does not close it early).
2740                        if at == from0 && successor_is_start {
2741                            break;
2742                        }
2743                        if loose.iter().all(|piece| piece.2 != at && piece.3 != at) {
2744                            break;
2745                        }
2746                    }
2747                    if next_remaining.len() > 1 {
2748                        if let Some(k) = next_remaining.iter().copied().find(|k| remaining[*k].3 == (previous + 1) % n) {
2749                            next_remaining = vec![k];
2750                        }
2751                    }
2752                    let next_pieces: Vec<usize> = loose.iter().enumerate().filter(|(_, piece)| piece.2 == at || piece.3 == at).map(|(k, _)| k).collect();
2753                    match (next_remaining.len(), next_pieces.len()) {
2754                        (1, 0) => {
2755                            let (coedge, _, to, index) = remaining.remove(next_remaining[0]);
2756                            walk.push(coedge);
2757                            at = to;
2758                            previous = index;
2759                        }
2760                        (0, 1) => {
2761                            let piece = loose.remove(next_pieces[0]);
2762                            let (edge_id, from, to, pcurve) = (piece.1, piece.2, piece.3, &piece.4);
2763                            let (start, _) = edge_ends.get(&edge_id).copied()
2764                                .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, what, format!("blend stopped-end rollover: footprint edge {edge_id} missing")))?;
2765                            let along = from == at;
2766                            let coedge_forward = if along { start == from } else { start == to };
2767                            walk.push(CoedgeRecord {
2768                                id: take_id(),
2769                                edge_id,
2770                                forward: coedge_forward,
2771                                pcurve: if along { pcurve.clone() } else { pcurve.reversed().or_refuse(KernelStage::Refine, "reversed")? },
2772                            });
2773                            at = if along { to } else { from };
2774                        }
2775                        (r, p) => {
2776                            return Err(not_built(format!("face {face_id}: vertex {at} has {} ways on ({r} boundary, {p} new), not one", r + p)));
2777                        }
2778                    }
2779                }
2780                rebuilt_loops.push(LoopRecord { id: if rebuilt_loops.is_empty() { loop_record.id } else { take_id() }, coedges: walk });
2781            }
2782            if !loose.is_empty() {
2783                return Err(not_built(format!("face {face_id}: {} new boundary piece(s) joined no loop", loose.len())));
2784            }
2785        }
2786        // The first loop keeps the face; every further closed trace of a
2787        // touched loop is a face of its own on the same carrier.
2788        let kept = rebuilt_loops.remove(0);
2789        face.loops = vec![kept];
2790        let surface = face.surface.clone();
2791        let same_sense = face.same_sense;
2792        let base_name = face.name.clone();
2793        for extra in rebuilt_loops {
2794            let name = base_name.as_ref().map(|base| {
2795                (1..).map(|k| format!("{base}_{k}")).find(|candidate| !taken.contains(candidate)).expect("a free name")
2796            });
2797            if let Some(name) = &name {
2798                taken.push(name.clone());
2799            }
2800            new_faces.push(FaceRecord { id: take_id(), surface: surface.clone(), same_sense, loops: vec![extra], name });
2801        }
2802    }
2803    if !new_faces.is_empty() {
2804        let shell_index = result.shells.iter().position(|shell| !shell.faces.is_empty())
2805            .ok_or_else(|| KernelRefusal::internal(KernelStage::Sew, what, "blend stopped-end rollover: no shell"))?;
2806        result.shells[shell_index].faces.extend(new_faces);
2807    }
2808    result.edges.retain(|edge| !interior.contains(&edge.id));
2809    Ok(())
2810}
2811
2812/// Swap the two parameters of a face: the surface's control net, every
2813/// coedge pcurve, and the sense (S_u × S_v changes sign).  The face's
2814/// geometry is untouched; only its chart is.  Used to hand an exact
2815/// cylinder patch built with its section along v to the analytic recogniser,
2816/// which wants the circle along u.
2817pub(in crate::blend) fn transpose_face(face: &mut FaceRecord) -> Result<(), KernelRefusal> {
2818    let surface = &face.surface;
2819    let rows_u = surface.control_points.len();
2820    let rows_v = surface.control_points.first().map(|row| row.len()).unwrap_or(0);
2821    let mut transposed = vec![Vec::with_capacity(rows_u); rows_v];
2822    for row in &surface.control_points {
2823        for (j, point) in row.iter().enumerate() {
2824            transposed[j].push(*point);
2825        }
2826    }
2827    face.surface = NurbsSurface::new(
2828        surface.degree_v,
2829        surface.degree_u,
2830        surface.knots_v.clone(),
2831        surface.knots_u.clone(),
2832        transposed,
2833    ).or_refuse(KernelStage::Refine, "new")?;
2834    for loop_record in &mut face.loops {
2835        for coedge in &mut loop_record.coedges {
2836            for control in &mut coedge.pcurve.control_points {
2837                std::mem::swap(&mut control.x, &mut control.y);
2838            }
2839        }
2840    }
2841    face.same_sense = !face.same_sense;
2842    Ok(())
2843}
2844
2845/// Drop every vertex no longer referenced by an edge — the sharp corners the
2846/// blends replaced, and anything freed by a consumed boundary.  Run ONCE after
2847/// a whole group of stripes is in: a corner vertex is still referenced by the
2848/// selected edges that have not been sewn yet.
2849pub(in crate::blend) fn prune_orphan_vertices(result: &mut BrepSolid) {
2850    let used: rustc_hash::FxHashSet<u64> = result
2851        .edges
2852        .iter()
2853        .flat_map(|candidate| [candidate.start_vertex_id, candidate.end_vertex_id])
2854        .collect();
2855    result
2856        .vertices
2857        .retain(|candidate| used.contains(&candidate.id));
2858}
2859
2860fn cs_blend_pcurve_reversed(cs_domain: &[f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
2861    crate::sweep_topology::parameter_line(cs_domain[1], 1.0, cs_domain[0], 1.0).or_refuse(KernelStage::Refine, "parameter_line")
2862}
2863
2864
2865