Skip to main content

brep_kernel/blending/blend/edge/
closed.rs

1use crate::{KernelRefusal, KernelStage, OrRefuse};
2use super::*;
3
4/// General closed-edge rolling-ball fillet or chamfer by direct §6.9 topology
5/// surgery. The refusal class of a concave closed rim whose fill overruns the
6/// plane it stands on (lane L, 2026-10-16).
7pub(crate) const CONCAVE_RIM_OVERRUN_WHAT: &str = "concave_rim_overrun";
8
9/// Lane L (2026-10-16): a CONCAVE closed rim standing on a PLANE — the rim one
10/// of the plane's INNER loops (a boss on a plate) — whose fill reaches past
11/// the plane's OUTER loop is not a face consumed up to one preserved far edge:
12/// the fill overruns the plate, and the body owed is that fill clipped by the
13/// plate's neighbouring faces. The edge-preserving construction found four
14/// "far" edges there and said "ambiguous preserved boundary edge". Read
15/// geometrically: the rim sampled, each sample stepped `radius` into the plane
16/// square to the rim (the fill's contact for a boss standing square to the
17/// plane), tested against the outer loop as a polygon in the plane (the chart
18/// clamps; the loop does not).
19fn concave_rim_overrun(
20    solid: &BrepSolid,
21    edge: &EdgeRecord,
22    mates: [(&FaceRecord, usize); 2],
23    radius: f64,
24) -> Result<Option<KernelRefusal>, KernelRefusal> {
25    const RIM_SAMPLES: usize = 64;
26    const LOOP_SAMPLES: usize = 256;
27    if edge.start_vertex_id != edge.end_vertex_id {
28        return Ok(None);
29    }
30    for (index, (face, rim_loop)) in mates.iter().copied().enumerate() {
31        if rim_loop == 0 {
32            continue;
33        }
34        let Some(crate::AnalyticSurface::Plane { origin, u_dir, v_dir, .. }) = face.surface.analytic() else { continue };
35        let wall = mates[1 - index].0;
36        let e1 = u_dir.normalized().or_refuse(KernelStage::Classify, "normalized")?;
37        let normal = u_dir.cross(*v_dir).normalized().or_refuse(KernelStage::Classify, "normalized")?;
38        let e2 = normal.cross(e1);
39        let flat = |p: Vec3| -> (f64, f64) { let d = p.sub(*origin); (d.dot(e1), d.dot(e2)) };
40        // The outer loop and the rim's own loop as polygons in the plane.
41        let polygon = |loop_index: usize| -> Result<Vec<(f64, f64)>, KernelRefusal> {
42            let mut points: Vec<(f64, f64)> = Vec::new();
43            for coedge in &face.loops[loop_index].coedges {
44                let Some(boundary) = solid.edges.iter().find(|candidate| candidate.id == coedge.edge_id) else { continue };
45                for k in 0..LOOP_SAMPLES {
46                    let f = k as f64 / LOOP_SAMPLES as f64;
47                    let t = if coedge.forward { boundary.t0 + (boundary.t1 - boundary.t0) * f } else { boundary.t1 - (boundary.t1 - boundary.t0) * f };
48                    points.push(flat(boundary.curve.evaluate(t).or_refuse(KernelStage::Classify, "evaluate")?));
49                }
50            }
51            Ok(points)
52        };
53        let (outer, rim_polygon) = (polygon(0)?, polygon(rim_loop)?);
54        let within = |points: &[(f64, f64)], x: f64, y: f64| -> bool {
55            crate::polygon::parity_inside([x, y], points.len(), |k| [points[k].0, points[k].1])
56        };
57        // The plate's region about the rim: inside the outer loop, outside the
58        // rim's own loop (where the boss stands).
59        let inside = |x: f64, y: f64| -> bool { within(&outer, x, y) && !within(&rim_polygon, x, y) };
60        // Concave: at a rim sample the wall's OUTWARD normal points into the
61        // plate's region (a boss facing out over its plate); a hole's wall
62        // faces its axis (convex) and is not this class.
63        {
64            let derivatives = edge.curve.derivatives(edge.t0, 1).or_refuse(KernelStage::Classify, "derivatives")?;
65            let (point, tangent) = (derivatives[0], derivatives[1]);
66            let side = normal.cross(tangent).normalized().or_refuse(KernelStage::Classify, "normalized")?;
67            // A twentieth of the radius: well past the sampled loops' chord
68            // sag, well inside the fill's own reach.
69            let probe = radius * 0.05;
70            let (px, py) = flat(point.add(side.scale(probe)));
71            let toward = if inside(px, py) { side } else { side.scale(-1.0) };
72            let foot = crate::project_point_to_surface(&wall.surface, point).or_refuse(KernelStage::Classify, "project_point_to_surface")?;
73            let wall_normal = wall.surface.normal(foot.u, foot.v).or_refuse(KernelStage::Classify, "normal")?;
74            let outward = if wall.same_sense { wall_normal } else { wall_normal.scale(-1.0) };
75            if outward.dot(toward) <= 0.0 {
76                continue;
77            }
78        }
79        let mut overruns = false;
80        for k in 0..RIM_SAMPLES {
81            let t = edge.t0 + (edge.t1 - edge.t0) * (k as f64 + 0.5) / RIM_SAMPLES as f64;
82            let derivatives = edge.curve.derivatives(t, 1).or_refuse(KernelStage::Classify, "derivatives")?;
83            let (point, tangent) = (derivatives[0], derivatives[1]);
84            let Ok(side) = normal.cross(tangent).normalized() else { continue };
85            // Into the plate: of the two in-plane normals to the rim, the one a
86            // small step along which stays inside the outer loop's region.
87            // A twentieth of the radius: well past the sampled loops' chord
88            // sag, well inside the fill's own reach.
89            let probe = radius * 0.05;
90            let toward = if inside(flat(point.add(side.scale(probe))).0, flat(point.add(side.scale(probe))).1) { side } else { side.scale(-1.0) };
91            let contact = flat(point.add(toward.scale(radius)));
92            if !within(&outer, contact.0, contact.1) {
93                overruns = true;
94                break;
95            }
96        }
97        if overruns {
98            return Ok(Some(KernelRefusal::unsupported(KernelStage::Classify, CONCAVE_RIM_OVERRUN_WHAT, format!(
99                "blend: the concave rim fill overruns the face's outer boundary — rolling on rim edge {}, the ball's contact on the plane {} it stands on (radius {radius} from the rim) reaches past that plane's outer loop, so the fill must be clipped by the plane's neighbouring faces, which this lane does not build",
100                edge.id,
101                face.name.clone().unwrap_or_else(|| format!("{}", face.id)),
102            ))));
103        }
104    }
105    Ok(None)
106}
107
108pub fn blend_closed_edge(
109    solid: &BrepSolid,
110    edge_id: u64,
111    radius: f64,
112    chamfer: bool,
113    name: Option<&str>,
114) -> Result<BrepSolid, KernelRefusal> {
115    // One blend operation: the reports of an earlier one, never consumed, are
116    // dropped as it starts (nested calls keep this operation's).
117    let _operation = crate::blend::BlendOperation::enter();
118    if !(radius > 0.0) || !radius.is_finite() {
119        return Err(KernelRefusal::input(KernelStage::Collect, "radius", "blend: radius must be positive"));
120    }
121    blend_closed_edge_impl(solid, edge_id, &|_| radius, Some(radius), chamfer, name)
122}
123
124/// [`blend_closed_edge`] with the closed-rim support refit's KNOT-AWARE retry
125/// (lane L, 2026-10-16): where a support pcurve's uniform track misses the floor,
126/// the fit is retried on a track that also samples the rail's own knots
127/// (`project_piece_pcurve_within_knot_retry`). Only for a caller whose refusal is
128/// TERMINAL for the whole operation — the fillet tool's last rung
129/// (`fillet/tool.rs`, `lcount201_knot_aware_last_rung_20261016`) on a refusal
130/// [`is_pcurve_floor_refusal`] reads: roads that call `blend_closed_edge` per
131/// rung and recover a floor miss themselves (the stadium, half-torus and box
132/// ladders) never see it.
133pub fn blend_closed_edge_knot_aware(
134    solid: &BrepSolid,
135    edge_id: u64,
136    radius: f64,
137    chamfer: bool,
138    name: Option<&str>,
139) -> Result<BrepSolid, KernelRefusal> {
140    let _operation = crate::blend::BlendOperation::enter();
141    if !(radius > 0.0) || !radius.is_finite() {
142        return Err(KernelRefusal::input(KernelStage::Collect, "radius", "blend: radius must be positive"));
143    }
144    KNOT_RETRY.with(|flag| flag.set(true));
145    let built = blend_closed_edge_impl(solid, edge_id, &|_| radius, Some(radius), chamfer, name);
146    KNOT_RETRY.with(|flag| flag.set(false));
147    built
148}
149
150/// A refusal for a support pcurve that does not reach the refinement floor —
151/// read off its CLASS and code (`CHAIN_PCURVE_FLOOR_WHAT`,
152/// `CLOSED_SUPPORT_PCURVE_FLOOR_WHAT`), never its wording.
153pub fn is_pcurve_floor_refusal(refusal: &KernelRefusal) -> bool {
154    matches!(&refusal.class, crate::RefusalClass::NonConvergence { what }
155        if what == crate::blend::chain::CHAIN_PCURVE_FLOOR_WHAT || what == CLOSED_SUPPORT_PCURVE_FLOOR_WHAT)
156}
157
158/// The code of a closed-rim support refit that misses the floor as shipped.
159pub(crate) const CLOSED_SUPPORT_PCURVE_FLOOR_WHAT: &str = "closed_support_pcurve_floor";
160
161/// Variable-radius blend (4.9.5): radius stops as (edge fraction, radius)
162/// pairs, linearly interpolated along the edge parameter and clamped at
163/// the ends.  Closed edges must supply matching first/last radii.
164pub fn blend_edge_variable(
165    solid: &BrepSolid,
166    edge_id: u64,
167    radii: &[(f64, f64)],
168    chamfer: bool,
169    name: Option<&str>,
170) -> Result<BrepSolid, KernelRefusal> {
171    // One blend operation: the reports of an earlier one, never consumed, are
172    // dropped as it starts (nested calls keep this operation's).
173    let _operation = crate::blend::BlendOperation::enter();
174    if radii.is_empty() || radii.iter().any(|(_, radius)| !(*radius > 0.0)) {
175        return Err(KernelRefusal::input(KernelStage::Collect, "radius_stop", "blend: every radius stop must be positive"));
176    }
177    let mut stops = radii.to_vec();
178    stops.sort_by(|a, b| a.0.total_cmp(&b.0));
179    let edge = solid
180        .edges
181        .iter()
182        .find(|edge| edge.id == edge_id)
183        .ok_or_else(|| format!("blend: edge {edge_id} not found")).or_refuse(KernelStage::Refine, "ok_or_else")?;
184    let closed = edge.start_vertex_id == edge.end_vertex_id;
185    if closed && (stops[0].1 - stops[stops.len() - 1].1).abs() > 1e-12 {
186        return Err(KernelRefusal::input(KernelStage::Collect, "closed_edge_radii", "blend: closed edges need equal first/last radii"));
187    }
188    // CONSTANT stops must DEGENERATE to the exact constant-radius
189    // machinery (§6.9 exact cylinder cutters where the mates allow them,
190    // the same general march otherwise).  The general march's fitted
191    // NURBS is geometrically exact for a constant radius, but downstream
192    // booleans treat it as a generic surface: marched SSI curves against
193    // a tangent mate drift O(√ε) along the tangency (measured 1.2e-3 on
194    // a 10-box chain miter), while the exact representation intersects
195    // analytically — this is what keeps chain-corner miters composable.
196    let first_radius = stops[0].1;
197    if stops
198        .iter()
199        .all(|(_, radius)| (radius - first_radius).abs() <= 1e-12 * (1.0 + first_radius.abs()))
200    {
201        return if chamfer {
202            crate::fillet::chamfer_edge(solid, edge_id, first_radius, name)
203        } else {
204            crate::fillet::fillet_edge(solid, edge_id, first_radius, name)
205        };
206    }
207    let (t0, t1) = (edge.t0, edge.t1);
208    let radius_at = move |t: f64| -> f64 {
209        let raw = (t - t0) / (t1 - t0);
210        // Closed edges WRAP (the anchored march may start mid-edge and run
211        // past t1 once around — clamping misplaced mid-profile stops
212        // there); open edges CLAMP flat past the ends, which is only the
213        // marched overshoot region beyond the trims.  The blend-end
214        // stations are pinned exactly at t0/t1 by the open march, so the
215        // profile kink the clamp creates sits ON an interpolation node and
216        // the fitted rows still pass through the closed-form end stations.
217        let fraction = if closed {
218            raw.rem_euclid(1.0)
219        } else {
220            raw.clamp(0.0, 1.0)
221        };
222        if fraction <= stops[0].0 {
223            return stops[0].1;
224        }
225        for pair in stops.windows(2) {
226            if fraction <= pair[1].0 {
227                let width = (pair[1].0 - pair[0].0).max(1e-12);
228                let local = (fraction - pair[0].0) / width;
229                return pair[0].1 + (pair[1].1 - pair[0].1) * local;
230            }
231        }
232        stops[stops.len() - 1].1
233    };
234    // A VARIABLE profile (constant stops left above for the constant entry):
235    // no constant-radius provenance, so no rolling-ball wall verdict.
236    if closed {
237        blend_closed_edge_impl(solid, edge_id, &radius_at, None, chamfer, name)
238    } else {
239        blend_open_edge_impl(solid, edge_id, &radius_at, None, chamfer, name)
240    }
241}
242
243/// `constant`: the radius when the blend came in through a CONSTANT-radius
244/// entry point (`blend_closed_edge`), `None` for a variable profile — the
245/// only provenance on which the wall is judged against one rolling ball.
246fn blend_closed_edge_impl(
247    solid: &BrepSolid,
248    edge_id: u64,
249    radius_at: &dyn Fn(f64) -> f64,
250    constant: Option<f64>,
251    chamfer: bool,
252    name: Option<&str>,
253) -> Result<BrepSolid, KernelRefusal> {
254    let _closed_timing = crate::blend::BlendTimer::start("timing.closed_rim_ms");
255    let prepare_timing = crate::blend::BlendTimer::start("timing.closed.prepare_ms");
256    if let Some(separated) = separate_spherical_domain_cut(solid, edge_id)? {
257        return blend_closed_edge_impl(&separated, edge_id, radius_at, constant, chamfer, name);
258    }
259    if let Some(simplified) = remove_retraced_cuts(solid, edge_id)? {
260        return blend_closed_edge_impl(&simplified, edge_id, radius_at, constant, chamfer, name);
261    }
262    let edge = solid
263        .edges
264        .iter()
265        .find(|edge| edge.id == edge_id)
266        .ok_or_else(|| format!("blend: edge {edge_id} not found")).or_refuse(KernelStage::Refine, "ok_or_else")?;
267    if edge.start_vertex_id != edge.end_vertex_id {
268        return Err(KernelRefusal::input(KernelStage::Collect, "closed_edge", "blend: general path currently requires a CLOSED edge"));
269    }
270    let (face_a, loop_a, coedge_a) = locate_mate(solid, edge_id, None)?;
271    let (face_b, loop_b, coedge_b) = locate_mate(solid, edge_id, Some((face_a.id, loop_a)))?;
272    if face_a.id == face_b.id && loop_a == loop_b {
273        return Err(KernelRefusal::unsupported(KernelStage::Classify, "seam_edge", "blend: edge is used twice by one loop (seam edge?)"));
274    }
275
276    // Seam-structured loops force the blend seam onto that carrier's seam
277    // meridian; at most one mate may need it.
278    let seam_a = face_a.loops[loop_a].coedges.len() > 1;
279    let seam_b = face_b.loops[loop_b].coedges.len() > 1;
280    let (first_face, first_loop, first_coedge, second_face, second_loop, second_coedge) =
281        if seam_a || !seam_b {
282            (face_a, loop_a, coedge_a, face_b, loop_b, coedge_b)
283        } else {
284            (face_b, loop_b, coedge_b, face_a, loop_a, coedge_a)
285        };
286    let anchored = first_face.loops[first_loop].coedges.len() > 1;
287    let second_seam = anchored && second_face.loops[second_loop].coedges.len() > 1;
288    let anchor_u = if anchored {
289        // Lock onto the carrier's seam meridian: the u-domain start.
290        Some(first_face.surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?[0])
291    } else {
292        None
293    };
294
295    // Signed radii from the cross-section seed at the edge midpoint.
296    let mid_radius = radius_at(edge.t0 + (edge.t1 - edge.t0) * 0.5);
297    let (rho1, rho2) = signed_radii(
298        edge,
299        first_face,
300        first_coedge,
301        second_face,
302        second_coedge,
303        mid_radius,
304    )?;
305
306    let first_mate = BlendMate {
307        face: first_face,
308        coedge: first_coedge,
309        loop_index: first_loop,
310        rho: rho1,
311    };
312    let second_mate = BlendMate {
313        face: second_face,
314        coedge: second_coedge,
315        loop_index: second_loop,
316        rho: rho2,
317    };
318    let mid_t = edge.t0 + (edge.t1 - edge.t0) * 0.5;
319    // Anchored FIRST, always — everything that already works takes this rung
320    // and is unchanged.  An anchored march freezes the first carrier's u on
321    // its seam meridian and frees t (`solve_anchored_start`), so it is only
322    // solvable when the edge actually reaches that meridian.  A closed edge
323    // cut by a plane through a surface of revolution's AXIS is one whole
324    // MERIDIAN of that carrier — constant u, a full turn in v — so no station
325    // on it can sit at the seam, and the seam may even have been trimmed off
326    // the face (the 2026-09-01 reported document: the kept torus was
327    // u ∈ [0.1369, 0.8869] while the anchor locked u = 0).  That march reports
328    // "anchored seam start did not converge"; the UNANCHORED march solves the
329    // same edge exactly, because the edge's own endpoints already sit on the
330    // carrier's OTHER (v) seam.  Retrying is what makes this a rung of the
331    // existing ladder rather than a predicate with a tolerance to tune: a
332    // march that needs its anchor still gets one.
333    use crate::blend::chain::FoldPolicy;
334    let march_with = |fold: FoldPolicy, depth_budget: usize| -> Result<Vec<Station>, KernelRefusal> {
335        match march_stations(edge, &first_mate, &second_mate, radius_at, anchor_u, fold, depth_budget) {
336            Ok(stations) => Ok(stations),
337            Err(anchored_error) if anchor_u.is_some() => {
338                march_stations(edge, &first_mate, &second_mate, radius_at, None, fold, depth_budget).map_err(
339                    |retry_error| {
340                        if crate::blend::is_wall_fold(&retry_error)
341                        || crate::blend::is_marched_fit_off_carriers(&retry_error) {
342                            retry_error
343                        } else {
344                            anchored_error
345                        }
346                    },
347                )
348            }
349            Err(anchored_error) => Err(anchored_error),
350        }
351    };
352    let rail_bar = 0.5 * crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
353    // A FILLET of one constant radius is also judged on its wall between the
354    // rails, against that ball's sweep, at the unchanged `intersection_fit`
355    // (`ClosedWallCheck`); a chamfer or a varying radius is not.
356    let wall_check = {
357        // Constant-radius PROVENANCE (the entry point), never sampled
358        // constancy: a variable profile can agree at any finite set of samples.
359        let radius = constant.unwrap_or(f64::NAN);
360        let constant = constant.is_some();
361        // The construction request as on the closed chain's plain fillet
362        // rungs: `KernelTolerances::model` on the wall between the rails.
363        let model = crate::KernelTolerances::for_solid(solid, 1e-7).model;
364        let bar = crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
365        (!chamfer && constant && radius.is_finite() && radius != 0.0).then(|| crate::blend::stations::ClosedWallCheck {
366            radius: radius.abs(),
367            bar,
368            model: model.is_finite().then_some(model),
369        })
370    };
371    crate::blend::stations::CLOSED_MODEL_UNMET.with(|slot| slot.set(None));
372    crate::blend::stations::CLOSED_REQUEST_RAILS.with(|slot| slot.set(None));
373    prepare_timing.stop();
374    let exact_revolution = crate::blend::exact_rim_lane_on()
375        && crate::blend::stations::closed_revolution_axis(&first_mate, &second_mate).is_some();
376    let depth_budget = if exact_revolution { 0 } else { MAX_REFINEMENT_DEPTH };
377    if exact_revolution {
378        crate::blend::record_count("count.closed.exact_lane", 1);
379    }
380    let march_timing = crate::blend::BlendTimer::start("timing.closed.march_ms");
381    let attempt_timing = crate::blend::BlendTimer::start("timing.closed.march.anchored_fallback_ms");
382    let analytic = crate::blend::stations::analytic_rim::construct(
383        edge, &first_mate, &second_mate, constant, chamfer, anchor_u,
384    );
385    let (analytic_stations, analytic_rows) = match analytic {
386        Some((stations, rows)) => (Some(stations), Some(rows)),
387        None => (None, None),
388    };
389    let marched = match analytic_stations.map(Ok).unwrap_or_else(|| march_stations_with_rail_bar(edge, &first_mate, &second_mate, radius_at, anchor_u, FoldPolicy::Refuse, depth_budget, rail_bar, wall_check)) {
390        Ok(stations) => {
391            std::mem::forget(attempt_timing);
392            Ok(stations)
393        }
394        Err(failure) => {
395            // Post-refinement errors return directly, before either the
396            // unanchored retry or the legacy edge-preserving construction.
397            let anchored_error = failure.into_initial()?;
398            if anchor_u.is_some() {
399                attempt_timing.stop();
400                crate::blend::record_count("count.closed.march.anchor_fallback", 1);
401                if std::env::var("BREP_DEBUG_CLOSED_RAILS").is_ok() {
402                    eprintln!("closed initial anchor fallback: edge {}: {anchored_error}", edge.id);
403                }
404                match march_stations_with_rail_bar(edge, &first_mate, &second_mate, radius_at, None, FoldPolicy::Refuse, depth_budget, rail_bar, wall_check) {
405                    Ok(stations) => Ok(stations),
406                    Err(failure) => {
407                        let retry_error = failure.into_initial()?;
408                        if crate::blend::is_wall_fold(&retry_error) { Err(retry_error) }
409                        else { Err(anchored_error) }
410                    }
411                }
412            } else { Err(anchored_error) }
413        }
414    };
415    // A wall that FOLDS through itself: the lens of the envelope inside the
416    // swept ball volume is CARVED (`blend/carve.rs`), the way the closed chain
417    // lane carves it, and the crease sewn as an inner loop of the blend face.
418    // A fold that reaches a RAIL is not a lens (nothing to keep on one side)
419    // and stays the named refusal; so does a chamfer's (a straight section
420    // has no ball centre to read the fold locus against).  The march is
421    // re-run under `FoldPolicy::Carve` so the folding wall is built; the lane
422    // then checks the fitted rows are accurate enough to carve and that the
423    // lens does not straddle the wall's own seam before anything is cut.
424    // The march's unmet construction request (if any), taken before any other
425    // march runs; it is reported only for the plain wall this lane builds
426    // from that march's stations.
427    let model_unmet = crate::blend::stations::CLOSED_MODEL_UNMET.with(|slot| slot.take());
428    let request_rails = crate::blend::stations::CLOSED_REQUEST_RAILS.with(|slot| slot.take());
429    let mut carve_fold = false;
430    // The CARVE LADDER (see below): the stations a folding wall is carved
431    // from, or the refusal that there is no wall accurate enough to carve.
432    // Shared by the march's own fold verdict and by the rows-loop verdict
433    // read after the fit (2026-10-17: `fillet-mouth-over-wall-bore-5p5-r2p2`'s
434    // F2 wall loops at the rim's midpoint without the march's centre-curve
435    // verdict ever firing).
436    let climb_carve_ladder = |error: &KernelRefusal| -> Result<Vec<Station>, KernelRefusal> {
437        let rail_bar = 0.5 * crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
438        let mut climbed: Option<Vec<Station>> = None;
439        let mut last_off = f64::NAN;
440        for depth_budget in MAX_REFINEMENT_DEPTH..=CARVE_MAX_REFINEMENT_DEPTH {
441            let stations = match march_with(FoldPolicy::Carve, depth_budget) {
442                Ok(stations) => stations,
443                // The Carve march did not build: the fold stays the answer.
444                Err(_) => break,
445            };
446            let parameters = crate::blend::stations::closed_station_parameters(&stations, [&first_mate.face.surface, &second_mate.face.surface]);
447            let off = match fit_closed_rows(&stations, &parameters, chamfer) {
448                Ok(rows) => rails_off_closed_carriers(&rows, &stations, &parameters, &first_mate, &second_mate)?,
449                Err(_) => break,
450            };
451            last_off = off;
452            crate::blend::carve::carve_trace(format_args!(
453                "blend closed-edge carve ladder: depth budget {depth_budget} ({} stations) leaves the rails {off:.3e} off their carriers (bar {rail_bar:.3e})",
454                stations.len()
455            ));
456            if off <= rail_bar {
457                climbed = Some(stations);
458                break;
459            }
460        }
461        climbed.ok_or_else(|| {
462            crate::blend::fold::wall_fold_refusal(
463                Vec::new(),
464                format!(
465                    "{} {} fits this edge: the wall folds, and at depth budget {CARVE_MAX_REFINEMENT_DEPTH} — the top of the closed march's carve ladder — its fitted rails still stand {last_off:.3e} off their carriers between stations against a bar of {rail_bar:.3e}, so there is no wall accurate enough to carve ({error})",
466                    crate::blend::WALL_FOLDS,
467                    radius_at(mid_t).abs()
468                ),
469            )
470        })
471    };
472    let marched = match marched {
473        Err(error)
474            if crate::blend::is_wall_fold(&error)
475                && !crate::blend::fold::is_rail_fold(&error)
476                && !chamfer =>
477        {
478            crate::blend::carve::carve_trace(format_args!(
479                "blend closed-edge: the wall folds ({error}); re-marching under Carve"
480            ));
481            match climb_carve_ladder(&error) {
482                Ok(stations) => {
483                    carve_fold = true;
484                    Ok(stations)
485                }
486                Err(refusal) => Err(refusal),
487            }
488        }
489        other => other,
490    };
491    let mut stations = match marched {
492        Ok(stations) => stations,
493        // A wall that FOLDS is refused here for the same reason an escaped
494        // march is: the edge-preserving construction would build a blend on the
495        // same folding centre curve, and if it converged it would return the
496        // very surface this refusal exists to stop.  It is not the fallback's
497        // question to answer, so the geometry is reported as-is.
498        Err(march_error) if crate::blend::is_wall_fold(&march_error)
499            || crate::blend::is_marched_fit_off_carriers(&march_error) => return Err(march_error),
500        Err(march_error) if crate::blend::is_ball_off_carrier(&march_error) => {
501            // An ESCAPED march is not a non-convergence: the tangency system
502            // had no solution at all, so no fallback can build the blend the
503            // rolling ball never made.  Report the escape itself — routing it
504            // to the edge-preserving construction below only reports THAT
505            // lane's complaint about a face it was never meant to consume
506            // ("ambiguous preserved boundary edge" on the 2026-09-10 report).
507            return Err(march_error);
508        }
509        Err(march_error) => {
510            // Lane L (2026-10-16): a concave rim overrunning its plane is
511            // named before the edge-preserving construction misreads it.
512            if let Some(refusal) = concave_rim_overrun(solid, edge, [(first_face, first_loop), (second_face, second_loop)], radius_at(mid_t))? {
513                return Err(refusal);
514            }
515            // A non-converging march often means the rolling ball falls off
516            // one face — try the edge-preserving construction (4.9.7).
517            return blend_closed_edge_keep(
518                solid,
519                edge,
520                &first_mate,
521                &second_mate,
522                radius_at(mid_t),
523                rho1,
524                chamfer,
525                name,
526            )
527            .or_else(|_| {
528                blend_closed_edge_keep(
529                    solid,
530                    edge,
531                    &second_mate,
532                    &first_mate,
533                    radius_at(mid_t),
534                    rho2,
535                    chamfer,
536                    name,
537                )
538            })
539            .map_err(|keep_error| {
540                format!("{march_error}; edge-preserving blend also failed: {keep_error}")
541            }).or_refuse(KernelStage::Refine, "map_err");
542        }
543    };
544    // Support-out-of-trim detection (4.9.7 trigger): a tangency track that
545    // leaves its face's trimmed region cannot be trimmed there — the far
546    // boundary must be PRESERVED instead.
547    let support_exits = |face: &FaceRecord, second_side: bool| -> bool {
548        // Adaptive marches vary the station count; keep at least the old fixed
549        // grid's ~16-probe floor while inheriting extra density where the
550        // march refined (which is where an exit would hide).
551        let stride = (stations.len() / 16).max(1);
552        stations.iter().step_by(stride).any(|station| {
553            support_exits_at(face, if second_side { station.uv2 } else { station.uv1 })
554        })
555    };
556    // The edge-preserving construction below cannot answer it (it consumes
557    // the mate up to one preserved far boundary; a rolled track has none) and
558    // on the reported bore mouth it said "ambiguous preserved boundary edge"
559    // about a face it was never meant to consume. The crossings are located
560    // and the lane declines BY NAME; the ladder falls through to the cutter
561    // as before. An exit across a sharp boundary, or onto a tangent neighbour
562    // the ball cannot roll onto, keeps the route below unchanged.
563    let exits_timing = crate::blend::BlendTimer::start("timing.closed.march.exits_ms");
564    // A mate bounded only by parallels of the rim's axis answers for all its
565    // stations with ONE probe (`support_exit_between_parallels`); any other
566    // mate, and any station near a boundary, takes the full probe scan.
567    let revolution = crate::blend::stations::closed_revolution_axis(&first_mate, &second_mate);
568    let exit_of = |face: &FaceRecord, second_side: bool| -> bool {
569        let contacts: Vec<Vec3> = stations.iter().map(|station| if second_side { station.p2 } else { station.p1 }).collect();
570        let probe = |station: usize| -> bool {
571            support_exits_at(face, if second_side { stations[station].uv2 } else { stations[station].uv1 })
572        };
573        match revolution.and_then(|axis| support_exit_between_parallels(solid, face, axis, &contacts, &probe)) {
574            Some(exit) => {
575                crate::blend::record_count("count.closed.exits_by_parallels", 1);
576                exit
577            }
578            None => support_exits(face, second_side),
579        }
580    };
581    let exits = [exit_of(first_face, false), exit_of(second_face, true)];
582    exits_timing.stop();
583    if exits[0] || exits[1] {
584        let scale = crate::blend::stations::march_model_scale(&edge.curve, edge.t0, edge.t1, radius_at(mid_t))?;
585        match crate::blend::rollover::plan_closed(solid, edge, &stations, [&first_mate, &second_mate], radius_at, scale) {
586            Ok(Some(plan)) => {
587                // The BUILD (behind its switch): every piece marched on its
588                // own carriers and fitted, then sewn on the crossing ribs.
589                if crate::blend::rollover_on() {
590                    let pieces = crate::blend::rollover::march_pieces(
591                        solid, edge, &plan, &stations, [&first_mate, &second_mate], radius_at, scale, rail_bar, chamfer, anchor_u,
592                    )?;
593                    let built = crate::blend::rollover::build(solid, edge, [&first_mate, &second_mate], &plan, pieces, anchor_u, name)?;
594                    march_timing.stop();
595                    return Ok(built);
596                }
597                return Err(crate::blend::rollover::refusal(&plan, radius_at(mid_t).abs()));
598            }
599            Ok(None) => {}
600            Err(error) => {
601                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
602                    eprintln!("closed-rim rollover scan did not read the exit: {error}");
603                }
604            }
605        }
606    }
607    if let Some(refusal) = concave_rim_overrun(solid, edge, [(first_face, first_loop), (second_face, second_loop)], radius_at(mid_t))? {
608        return Err(refusal);
609    }
610    if exits[1] {
611        return blend_closed_edge_keep(
612            solid,
613            edge,
614            &first_mate,
615            &second_mate,
616            radius_at(mid_t),
617            rho1,
618            chamfer,
619            name,
620        );
621    }
622    if exits[0] {
623        return blend_closed_edge_keep(
624            solid,
625            edge,
626            &second_mate,
627            &first_mate,
628            radius_at(mid_t),
629            rho2,
630            chamfer,
631            name,
632        );
633    }
634    if std::env::var("BREP_DEBUG_BLEND_MARCH").is_ok() {
635        let last = stations.len() - 1;
636        for index in [
637            0usize,
638            1.min(last),
639            2.min(last),
640            last.saturating_sub(1),
641            last,
642        ] {
643            let station = &stations[index];
644            eprintln!(
645                "station {index}: uv1=({:.6},{:.6}) uv2=({:.6},{:.6}) p1=({:.6},{:.6},{:.6}) w={:.6}",
646                station.uv1[0], station.uv1[1], station.uv2[0], station.uv2[1],
647                station.p1.x, station.p1.y, station.p1.z, station.weight,
648            );
649        }
650    }
651    march_timing.stop();
652    crate::blend::record_count("count.closed.stations", stations.len() as u64);
653    let rows_timing = crate::blend::BlendTimer::start("timing.closed.rows_ms");
654    let mut parameters = crate::blend::stations::closed_station_parameters(&stations, [&first_mate.face.surface, &second_mate.face.surface]);
655    let exact_rows = analytic_rows.map(Ok).or_else(|| exact_closed_revolution_rows(&stations, &first_mate, &second_mate, chamfer));
656    crate::blend::record_count(
657        if exact_rows.is_some() { "count.rows.exact_revolution" } else { "count.rows.fitted_closed" },
658        1,
659    );
660    let rows = match exact_rows {
661        Some(rows) => rows?,
662        None => {
663            // The support pcurves interpolate the stations' (u, v) and are
664            // read nowhere between them: on the 20-degree crossing's single
665            // closed exit edge they stood 1.01e-4 (thin carrier) and
666            // 2.6e-5 to 3.8e-5 (fat carrier) off the rails they trim, while the
667            // rails stood on their carriers to 1e-6 — the whole of a 5e-6 to
668            // 1.1e-5 shell vector-area residual and of a seam-placement-
669            // dependent volume (dumps of c5ea8fb80 and 635ef7630, read
670            // input-free). Each is refitted to its rail's own projected track
671            // at the pcurve floor, by the closed chain's support-piece fitter.
672            let fit_timing = crate::blend::BlendTimer::start("timing.closed.rows.fit_ms");
673            let mut rows = fit_closed_rows(&stations, &parameters, chamfer)?;
674            fit_timing.stop();
675            // THE ROWS-LOOP VERDICT (2026-10-17): the fitted wall itself may
676            // pass back through itself along a row where the march's
677            // centre-curve verdict never fired (`fold::check_rows_loop`;
678            // `fillet-mouth-over-wall-bore-5p5-r2p2`'s F2 wall at the rim's
679            // midpoint). Such a wall is a folding wall, and takes the same
680            // road the march's own fold verdict takes: re-marched under
681            // Carve up the ladder, and its lens carved below.
682            if !carve_fold && !chamfer {
683                if let Err(error) = crate::blend::fold::check_rows_loop(
684                    &rows, &stations, &parameters, None, radius_at(mid_t).abs(), vec![first_face.id, second_face.id], crate::solid_scale(solid),
685                ) {
686                    crate::blend::carve::carve_trace(format_args!(
687                        "blend closed-edge: the fitted rows loop ({error}); re-marching under Carve"
688                    ));
689                    stations = climb_carve_ladder(&error)?;
690                    parameters = crate::blend::stations::closed_station_parameters(&stations, [&first_mate.face.surface, &second_mate.face.surface]);
691                    rows = fit_closed_rows(&stations, &parameters, chamfer)?;
692                    carve_fold = true;
693                }
694            }
695            // Lane G row 2 (behind `closed_trim_read_first_on`): each trim
696            // is first read as shipped at the floor and refitted only on a
697            // miss (`closed_support_trim`); off the switch, the refit as before.
698            let read_first = crate::blend::closed_trim_read_first_on();
699            let refit_timing = crate::blend::BlendTimer::start("timing.closed.rows.refit_first_ms");
700            rows.cr_pcurve = if read_first {
701                closed_support_trim(&rows.cr, &rows.cr_pcurve, &first_mate.face.surface)?
702            } else {
703                refit_closed_support_pcurve(&rows.cr, &rows.cr_pcurve, &first_mate.face.surface)?
704            };
705            refit_timing.stop();
706            let refit_timing = crate::blend::BlendTimer::start("timing.closed.rows.refit_second_ms");
707            rows.cs_pcurve = if read_first {
708                closed_support_trim(&rows.cs, &rows.cs_pcurve, &second_mate.face.surface)?
709            } else {
710                refit_closed_support_pcurve(&rows.cs, &rows.cs_pcurve, &second_mate.face.surface)?
711            };
712            refit_timing.stop();
713            rows
714        }
715    };
716    rows_timing.stop();
717    let carve_timing = crate::blend::BlendTimer::start("timing.closed.carve_ms");
718    let crease = if carve_fold {
719        Some(carve_closed_wall(solid, &rows, &stations, &parameters, &first_mate, &second_mate, radius_at(mid_t).abs())?)
720    } else {
721        None
722    };
723    carve_timing.stop();
724    let surgery_timing = crate::blend::BlendTimer::start("timing.closed.surgery_ms");
725
726    // Both mates seam-structured: the second support crosses ITS carrier's
727    // seam meridian somewhere mid-loop; split cs there so face2's loop can
728    // keep its seam-in-one-loop structure.
729    let second_split = if second_seam {
730        let seam2 = second_face.surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?[0];
731        let period2 = {
732            let [d0, d1] = second_face.surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
733            d1 - d0
734        };
735        // Bracket: unwrapped uv2 track crossing seam2 + k·period.
736        let u2_first = stations[0].uv2[0];
737        let u2_last = stations[stations.len() - 1].uv2[0];
738        let direction = (u2_last - u2_first).signum();
739        let mut k = ((u2_first - seam2) / period2).ceil();
740        if direction < 0.0 {
741            k = ((u2_first - seam2) / period2).floor();
742        }
743        let target = seam2 + k * period2;
744        let inside =
745            (target - u2_first) * direction > 1e-6 && (u2_last - target) * direction > 1e-6;
746        // ALIGNED seams (both carriers' meridians meet at the shared
747        // vertex — the natural coaxial construction): the crossing sits
748        // at the march boundary and no mid-loop split is needed; the
749        // blend seam vertex already lies on both meridians.
750        let aligned = (target - u2_first).abs() <= 1e-6
751            || (target - u2_last).abs() <= 1e-6
752            || ((u2_first - seam2) / period2).fract().abs() <= 1e-9;
753        if !inside && aligned {
754            None
755        } else if !inside {
756            return Err(KernelRefusal::internal(KernelStage::Refine, "seam_crossing_bracket", "blend: second seam crossing not bracketed by the march"));
757        } else {
758            // Fit-space crossing parameter on the fitted cs (Newton via the
759            // fitted pcurve so the split lands exactly where the FITTED track
760            // crosses the meridian).
761            let [fit_low, fit_high] = rows.u_domain;
762            let mut p = fit_low
763                + (fit_high - fit_low) * {
764                    // Seed from the bracketing stations.
765                    let mut seed = 0.5;
766                    for pair in 0..stations.len() - 1 {
767                        let a = stations[pair].uv2[0];
768                        let b = stations[pair + 1].uv2[0];
769                        if (target - a) * (target - b) <= 0.0 {
770                            let local = (target - a) / (b - a);
771                            seed = (parameters[pair]
772                                + (parameters[pair + 1] - parameters[pair]) * local)
773                                .clamp(0.0, 1.0);
774                            break;
775                        }
776                    }
777                    seed
778                };
779            for _ in 0..NEWTON_ITERATIONS {
780                let value = rows.cs_pcurve.evaluate(p).or_refuse(KernelStage::Refine, "evaluate")?.x - target;
781                if value.abs() <= 1e-12 {
782                    break;
783                }
784                let step = 1e-8;
785                let probed = rows.cs_pcurve.evaluate(p + step).or_refuse(KernelStage::Refine, "evaluate")?.x - target;
786                let derivative = (probed - value) / step;
787                if derivative.abs() <= 1e-14 {
788                    return Err(KernelRefusal::non_convergence(KernelStage::Refine, "seam_crossing_newton", "blend: second seam crossing Newton stalled"));
789                }
790                p -= value / derivative;
791            }
792            let crossing_v = rows.cs_pcurve.evaluate(p).or_refuse(KernelStage::Refine, "evaluate")?.y;
793            Some(SecondSeamSplit {
794                fit_parameter: p,
795                crossing_v,
796                period: period2 * direction,
797            })
798        }
799    } else {
800        None
801    };
802
803    // A wall that SHIPS short of its construction request says so, typed, on
804    // the blend face it built (exact name and surface); a carved wall or a
805    // fallback construction makes no request.
806    let model_unmet = if carve_fold { None } else { model_unmet };
807    let wall_surface = model_unmet.map(|_| rows.surface.clone());
808    let built = build_surgery(
809        solid,
810        edge,
811        &first_mate,
812        &second_mate,
813        rows,
814        second_split,
815        name,
816        crease,
817    )?;
818    surgery_timing.stop();
819    if let (Some((declared, reason, round, stations, ceiling)), Some(surface)) = (model_unmet, wall_surface) {
820        crate::blend::record_wall_model_report(crate::blend::WallModelReport {
821            name: name.map(str::to_string),
822            surface,
823            request: crate::KernelTolerances::for_solid(solid, 1e-7).model,
824            residual: declared,
825            // The request covers the rails (the shipped support curves) and
826            // the wall; the residual is the worse of the two.
827            detail: request_rails.map(|(rails, unread, wall)| {
828                format!("last request read: rails {rails:.3e} off their carriers at j/16 ({unread} interval(s) unread), wall {wall:.3e}")
829            }),
830            budget: crate::ApproximationBudget {
831                reason,
832                rounds_used: round,
833                rounds_limit: crate::blend::stations::REFINE_ROUNDS,
834                stations,
835                station_limit: ceiling,
836                mechanism: crate::BudgetMechanism::LocalRounds,
837                // The request covers rails and wall: which one the residual
838                // reads, and the rail intervals it could not read.
839                measured_component: match request_rails {
840                    Some((rails, _, wall)) if rails > wall => crate::MeasuredComponent::Rails,
841                    _ => crate::MeasuredComponent::Wall,
842                },
843                unread: request_rails.map_or(0, |(_, unread, _)| unread),
844            },
845        });
846    }
847    Ok(built)
848}
849
850/// A closed spherical hole may meet the carrier's full-domain seam at its
851/// loop vertex. The domain rectangle is only a parameter cut, so moving the
852/// hole need not move that cut. Separate the ring from the rectangle and give
853/// it its own coincident vertex before surgery. Unlike a retraced slit, the
854/// opposite seam branches and collapsed pole edges remain in the solid.
855fn separate_spherical_domain_cut(
856    solid: &BrepSolid,
857    edge_id: u64,
858) -> Result<Option<BrepSolid>, KernelRefusal> {
859    let Some(edge) = solid.edges.iter().find(|edge| edge.id == edge_id) else {
860        return Ok(None);
861    };
862    if edge.start_vertex_id != edge.end_vertex_id {
863        return Ok(None);
864    }
865    let mut result = solid.clone();
866    let mut take_id = crate::blend::edge::fresh_id_source(solid);
867    let mut separated = false;
868    for face in result.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
869        let Some(atlas) = crate::sphere_chart::SphereAtlas::of_surface(&face.surface) else {
870            continue;
871        };
872        let [u0, u1] = face
873            .surface
874            .domain_u()
875            .or_refuse(KernelStage::Collect, "domain_cut_u")?;
876        let [v0, v1] = face
877            .surface
878            .domain_v()
879            .or_refuse(KernelStage::Collect, "domain_cut_v")?;
880        if [u0, u1, v0, v1] != [0.0, 1.0, 0.0, 1.0] {
881            continue;
882        }
883        if face
884            .surface
885            .closed_directions()
886            .or_refuse(KernelStage::Collect, "domain_cut_closed")?
887            != (true, false)
888        {
889            continue;
890        }
891        let band = 1e-8 * atlas.radius;
892        let bottom = face
893            .surface
894            .evaluate(u0, v0)
895            .or_refuse(KernelStage::Collect, "domain_cut_bottom")?;
896        let top = face
897            .surface
898            .evaluate(u0, v1)
899            .or_refuse(KernelStage::Collect, "domain_cut_top")?;
900        if bottom.add(top).scale(0.5).sub(atlas.centre).length() > band
901            || (bottom.sub(top).length() - 2.0 * atlas.radius).abs() > band
902        {
903            continue;
904        }
905        let mut additions = Vec::new();
906        let mut cut_ids = std::collections::HashSet::new();
907        for rim in &mut face.loops {
908            if rim.coedges.len() < 5 {
909                continue;
910            }
911            let positions: Vec<_> = rim
912                .coedges
913                .iter()
914                .enumerate()
915                .filter_map(|(i, c)| (c.edge_id == edge_id).then_some(i))
916                .collect();
917            if positions.len() != 1 {
918                continue;
919            }
920            let position = positions[0];
921            let ring = &rim.coedges[position];
922            let [a, b] = ring
923                .pcurve
924                .domain()
925                .or_refuse(KernelStage::Collect, "domain_cut_ring")?;
926            if ring
927                .pcurve
928                .evaluate(a)
929                .or_refuse(KernelStage::Collect, "domain_cut_ring_start")?
930                .sub(
931                    ring.pcurve
932                        .evaluate(b)
933                        .or_refuse(KernelStage::Collect, "domain_cut_ring_end")?,
934                )
935                .length()
936                > 1e-7
937            {
938                continue;
939            }
940            let rest: Vec<_> = rim
941                .coedges
942                .iter()
943                .filter(|c| c.edge_id != edge_id)
944                .collect();
945            let mut points = Vec::new();
946            let mut domain_cut = true;
947            for coedge in &rest {
948                let [a, b] = coedge
949                    .pcurve
950                    .domain()
951                    .or_refuse(KernelStage::Collect, "domain_cut_trim")?;
952                let start = coedge
953                    .pcurve
954                    .evaluate(a)
955                    .or_refuse(KernelStage::Collect, "domain_cut_start")?;
956                let end = coedge
957                    .pcurve
958                    .evaluate(b)
959                    .or_refuse(KernelStage::Collect, "domain_cut_end")?;
960                points.push(start);
961                let degenerate = solid
962                    .edges
963                    .iter()
964                    .any(|e| e.id == coedge.edge_id && e.degenerate);
965                let at = |x: f64, low: f64, high: f64| {
966                    (x - low).abs() <= 1e-8 || (x - high).abs() <= 1e-8
967                };
968                let on_boundary = if degenerate {
969                    (start.y - end.y).abs() <= 1e-8
970                        && at(start.y, v0, v1)
971                        && coedge
972                            .pcurve
973                            .control_points
974                            .iter()
975                            .all(|p| (p.y / p.w - start.y).abs() <= 1e-8)
976                } else {
977                    at(start.x, u0, u1)
978                        && (start.x - end.x).abs() <= 1e-8
979                        && coedge
980                            .pcurve
981                            .control_points
982                            .iter()
983                            .all(|p| (p.x / p.w - start.x).abs() <= 1e-8)
984                        && rest.iter().filter(|c| c.edge_id == coedge.edge_id).count() == 2
985                        && rest
986                            .iter()
987                            .any(|c| c.edge_id == coedge.edge_id && c.forward != coedge.forward)
988                };
989                domain_cut &= on_boundary;
990            }
991            let twice_area: f64 = (0..points.len())
992                .map(|i| {
993                    let a = points[i];
994                    let b = points[(i + 1) % points.len()];
995                    a.x * b.y - a.y * b.x
996                })
997                .sum();
998            let expected = (u1 - u0) * (v1 - v0) * if face.same_sense { 1.0 } else { -1.0 };
999            if !domain_cut || (0.5 * twice_area - expected).abs() > 1e-7 * expected.abs() {
1000                continue;
1001            }
1002            // A relocated cut must belong only to this sphere. Its vertices
1003            // may touch the selected ring or collapsed poles, but no other
1004            // material edge. Its active parameter must already be sphere v.
1005            let cuts: std::collections::HashSet<_> = rest
1006                .iter()
1007                .filter_map(|c| {
1008                    solid
1009                        .edges
1010                        .iter()
1011                        .find(|e| e.id == c.edge_id && !e.degenerate)
1012                        .map(|e| e.id)
1013                })
1014                .collect();
1015            for cut in solid.edges.iter().filter(|e| cuts.contains(&e.id)) {
1016                let users = solid
1017                    .shells
1018                    .iter()
1019                    .flat_map(|s| &s.faces)
1020                    .flat_map(|f| &f.loops)
1021                    .flat_map(|l| &l.coedges)
1022                    .filter(|c| c.edge_id == cut.id)
1023                    .count();
1024                let exclusive_vertices = solid
1025                    .edges
1026                    .iter()
1027                    .filter(|e| {
1028                        e.start_vertex_id == cut.start_vertex_id
1029                            || e.end_vertex_id == cut.start_vertex_id
1030                            || e.start_vertex_id == cut.end_vertex_id
1031                            || e.end_vertex_id == cut.end_vertex_id
1032                    })
1033                    .all(|e| e.degenerate || cuts.contains(&e.id) || e.id == edge_id);
1034                let mut same_parameter = cut.t0 >= v0 && cut.t1 <= v1 && cut.t0 < cut.t1;
1035                for i in 0..=16 {
1036                    let t = cut.t0 + (cut.t1 - cut.t0) * i as f64 / 16.0;
1037                    let point = cut
1038                        .curve
1039                        .evaluate(t)
1040                        .or_refuse(KernelStage::Collect, "domain_cut_curve")?;
1041                    let carrier = face
1042                        .surface
1043                        .evaluate(u0, t)
1044                        .or_refuse(KernelStage::Collect, "domain_cut_carrier")?;
1045                    same_parameter &= point.sub(carrier).length() <= band;
1046                }
1047                domain_cut &= users == 2 && exclusive_vertices && same_parameter;
1048            }
1049            if !domain_cut {
1050                continue;
1051            }
1052            cut_ids.extend(cuts);
1053            additions.push(LoopRecord {
1054                id: take_id(),
1055                coedges: vec![rim.coedges.remove(position)],
1056            });
1057            separated = true;
1058        }
1059        if !additions.is_empty() {
1060            // The freed contact can cross the old parameter seam. Move the
1061            // artificial cut by a quarter turn, which is an exact shift of
1062            // this rational circle chart, to keep every real trim in-domain.
1063            let real = |id: u64| {
1064                !cut_ids.contains(&id) && !solid.edges.iter().any(|e| e.id == id && e.degenerate)
1065            };
1066            let curves: Vec<_> = face
1067                .loops
1068                .iter()
1069                .flat_map(|l| &l.coedges)
1070                .chain(additions.iter().flat_map(|l| &l.coedges))
1071                .filter(|c| real(c.edge_id) || c.edge_id == edge_id)
1072                .map(|c| &c.pcurve)
1073                .collect();
1074            let mut candidates = Vec::new();
1075            for shift in [0.25, 0.5, 0.75] {
1076                let mut clearance = f64::INFINITY;
1077                let mut fits = true;
1078                for curve in &curves {
1079                    let first = curve.control_points[0].x / curve.control_points[0].w;
1080                    let offset = -(first - shift).floor();
1081                    for p in &curve.control_points {
1082                        let u = p.x / p.w - shift + offset;
1083                        fits &= u >= 0.0 && u <= 1.0;
1084                        clearance = clearance.min(u.min(1.0 - u));
1085                    }
1086                }
1087                if fits {
1088                    candidates.push((clearance, shift));
1089                }
1090            }
1091            let Some((_, shift)) = candidates.into_iter().max_by(|a, b| a.0.total_cmp(&b.0)) else {
1092                return Err(KernelRefusal::unsupported(
1093                    KernelStage::Collect,
1094                    "sphere_domain_cut",
1095                    "blend: no quarter-turn sphere chart keeps the real trims in-domain",
1096                ));
1097            };
1098            let seam_direction = face
1099                .surface
1100                .evaluate(shift, 0.5)
1101                .or_refuse(KernelStage::Collect, "sphere_cut_direction")?
1102                .sub(atlas.centre);
1103            let surface = crate::make_sphere_surface_framed(
1104                atlas.centre,
1105                atlas.radius,
1106                atlas.basis[2],
1107                Some(seam_direction),
1108            )
1109            .or_refuse(KernelStage::Collect, "sphere_cut_surface")?;
1110            // Rebuilding must be only a chart change, including handedness.
1111            for i in 0..=16 {
1112                for v in [0.0, 0.3, 0.5, 0.7, 1.0] {
1113                    let u = i as f64 / 16.0;
1114                    let old = face
1115                        .surface
1116                        .evaluate(u, v)
1117                        .or_refuse(KernelStage::Collect, "sphere_cut_old")?;
1118                    let new = surface
1119                        .evaluate((u - shift).rem_euclid(1.0), v)
1120                        .or_refuse(KernelStage::Collect, "sphere_cut_new")?;
1121                    if old.sub(new).length() > band {
1122                        return Err(KernelRefusal::unsupported(
1123                            KernelStage::Collect,
1124                            "sphere_cut_chart",
1125                            "blend: the sphere quarter turn is not the same carrier",
1126                        ));
1127                    }
1128                }
1129            }
1130            let seam = surface
1131                .iso_curve_u(0.0)
1132                .or_refuse(KernelStage::Collect, "sphere_cut_seam")?;
1133            for coedge in face
1134                .loops
1135                .iter_mut()
1136                .flat_map(|l| &mut l.coedges)
1137                .chain(additions.iter_mut().flat_map(|l| &mut l.coedges))
1138            {
1139                if solid
1140                    .edges
1141                    .iter()
1142                    .any(|e| e.id == coedge.edge_id && e.degenerate)
1143                {
1144                    continue;
1145                }
1146                if !cut_ids.contains(&coedge.edge_id) {
1147                    let first =
1148                        coedge.pcurve.control_points[0].x / coedge.pcurve.control_points[0].w;
1149                    let offset = -(first - shift).floor() - shift;
1150                    for p in &mut coedge.pcurve.control_points {
1151                        p.x += offset * p.w;
1152                    }
1153                }
1154            }
1155            for cut in result.edges.iter_mut().filter(|e| cut_ids.contains(&e.id)) {
1156                for (vertex_id, t) in [(cut.start_vertex_id, cut.t0), (cut.end_vertex_id, cut.t1)] {
1157                    let point = seam
1158                        .evaluate(t)
1159                        .or_refuse(KernelStage::Collect, "sphere_cut_vertex")?;
1160                    let vertex = result
1161                        .vertices
1162                        .iter_mut()
1163                        .find(|v| v.id == vertex_id)
1164                        .ok_or(KernelRefusal::internal(
1165                            KernelStage::Collect,
1166                            "sphere_cut_vertex",
1167                            "blend: sphere seam vertex is missing",
1168                        ))?;
1169                    vertex.point = point;
1170                }
1171                cut.curve = seam.clone();
1172            }
1173            face.surface = surface;
1174        }
1175        face.loops.extend(additions);
1176    }
1177    if !separated {
1178        return Ok(None);
1179    }
1180    let old_vertex = solid
1181        .vertices
1182        .iter()
1183        .find(|v| v.id == edge.start_vertex_id)
1184        .ok_or(KernelRefusal::internal(
1185            KernelStage::Collect,
1186            "domain_cut_vertex",
1187            "blend: closed ring vertex is missing",
1188        ))?;
1189    let vertex_id = take_id();
1190    result.vertices.push(VertexRecord {
1191        id: vertex_id,
1192        point: old_vertex.point,
1193    });
1194    let ring = result
1195        .edges
1196        .iter_mut()
1197        .find(|e| e.id == edge_id)
1198        .ok_or(KernelRefusal::internal(
1199            KernelStage::Collect,
1200            "domain_cut_ring",
1201            "blend: closed ring edge is missing",
1202        ))?;
1203    ring.start_vertex_id = vertex_id;
1204    ring.end_vertex_id = vertex_id;
1205    Ok(Some(result))
1206}
1207
1208/// Imported faces can carry a slit from a closed rim to a pole and straight
1209/// back along the same UV track. It has no area and is not a periodic seam
1210/// (whose two pcurves differ by a period). Moving the rim must not drag this
1211/// artificial cut onto a different meridian. Cancel only adjacent opposite
1212/// uses of an edge with no other users, and prove that their UV tracks agree.
1213fn remove_retraced_cuts(
1214    solid: &BrepSolid,
1215    edge_id: u64,
1216) -> Result<Option<BrepSolid>, KernelRefusal> {
1217    let mut result = solid.clone();
1218    let mut removed = Vec::new();
1219    for face in result.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
1220        for rim in &mut face.loops {
1221            if !rim.coedges.iter().any(|coedge| coedge.edge_id == edge_id) {
1222                continue;
1223            }
1224            loop {
1225                let n = rim.coedges.len();
1226                let mut pair = None;
1227                for i in 0..n {
1228                    let j = (i + 1) % n;
1229                    let (a, b) = (&rim.coedges[i], &rim.coedges[j]);
1230                    if a.edge_id == edge_id || a.edge_id != b.edge_id || a.forward == b.forward {
1231                        continue;
1232                    }
1233                    let users = solid
1234                        .shells
1235                        .iter()
1236                        .flat_map(|s| &s.faces)
1237                        .flat_map(|f| &f.loops)
1238                        .flat_map(|l| &l.coedges)
1239                        .filter(|c| c.edge_id == a.edge_id)
1240                        .count();
1241                    if users != 2 {
1242                        continue;
1243                    }
1244                    let [a0, a1] = a
1245                        .pcurve
1246                        .domain()
1247                        .or_refuse(KernelStage::Collect, "cut_domain")?;
1248                    let [b0, b1] = b
1249                        .pcurve
1250                        .domain()
1251                        .or_refuse(KernelStage::Collect, "cut_domain")?;
1252                    // Compare the complete reversed rational representation,
1253                    // not a few probes that could miss a curved excursion.
1254                    let agrees =
1255                        a.pcurve.degree == b.pcurve.degree
1256                            && a.pcurve.knots.len() == b.pcurve.knots.len()
1257                            && a.pcurve.control_points.len() == b.pcurve.control_points.len()
1258                            && a.pcurve.knots.iter().zip(b.pcurve.knots.iter().rev()).all(
1259                                |(x, y)| {
1260                                    ((x - a0) / (a1 - a0) - (b1 - y) / (b1 - b0)).abs() <= 1e-9
1261                                },
1262                            )
1263                            && a.pcurve
1264                                .control_points
1265                                .iter()
1266                                .zip(b.pcurve.control_points.iter().rev())
1267                                .all(|(p, q)| {
1268                                    p.point()
1269                                        .ok()
1270                                        .zip(q.point().ok())
1271                                        .is_some_and(|(p, q)| p.sub(q).length() <= 1e-9)
1272                                        && (p.w / a.pcurve.control_points[0].w
1273                                            - q.w / b.pcurve.control_points.last().unwrap().w)
1274                                            .abs()
1275                                            <= 1e-9
1276                                });
1277                    if agrees {
1278                        pair = Some((i, j, a.edge_id));
1279                        break;
1280                    }
1281                }
1282                let Some((i, j, id)) = pair else {
1283                    break;
1284                };
1285                rim.coedges.remove(i.max(j));
1286                rim.coedges.remove(i.min(j));
1287                removed.push(id);
1288            }
1289        }
1290    }
1291    if removed.is_empty() {
1292        return Ok(None);
1293    }
1294    result.edges.retain(|edge| !removed.contains(&edge.id));
1295    super::open::prune_orphan_vertices(&mut result);
1296    Ok(Some(result))
1297}
1298
1299/// Where the second support crosses ITS seam-structured carrier's seam
1300/// meridian (both-seam closed edges).
1301struct SecondSeamSplit {
1302    fit_parameter: f64,
1303    crossing_v: f64,
1304    /// Signed carrier period travelled by the unwrapped pcurve track.
1305    period: f64,
1306}
1307
1308/// Replace the blended edge in both mating loops, trim the seam edge of an
1309/// anchored closed carrier, and insert the blend face.
1310/// The carve of a folding closed-edge wall: measure the fitted rows against
1311/// the carriers between the stations they were fitted through (the network's
1312/// own rail bar, half `intersection_fit`), trace the crease on the fitted
1313/// surface and fit it to `pcurve_consistency`, and refuse by name a lens
1314/// that straddles the wall's own seam (the closed rows join at u = 0 ≡ 1, and
1315/// the crease tracer reads one parameter rectangle).
1316/// Top of the closed march's carve ladder: `SEED_INTERVALS << 8` = 4096
1317/// intervals, the station count the chain lane's ladder also tops out near
1318/// (`CHAIN_CARVE_MAX_PER_SEGMENT` per segment).
1319const CARVE_MAX_REFINEMENT_DEPTH: usize = MAX_REFINEMENT_DEPTH + 4;
1320
1321/// How far the closed rows' rails stand off their carriers BETWEEN the
1322/// stations they were fitted through, at 0.25/0.5/0.75 of every span — the
1323/// open march's `rails_off_carriers` reading on closed rows.
1324fn rails_off_closed_carriers(
1325    rows: &FittedRows,
1326    stations: &[Station],
1327    parameters: &[f64],
1328    first: &BlendMate,
1329    second: &BlendMate,
1330) -> Result<f64, KernelRefusal> {
1331    Ok(closed_rail_interval_misses(rows, stations, parameters,
1332        [&first.face.surface, &second.face.surface])?.into_iter().fold(0.0_f64, f64::max))
1333}
1334
1335fn carve_closed_wall(
1336    solid: &BrepSolid,
1337    rows: &FittedRows,
1338    stations: &[Station],
1339    parameters: &[f64],
1340    first: &BlendMate,
1341    second: &BlendMate,
1342    radius: f64,
1343) -> Result<crate::blend::carve::CarvedCrease, KernelRefusal> {
1344    let policy = crate::KernelTolerances::for_solid(solid, 1e-7);
1345    let rail_bar = 0.5 * policy.intersection_fit;
1346    let off = rails_off_closed_carriers(rows, stations, parameters, first, second)?;
1347    crate::blend::carve::carve_trace(format_args!(
1348        "blend closed-edge carve: {} stations, rails {off:.3e} off their carriers between stations (bar {rail_bar:.3e})",
1349        parameters.len()
1350    ));
1351    if off > rail_bar {
1352        return Err(crate::blend::fold::wall_fold_refusal(
1353            Vec::new(),
1354            format!(
1355                "{} {radius} fits this edge: the wall folds, and the closed march's fitted rails stand {off:.3e} off their carriers between stations (bar {rail_bar:.3e}), so there is no wall accurate enough to carve",
1356                crate::blend::WALL_FOLDS
1357            ),
1358        ));
1359    }
1360    let Some(carved) = crate::blend::carve::trace_wall_crease(&rows.surface, radius)? else {
1361        return Err(KernelRefusal::internal(KernelStage::Refine, "carve_no_fold", "blend closed-edge carve: the wall re-marched under Carve carries no fold to carve, but the march refused one"));
1362    };
1363    let [u0, u1] = rows.u_domain;
1364    let margin = 1e-3 * (u1 - u0);
1365    let straddles = carved.ends.iter().any(|end| end[0] <= u0 + margin || end[0] >= u1 - margin);
1366    if straddles {
1367        return Err(crate::blend::fold::wall_fold_refusal(
1368            Vec::new(),
1369            format!(
1370                "{} {radius} fits this edge: the wall folds, and the fold band straddles the wall's own seam (lens ends at u = {:.6} and {:.6} of [{u0:.3}, {u1:.3}]), which the crease tracer reads as two half-lenses; carving across the seam is not built",
1371                crate::blend::WALL_FOLDS, carved.ends[0][0], carved.ends[1][0]
1372            ),
1373        ));
1374    }
1375    crate::blend::carve::fit_crease(&rows.surface, &carved, policy.pcurve_consistency)
1376}
1377
1378/// Lane G row 2 (2026-10-14, `closed_trim_read_first_on`): a closed rail's
1379/// support trim on a PLANE mate is the rail's own control points carried
1380/// through the plane's affine chart (an exact image of the rail, the exact
1381/// revolution lane's rule for a plane mate's rail, `plane_affine_pcurve`),
1382/// read once as shipped at the pcurve floor (`track_fit::read_shipped_pcurve`,
1383/// the read the refit itself is judged on, at the rail's own parameter) and
1384/// kept when it reads within it (8.98e-15 on the half torus's cut plane);
1385/// any other mate, or an image that misses, takes the refit as before. The
1386/// shipped contract (every trim read within the floor) is the refit's own;
1387/// what changes is the bytes of a plane trim (the refit's control points are
1388/// the track fitter's, these are the rail's own), which is why the road is
1389/// behind its switch until its census. The march's own interpolated pcurve
1390/// was measured as a second candidate and dropped: on the half torus it
1391/// reads 8.5e-5 off its rail where the uv track crosses the carrier's knot
1392/// lines (the chart is C1 there, a cubic interpolant through the stations is
1393/// not), the two reads cost 2.8 ms for nothing, and a rational carrier's
1394/// knot lines make that the rule, not the exception.
1395fn closed_support_trim(rail: &NurbsCurve, old: &NurbsCurve, surface: &NurbsSurface) -> Result<NurbsCurve, KernelRefusal> {
1396    let floor = crate::pcurve::PCURVE_REFINEMENT_TOLERANCE;
1397    let [d0, d1] = rail.domain().or_refuse(KernelStage::Refine, "domain")?;
1398    let within_floor = |candidate: &NurbsCurve, what: &str| -> bool {
1399        let _read_timing = crate::blend::BlendTimer::start("timing.closed.rows.trim_read_ms");
1400        let read = crate::blend::track_fit::read_shipped_pcurve(surface, &|t| rail.evaluate(t), candidate, d0, d1);
1401        if std::env::var_os("BREP_DEBUG_TRACK_FIT").is_some() {
1402            match &read {
1403                Ok((miss, standoff, samples, worst)) => eprintln!(
1404                    "TRACK_FIT closed-edge support, {what} candidate ({} control points): miss {miss:.3e} at t {worst:.9} ({samples} samples), rail standoff {standoff:.3e}, floor {floor:e}",
1405                    candidate.control_points.len()),
1406                Err(error) => eprintln!("TRACK_FIT closed-edge support, {what} candidate: unreadable: {error}"),
1407            }
1408        }
1409        read.is_ok_and(|(miss, _, _, _)| miss <= floor)
1410    };
1411    if let Some(affine) = plane_affine_pcurve(rail, surface) {
1412        if within_floor(&affine, "affine plane image") {
1413            crate::blend::record_count("count.closed.rows.trim.affine", 1);
1414            return Ok(affine);
1415        }
1416    }
1417    crate::blend::record_count("count.closed.rows.trim.refit", 1);
1418    refit_closed_support_pcurve(rail, old, surface)
1419}
1420
1421/// The rail's own control points through a PLANE mate's affine chart (the
1422/// chart read off the surface's domain corners, as the exact revolution
1423/// lane's `plane_pcurve` reads it), on the rail's knots and weights: the
1424/// exact image of the rail in (u, v). `None` on any other carrier, or on a
1425/// chart too thin to invert.
1426fn plane_affine_pcurve(rail: &NurbsCurve, surface: &NurbsSurface) -> Option<NurbsCurve> {
1427    if !matches!(surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) {
1428        return None;
1429    }
1430    let [u0, u1] = surface.domain_u().ok()?;
1431    let [v0, v1] = surface.domain_v().ok()?;
1432    let origin = surface.evaluate(u0, v0).ok()?;
1433    let du = surface.evaluate(u1, v0).ok()?.sub(origin).scale(1.0 / (u1 - u0));
1434    let dv = surface.evaluate(u0, v1).ok()?.sub(origin).scale(1.0 / (v1 - v0));
1435    let (a, b, c) = (du.dot(du), du.dot(dv), dv.dot(dv));
1436    let det = a * c - b * b;
1437    let chart_scale = origin.length().max(du.length()).max(dv.length()).max(1.0);
1438    if !(det > 1e-24 * chart_scale.powi(4)) {
1439        return None;
1440    }
1441    let mut pcurve = rail.clone();
1442    for control in &mut pcurve.control_points {
1443        let weight = control.w;
1444        let offset = Vec3::new(control.x / weight, control.y / weight, control.z / weight).sub(origin);
1445        let (r, s) = (offset.dot(du), offset.dot(dv));
1446        control.x = (u0 + (c * r - b * s) / det) * weight;
1447        control.y = (v0 + (a * s - b * r) / det) * weight;
1448        control.z = 0.0;
1449    }
1450    Some(pcurve)
1451}
1452
1453/// A support rail's pcurve on its mate `surface` (a closed edge's whole rail,
1454/// or an open edge's rail trimmed to its crossing window), fitted to the
1455/// rail's own projected track at the pcurve floor
1456/// (`chain::project_piece_pcurve`, the closed chain's support-piece fitter,
1457/// which refuses a fit off that floor), on the rail's parameter domain and in
1458/// the same carrier period as the interpolated pcurve `old` it replaces. A
1459/// closed rail around a periodic carrier spans a whole period, so its ends are
1460/// not pinned by the fitter (both would go to one seam); instead an end whose
1461/// `old` coordinate lies exactly on a seam keeps that coordinate, so the loop
1462/// still closes on the seam the surgery built it on.
1463///
1464/// The shipped curve is read again at the floor (`read_shipped_pcurve`). The
1465/// fitter's stencil reads j/16 of each TRACK interval and the shipped read
1466/// j/16 of each span of the fitted curve's own (averaged) knots, so a fit the
1467/// stencil reads just under the floor can read just over it as shipped (the
1468/// 2026-09-27 revolve: 9.923e-8 on the stencil, 1.037e-7 at t 0.4902). Such
1469/// a fit is refitted, at the SAME floor, with its track refined where the
1470/// shipped read found the miss, up to `SHIPPED_READ_REPAIRS` times; the floor
1471/// never moves, and a fit read within it the first time ships as before.
1472///
1473/// Its first fit, whose floor miss is TERMINAL on this road, takes the
1474/// knot-aware retry (lane L, 2026-10-16); the open surgery's own refit
1475/// (`refit_closed_support_pcurve_read`), which answers a miss with its
1476/// fallback, does not.
1477pub(in crate::blend) fn refit_closed_support_pcurve(rail: &NurbsCurve, old: &NurbsCurve, surface: &NurbsSurface) -> Result<NurbsCurve, KernelRefusal> {
1478    let knot_retry = KNOT_RETRY.with(|flag| flag.get());
1479    refit_closed_support_pcurve_read_with(rail, old, surface, &mut crate::blend::track_fit::FootMemo::transient(), knot_retry).map(|(fitted, _)| fitted)
1480}
1481
1482thread_local! {
1483    /// Set only while [`blend_closed_edge_knot_aware`] or
1484    /// [`with_pcurve_knot_retry`] re-runs a blend whose first run was refused
1485    /// for a support pcurve off the floor (lane L, 2026-10-16).
1486    static KNOT_RETRY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1487}
1488
1489/// [`refit_closed_support_pcurve`] handing back the shipped curve's own read
1490/// `(miss, rail standoff, samples, worst parameter)` -- the
1491/// `read_shipped_pcurve` of the curve returned, which a caller that reads
1492/// the shipped trim again would otherwise compute a second time on the same
1493/// inputs -- with the feet of that read left in `memo` (cleared before each
1494/// fit, so it holds the returned curve's feet only) for the caller's
1495/// further reads of the same curve against the same rail.
1496pub(in crate::blend) fn refit_closed_support_pcurve_read(
1497    rail: &NurbsCurve,
1498    old: &NurbsCurve,
1499    surface: &NurbsSurface,
1500    memo: &mut crate::blend::track_fit::FootMemo,
1501) -> Result<(NurbsCurve, (f64, f64, usize, f64)), KernelRefusal> {
1502    // The open surgery's refit takes the knot-aware retry only inside
1503    // `with_pcurve_knot_retry` (lane L, 2026-10-16, lCount_229).
1504    let knot_retry = KNOT_RETRY.with(|flag| flag.get());
1505    refit_closed_support_pcurve_read_with(rail, old, surface, memo, knot_retry)
1506}
1507
1508/// Runs `build` with every support refit taking the knot-aware retry on a
1509/// floor miss, restoring the flag after (lane L, 2026-10-16, lCount_229: the
1510/// fillet group's network re-run on a pcurve-floor refusal).
1511pub fn with_pcurve_knot_retry<T>(build: impl FnOnce() -> T) -> T {
1512    let previous = KNOT_RETRY.with(|flag| flag.replace(true));
1513    let built = build();
1514    KNOT_RETRY.with(|flag| flag.set(previous));
1515    built
1516}
1517
1518/// [`refit_closed_support_pcurve_read`], its first fit taking the knot-aware
1519/// retry when `knot_retry` (see [`refit_closed_support_pcurve`]).
1520fn refit_closed_support_pcurve_read_with(
1521    rail: &NurbsCurve,
1522    old: &NurbsCurve,
1523    surface: &NurbsSurface,
1524    memo: &mut crate::blend::track_fit::FootMemo,
1525    knot_retry: bool,
1526) -> Result<(NurbsCurve, (f64, f64, usize, f64)), KernelRefusal> {
1527    const SHIPPED_READ_REPAIRS: usize = 3;
1528    let floor = crate::pcurve::PCURVE_REFINEMENT_TOLERANCE;
1529    let [d0, d1] = rail.domain().or_refuse(KernelStage::Refine, "domain")?;
1530    let mut near: Vec<f64> = Vec::new();
1531    // The FIRST fit's floor miss is terminal here, so it takes the knot-aware
1532    // retry (lane L, 2026-10-16, lCount_201); a repair round's miss keeps the
1533    // last fit, as before.
1534    let (mut fitted, mut read) = fit_and_read_support(rail, old, surface, &near, memo, knot_retry)?;
1535    for _ in 0..SHIPPED_READ_REPAIRS {
1536        if read.0 <= floor || !(d1 > d0) {
1537            break;
1538        }
1539        near.push((read.3 - d0) / (d1 - d0));
1540        crate::blend::record_count("count.surgery.refit_repairs", 1);
1541        // A repair that fails keeps the last fit AND its feet: a failed
1542        // fit or an unreadable read hands nothing to the memo.
1543        match fit_and_read_support(rail, old, surface, &near, memo, false) {
1544            Ok(repaired) => (fitted, read) = repaired,
1545            Err(_) => break,
1546        }
1547    }
1548    let (miss, standoff, samples, _) = read;
1549    if !(miss <= floor) {
1550        return Err(KernelRefusal::non_convergence(KernelStage::Refine, CLOSED_SUPPORT_PCURVE_FLOOR_WHAT, format!(
1551            "{} a blend's support pcurve, as shipped, misses its rail's track by {miss:.3e} at {samples} samples, \
1552             against a floor of {floor:.1e}",
1553            crate::blend::PCURVE_OFF_FLOOR,
1554        )));
1555    }
1556    Ok((fitted, read))
1557}
1558
1559/// [`refit_closed_support_pcurve`]'s fit, its track refined near the
1560/// fractions `near` first, and the shipped curve's read (miss, standoff,
1561/// samples, worst rail parameter).
1562fn fit_and_read_support(
1563    rail: &NurbsCurve,
1564    old: &NurbsCurve,
1565    surface: &NurbsSurface,
1566    near: &[f64],
1567    memo: &mut crate::blend::track_fit::FootMemo,
1568    knot_retry: bool,
1569) -> Result<(NurbsCurve, (f64, f64, usize, f64)), KernelRefusal> {
1570    let [d0, d1] = rail.domain().or_refuse(KernelStage::Refine, "domain")?;
1571    // Every foot of the track is sought from the march's own trim `old` at
1572    // the same rail parameter (`pcurve_guide`), on the branch it runs on.
1573    let guide = crate::blend::chain::pcurve_guide(old, surface)?;
1574    let track_timing = crate::blend::BlendTimer::start("timing.support_refit.track_ms");
1575    let mut fitted = if knot_retry {
1576        crate::blend::chain::project_piece_pcurve_within_knot_retry(rail, surface, false, false, Some(&guide), near)?
1577    } else {
1578        crate::blend::chain::project_piece_pcurve_within(rail, surface, false, false, Some(&guide), near)?
1579    };
1580    track_timing.stop();
1581    // The fitter's parameter is the track fraction; the surgery reads the
1582    // pcurve at the rail's own parameter.
1583    let [f0, f1] = fitted.domain().or_refuse(KernelStage::Refine, "domain")?;
1584    for knot in fitted.knots.iter_mut() {
1585        *knot = d0 + (*knot - f0) / (f1 - f0) * (d1 - d0);
1586    }
1587    let debug = std::env::var_os("BREP_DEBUG_TRACK_FIT").is_some();
1588    if debug {
1589        // Diagnostic only: the same read before the period shift and the seam
1590        // ends are set (the shift alone moves no point of the carrier).
1591        match crate::blend::track_fit::read_shipped_pcurve(surface, &|t| rail.evaluate(t), &fitted, d0, d1) {
1592            Ok((miss, standoff, samples, worst)) => eprintln!(
1593                "TRACK_FIT closed-edge support: before the seam ends, miss {miss:.3e} at t {worst:.9} ({samples} samples), standoff {standoff:.3e}"),
1594            Err(error) => eprintln!("TRACK_FIT closed-edge support: before the seam ends, unreadable: {error}"),
1595        }
1596    }
1597    let (closed_u, closed_v) = surface.closed_directions().or_refuse(KernelStage::Refine, "closed_directions")?;
1598    let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
1599    let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
1600    let old_start = old.evaluate(d0).or_refuse(KernelStage::Refine, "evaluate")?;
1601    let old_end = old.evaluate(d1).or_refuse(KernelStage::Refine, "evaluate")?;
1602    let new_start = fitted.evaluate(d0).or_refuse(KernelStage::Refine, "evaluate")?;
1603    // Whole periods only: the same carrier point, in the old pcurve's period.
1604    let shift = |closed: bool, from: f64, to: f64, period: f64| if closed { ((to - from) / period).round() * period } else { 0.0 };
1605    let (shift_u, shift_v) = (shift(closed_u, new_start.x, old_start.x, u1 - u0), shift(closed_v, new_start.y, old_start.y, v1 - v0));
1606    for point in fitted.control_points.iter_mut() {
1607        point.x += shift_u * point.w;
1608        point.y += shift_v * point.w;
1609    }
1610    let on_seam = |closed: bool, value: f64, low: f64, high: f64| {
1611        let period = high - low;
1612        closed && ((value - low) / period - ((value - low) / period).round()).abs() * period <= 1e-12 * period.max(1.0)
1613    };
1614    let last = fitted.control_points.len() - 1;
1615    for (index, end) in [(0, old_start), (last, old_end)] {
1616        let point = &mut fitted.control_points[index];
1617        if on_seam(closed_u, end.x, u0, u1) {
1618            point.x = end.x * point.w;
1619        }
1620        if on_seam(closed_v, end.y, v0, v1) {
1621            point.y = end.y * point.w;
1622        }
1623    }
1624    // The curve SHIPPED is not the one the fitter checked (its domain, period
1625    // and seam ends were edited), so it is read again, at the rail's own
1626    // parameter, against the fitter's floor; a miss refuses as the fitter's
1627    // own would, and an unreadable sample refuses.
1628    // The feet are the shipped curve's, read into a memo of their own and
1629    // handed over only with a readable curve: a read that refuses (an
1630    // unreadable sample, found after every sample was sought) must leave
1631    // the caller's memo holding the feet of the curve the caller keeps,
1632    // not this curve's.
1633    let mut own = memo.empty_like();
1634    let (miss, standoff, samples, worst) =
1635        crate::blend::track_fit::read_shipped_pcurve_memo(surface, &|t| rail.evaluate(t), &fitted, d0, d1, &mut own)?;
1636    *memo = own;
1637    if debug {
1638        eprintln!("TRACK_FIT closed-edge support: shipped pcurve miss {miss:.3e} at t {worst:.9} of [{d0:.9}, {d1:.9}] ({samples} samples); rail standoff from its carrier {standoff:.3e}");
1639    }
1640    Ok((fitted, (miss, standoff, samples, worst)))
1641}
1642
1643
1644/// One exit probe: whether a support station's `uv` (wrapped into a closed
1645/// carrier's domain) classifies OUTSIDE `face`'s trims, an unreadable class
1646/// counting as outside.
1647fn support_exits_at(face: &FaceRecord, mut uv: [f64; 2]) -> bool {
1648    if let Ok((closed_u, closed_v)) = face.surface.closed_directions() {
1649        if closed_u {
1650            if let Ok([low, high]) = face.surface.domain_u() {
1651                uv[0] = low + (uv[0] - low).rem_euclid(high - low);
1652            }
1653        }
1654        if closed_v {
1655            if let Ok([low, high]) = face.surface.domain_v() {
1656                uv[1] = low + (uv[1] - low).rem_euclid(high - low);
1657            }
1658        }
1659    }
1660    crate::parameter_point_in_face(face, crate::Vec2 { x: uv[0], y: uv[1] }, 1e-6)
1661        .map(|class| class == crate::PolygonClass::Outside)
1662        .unwrap_or(true)
1663}
1664
1665/// The exit question for a mate bounded only by PARALLELS of the rim's axis
1666/// (lane R 2026-10-28, the cylinder rims row: 17 probes per mate were 0.15 ms
1667/// of a two-rim fillet's ~1.5 ms).
1668///
1669/// A plane normal to the axis or a cylinder/cone about it is cut by the
1670/// parallels into cells — annuli of the plane between consecutive radii,
1671/// bands of the cylinder between consecutive heights — and when every
1672/// boundary edge of the face (seams, used twice by one loop, aside) is such a
1673/// parallel, each cell is wholly inside the face or wholly outside it.  The
1674/// support contacts of a rim between coaxial carriers are parallels too, so
1675/// when every station's meridian coordinate (radius on a plane, height on a
1676/// cylinder or cone) lies in ONE open cell, clear of its bounding parallels
1677/// by a margin far above the probe's 1e-6 band, every station classifies the
1678/// same, and the first station's probe is the scan's answer.  `None` — the
1679/// full scan — for any other carrier, any boundary that is not a parallel,
1680/// and any station within the margin of a boundary, so a track that does
1681/// meet a boundary is classified station by station exactly as before.
1682fn support_exit_between_parallels(
1683    solid: &BrepSolid,
1684    face: &FaceRecord,
1685    (origin, axis): (Vec3, Vec3),
1686    contacts: &[Vec3],
1687    probe: &dyn Fn(usize) -> bool,
1688) -> Option<bool> {
1689    let radial = match face.surface.analytic()? {
1690        crate::AnalyticSurface::Plane { .. } => true,
1691        crate::AnalyticSurface::RuledRevolution { .. } => false,
1692        _ => return None,
1693    };
1694    if contacts.is_empty() {
1695        return None;
1696    }
1697    let axis = axis.normalized().ok()?;
1698    let coordinates = |point: Vec3| -> (f64, f64) {
1699        let offset = point.sub(origin);
1700        let height = offset.dot(axis);
1701        (offset.sub(axis.scale(height)).length(), height)
1702    };
1703    let meridian = |point: Vec3| -> f64 {
1704        let (radius, height) = coordinates(point);
1705        if radial { radius } else { height }
1706    };
1707    let scale = contacts.iter().map(|point| point.sub(origin).length()).fold(1.0, f64::max);
1708    let parallel_band = 1e-9 * scale;
1709    let margin = 1e-5 * scale;
1710    // Every boundary edge but the seams must be a parallel: one radius and
1711    // one height along the whole edge, read at nine points.
1712    let mut boundaries: Vec<f64> = Vec::new();
1713    for loop_record in &face.loops {
1714        for coedge in &loop_record.coedges {
1715            if loop_record.coedges.iter().filter(|other| other.edge_id == coedge.edge_id).count() == 2 {
1716                continue;
1717            }
1718            let boundary = solid.edges.iter().find(|candidate| candidate.id == coedge.edge_id)?;
1719            if boundary.degenerate {
1720                continue;
1721            }
1722            let mut read: Option<(f64, f64)> = None;
1723            for step in 0..=8 {
1724                let point = boundary.curve.evaluate(boundary.t0 + (boundary.t1 - boundary.t0) * step as f64 / 8.0).ok()?;
1725                let here = coordinates(point);
1726                match read {
1727                    None => read = Some(here),
1728                    Some(first) => {
1729                        if (here.0 - first.0).abs() > parallel_band || (here.1 - first.1).abs() > parallel_band {
1730                            return None;
1731                        }
1732                    }
1733                }
1734            }
1735            let (radius, height) = read?;
1736            boundaries.push(if radial { radius } else { height });
1737        }
1738    }
1739    // One open cell holds every station, clear of every boundary parallel.
1740    let readings: Vec<f64> = contacts.iter().map(|point| meridian(*point)).collect();
1741    let low = readings.iter().copied().fold(f64::INFINITY, f64::min);
1742    let high = readings.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1743    if !(low.is_finite() && high.is_finite()) {
1744        return None;
1745    }
1746    if boundaries.iter().any(|boundary| *boundary >= low - margin && *boundary <= high + margin) {
1747        return None;
1748    }
1749    Some(probe(0))
1750}
1751
1752fn build_surgery(
1753    solid: &BrepSolid,
1754    edge: &EdgeRecord,
1755    first: &BlendMate,
1756    second: &BlendMate,
1757    rows: FittedRows,
1758    second_split: Option<SecondSeamSplit>,
1759    name: Option<&str>,
1760    crease: Option<crate::blend::carve::CarvedCrease>,
1761) -> Result<BrepSolid, KernelRefusal> {
1762    let mut result = solid.clone();
1763    let mut take_id = crate::blend::edge::fresh_id_source(solid);
1764
1765    let [u_start, u_end] = rows.u_domain;
1766    let cr_start = rows.cr.evaluate(u_start).or_refuse(KernelStage::Refine, "evaluate")?;
1767    let cs_start = rows.cs.evaluate(u_start).or_refuse(KernelStage::Refine, "evaluate")?;
1768    let vertex1_id = take_id();
1769    let vertex2_id = take_id();
1770    result.vertices.push(VertexRecord {
1771        id: vertex1_id,
1772        point: cr_start,
1773    });
1774    result.vertices.push(VertexRecord {
1775        id: vertex2_id,
1776        point: cs_start,
1777    });
1778
1779    let cr_edge_id = take_id();
1780    result.edges.push(EdgeRecord {
1781        id: cr_edge_id,
1782        curve: rows.cr.clone(),
1783        t0: u_start,
1784        t1: u_end,
1785        start_vertex_id: vertex1_id,
1786        end_vertex_id: vertex1_id,
1787        degenerate: false,
1788        name: None,
1789    });
1790    // Second support: whole closed edge, or two pieces split where it
1791    // crosses ITS carrier's seam meridian (both-seam closed edges).  Each
1792    // piece records (edge id, fit-space window, forward pcurve).
1793    let mut cs_pieces: Vec<(u64, [f64; 2], NurbsCurve)> = Vec::new();
1794    let mut second_seam_vertex = vertex2_id;
1795    let mut second_seam_point = cs_start;
1796    let mut second_crossing_v = 0.0;
1797    if let Some(split) = &second_split {
1798        let p = split.fit_parameter;
1799        second_crossing_v = split.crossing_v;
1800        let (cs_a, cs_b) = rows.cs.split(p).or_refuse(KernelStage::Refine, "split")?;
1801        let (pc_a, pc_b) = rows.cs_pcurve.split(p).or_refuse(KernelStage::Refine, "split")?;
1802        // Bring the wrapped second piece back into the carrier's domain.
1803        let mut pc_b = pc_b;
1804        for point in pc_b.control_points.iter_mut() {
1805            point.x -= split.period * point.w;
1806        }
1807        let w2s = take_id();
1808        second_seam_vertex = w2s;
1809        second_seam_point = rows.cs.evaluate(p).or_refuse(KernelStage::Refine, "evaluate")?;
1810        result.vertices.push(VertexRecord {
1811            id: w2s,
1812            point: second_seam_point,
1813        });
1814        let edge_a = take_id();
1815        result.edges.push(EdgeRecord {
1816            id: edge_a,
1817            curve: cs_a,
1818            t0: u_start,
1819            t1: p,
1820            start_vertex_id: vertex2_id,
1821            end_vertex_id: w2s,
1822            degenerate: false,
1823            name: None,
1824        });
1825        cs_pieces.push((edge_a, [u_start, p], pc_a));
1826        let edge_b = take_id();
1827        result.edges.push(EdgeRecord {
1828            id: edge_b,
1829            curve: cs_b,
1830            t0: p,
1831            t1: u_end,
1832            start_vertex_id: w2s,
1833            end_vertex_id: vertex2_id,
1834            degenerate: false,
1835            name: None,
1836        });
1837        cs_pieces.push((edge_b, [p, u_end], pc_b));
1838    } else {
1839        let cs_edge_id = take_id();
1840        result.edges.push(EdgeRecord {
1841            id: cs_edge_id,
1842            curve: rows.cs.clone(),
1843            t0: u_start,
1844            t1: u_end,
1845            start_vertex_id: vertex2_id,
1846            end_vertex_id: vertex2_id,
1847            degenerate: false,
1848            name: None,
1849        });
1850        cs_pieces.push((cs_edge_id, [u_start, u_end], rows.cs_pcurve.clone()));
1851    }
1852    let seam_curve = rows.surface.iso_curve_u(u_start).or_refuse(KernelStage::Refine, "iso_curve_u")?;
1853    let [seam_t0, seam_t1] = seam_curve.domain().or_refuse(KernelStage::Refine, "domain")?;
1854    let blend_seam_id = take_id();
1855    result.edges.push(EdgeRecord {
1856        id: blend_seam_id,
1857        curve: seam_curve,
1858        t0: seam_t0,
1859        t1: seam_t1,
1860        start_vertex_id: vertex1_id,
1861        end_vertex_id: vertex2_id,
1862        degenerate: false,
1863        name: None,
1864    });
1865
1866    let replace_in_face = |result: &mut BrepSolid, mate: &BlendMate, pieces: &[(u64, [f64; 2], NurbsCurve)], uv_new: [f64; 2]| -> Result<bool, KernelRefusal> {
1867        replace_rim_in_face(result, edge, mate, pieces, uv_new)
1868    };
1869    let uv1_new = rows.cr_pcurve.evaluate(u_start).or_refuse(KernelStage::Refine, "evaluate")?;
1870    let v1_new = uv1_new.y;
1871    let cr_pieces = vec![(cr_edge_id, [u_start, u_end], rows.cr_pcurve.clone())];
1872    let mut repaired = replace_in_face(&mut result, first, &cr_pieces, [uv1_new.x, v1_new])?;
1873    let uv2_new = rows.cs_pcurve.evaluate(u_start).or_refuse(KernelStage::Refine, "evaluate")?;
1874    let v2_new = if second_split.is_some() {
1875        second_crossing_v
1876    } else {
1877        uv2_new.y
1878    };
1879    repaired |= replace_in_face(&mut result, second, &cs_pieces, [uv2_new.x, v2_new])?;
1880
1881    // A contact circle about an axis oblique to a sphere's stored polar axis
1882    // can wind once around that sphere's U period.  Such a circle is not an
1883    // ordinary hole in the full-domain sphere rectangle: it bounds a cap with
1884    // one of the collapsed pole rims.  Keep that pole as the companion loop so
1885    // containment, integration, and tessellation see the actual cap topology.
1886    let collapse_winding_sphere_cap =
1887        |result: &mut BrepSolid, face_id: u64, support_ids: &[u64]| -> Result<(), KernelRefusal> {
1888            let face = result
1889                .shells
1890                .iter_mut()
1891                .flat_map(|shell| &mut shell.faces)
1892                .find(|face| face.id == face_id)
1893                .ok_or(KernelRefusal::internal(KernelStage::Sew, "sphere_carrier", "blend: sphere carrier lost during cap surgery"))?;
1894            if !matches!(
1895                face.surface.analytic(),
1896                Some(crate::AnalyticSurface::Sphere { .. })
1897            ) || face.surface.closed_directions().or_refuse(KernelStage::Refine, "closed_directions")? != (true, false)
1898            {
1899                return Ok(());
1900            }
1901            let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
1902            let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
1903            let period = u1 - u0;
1904            let support_loop = face.loops.iter().position(|loop_record| {
1905                !loop_record.coedges.is_empty()
1906                    && loop_record
1907                        .coedges
1908                        .iter()
1909                        .all(|coedge| support_ids.contains(&coedge.edge_id))
1910            });
1911            let Some(support_loop) = support_loop else {
1912                return Ok(());
1913            };
1914            if face.loops[support_loop].coedges.len() != 1 {
1915                return Ok(());
1916            }
1917            let support = &face.loops[support_loop].coedges[0];
1918            let [s0, s1] = support.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
1919            let support_start = support.pcurve.evaluate(s0).or_refuse(KernelStage::Refine, "evaluate")?;
1920            let support_end = support.pcurve.evaluate(s1).or_refuse(KernelStage::Refine, "evaluate")?;
1921            let support_winding = support_end.x - support_start.x;
1922            if (support_winding.abs() - period).abs() > 0.05 * period {
1923                return Ok(());
1924            }
1925
1926            let mut pole: Option<(usize, CoedgeRecord)> = None;
1927            for (loop_index, loop_record) in face.loops.iter().enumerate() {
1928                if loop_index == support_loop {
1929                    continue;
1930                }
1931                for coedge in &loop_record.coedges {
1932                    let [p0, p1] = coedge.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
1933                    let start = coedge.pcurve.evaluate(p0).or_refuse(KernelStage::Refine, "evaluate")?;
1934                    let end = coedge.pcurve.evaluate(p1).or_refuse(KernelStage::Refine, "evaluate")?;
1935                    let winding = end.x - start.x;
1936                    let at_pole = (start.y - v0).abs() <= 1e-8 || (start.y - v1).abs() <= 1e-8;
1937                    if at_pole
1938                        && (end.y - start.y).abs() <= 1e-8
1939                        && (winding.abs() - period).abs() <= 0.05 * period
1940                        && winding * support_winding < 0.0
1941                    {
1942                        pole = Some((loop_index, coedge.clone()));
1943                        break;
1944                    }
1945                }
1946                if pole.is_some() {
1947                    break;
1948                }
1949            }
1950            let Some((pole_loop, pole_coedge)) = pole else {
1951                return Ok(());
1952            };
1953            let support_record = face.loops[support_loop].clone();
1954            let pole_id = face.loops[pole_loop].id;
1955            face.loops = vec![
1956                LoopRecord {
1957                    id: pole_id,
1958                    coedges: vec![pole_coedge],
1959                },
1960                support_record,
1961            ];
1962            Ok(())
1963        };
1964    collapse_winding_sphere_cap(&mut result, first.face.id, &[cr_edge_id])?;
1965    let cs_edge_ids: Vec<u64> = cs_pieces.iter().map(|(edge_id, ..)| *edge_id).collect();
1966    collapse_winding_sphere_cap(&mut result, second.face.id, &cs_edge_ids)?;
1967    // Patch the zero coedge ids introduced for extra pieces.
1968    for shell in &mut result.shells {
1969        for face in &mut shell.faces {
1970            for loop_record in &mut face.loops {
1971                for coedge in &mut loop_record.coedges {
1972                    if coedge.id == 0 {
1973                        coedge.id = take_id();
1974                    }
1975                }
1976            }
1977        }
1978    }
1979
1980    // Trim seam EDGES that ended on the removed vertex: their endpoint
1981    // moves onto the support-curve crossing on THEIR carrier (first
1982    // mate's seam -> the blend seam vertex; second mate's -> its own
1983    // seam-crossing vertex).
1984    let new_edge_ids: Vec<u64> = std::iter::once(cr_edge_id)
1985        .chain(cs_pieces.iter().map(|(edge_id, ..)| *edge_id))
1986        .chain(std::iter::once(blend_seam_id))
1987        .collect();
1988    let first_face_edges: Vec<u64> = first
1989        .face
1990        .loops
1991        .iter()
1992        .flat_map(|loop_record| loop_record.coedges.iter().map(|coedge| coedge.edge_id))
1993        .collect();
1994    repaired |= trim_seam_edges(
1995        &mut result,
1996        edge,
1997        &new_edge_ids,
1998        &first_face_edges,
1999        (vertex1_id, v1_new, cr_start),
2000        (second_seam_vertex, v2_new, second_seam_point),
2001    )?;
2002
2003    // Blend face: outward orientation matches F1's outward at the v=0 rim.
2004    let mid_u = (u_start + u_end) * 0.5;
2005    let blend_normal = raw_normal(&rows.surface, mid_u, 0.0)?;
2006    let station_uv = rows.cr_pcurve.evaluate(mid_u).or_refuse(KernelStage::Refine, "evaluate")?;
2007    let n1 = raw_normal(&first.face.surface, station_uv.x, station_uv.y)?;
2008    let out1 = if first.face.same_sense {
2009        n1
2010    } else {
2011        n1.scale(-1.0)
2012    };
2013    let same_sense = blend_normal.dot(out1) >= 0.0;
2014    let loop_id = take_id();
2015    let mut coedges = vec![
2016        CoedgeRecord {
2017            id: take_id(),
2018            edge_id: cr_edge_id,
2019            forward: true,
2020            pcurve: crate::sweep_topology::parameter_line(u_start, 0.0, u_end, 0.0).or_refuse(KernelStage::Refine, "parameter_line")?,
2021        },
2022        CoedgeRecord {
2023            id: take_id(),
2024            edge_id: blend_seam_id,
2025            forward: true,
2026            pcurve: crate::sweep_topology::parameter_line(u_end, 0.0, u_end, 1.0).or_refuse(KernelStage::Refine, "parameter_line")?,
2027        },
2028    ];
2029    for (edge_id, window, _) in cs_pieces.iter().rev() {
2030        coedges.push(CoedgeRecord {
2031            id: take_id(),
2032            edge_id: *edge_id,
2033            forward: false,
2034            pcurve: crate::sweep_topology::parameter_line(window[1], 1.0, window[0], 1.0).or_refuse(KernelStage::Refine, "parameter_line")?,
2035        });
2036    }
2037    coedges.push(CoedgeRecord {
2038        id: take_id(),
2039        edge_id: blend_seam_id,
2040        forward: false,
2041        pcurve: crate::sweep_topology::parameter_line(u_start, 1.0, u_start, 0.0).or_refuse(KernelStage::Refine, "parameter_line")?,
2042    });
2043    // The coedges above trace the parameter rectangle counter-clockwise in
2044    // (u, v); that traversal is only the outward boundary when the blend
2045    // surface normal already points outward (same_sense).  When it does not
2046    // (a mate whose support rim runs the other way — e.g. the reversed cap
2047    // of a seam carrier), the loop must wind the OTHER way so its coedges
2048    // traverse the shared support edges opposite to the mate, and so the
2049    // classification tangent test (parameter_point_in_face) stays consistent
2050    // with same_sense.  Reversing the coedge order and each coedge (forward
2051    // flag + pcurve) flips the winding without touching same_sense.
2052    if !same_sense {
2053        coedges.reverse();
2054        for coedge in &mut coedges {
2055            coedge.forward = !coedge.forward;
2056            coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Refine, "reversed")?;
2057        }
2058    }
2059    let mut loops = vec![LoopRecord {
2060        id: loop_id,
2061        coedges,
2062    }];
2063    // The CARVED lens: an INNER loop of two coedges on ONE new edge — the
2064    // crease — both of them this face's own, the slit pattern the closed
2065    // chain lane sews (`chain/closed_surgery.rs`): the two sheets of the wall
2066    // are one surface, so the curve where they meet has one edge and two
2067    // coedges.  The lens between them is the part of the swept envelope
2068    // inside the swept ball volume, and dropping it is what makes the wall
2069    // the blend.  Winding: the inner loop runs AGAINST the outer one, read
2070    // off both loops' signed areas rather than assumed.
2071    if let Some(crease) = crease {
2072        let start_vertex = take_id();
2073        let end_vertex = take_id();
2074        let crease_edge = take_id();
2075        result.vertices.push(VertexRecord { id: start_vertex, point: crease.start });
2076        result.vertices.push(VertexRecord { id: end_vertex, point: crease.end });
2077        let [crease_t0, crease_t1] = crease.curve.domain().or_refuse(KernelStage::Refine, "domain")?;
2078        result.edges.push(EdgeRecord {
2079            id: crease_edge,
2080            curve: crease.curve,
2081            t0: crease_t0,
2082            t1: crease_t1,
2083            start_vertex_id: start_vertex,
2084            end_vertex_id: end_vertex,
2085            degenerate: false,
2086            name: name.map(|value| format!("{value}:CREASE")),
2087        });
2088        let outer = crate::blend::chain::signed_area(&loops[0].coedges)?;
2089        let forward_first = crate::blend::chain::signed_area(&[
2090            CoedgeRecord { id: 0, edge_id: crease_edge, forward: true, pcurve: crease.first.clone() },
2091            CoedgeRecord { id: 0, edge_id: crease_edge, forward: false, pcurve: crease.second.reversed().or_refuse(KernelStage::Refine, "reversed")? },
2092        ])?;
2093        let inner = if outer * forward_first < 0.0 {
2094            vec![
2095                CoedgeRecord { id: take_id(), edge_id: crease_edge, forward: true, pcurve: crease.first },
2096                CoedgeRecord { id: take_id(), edge_id: crease_edge, forward: false, pcurve: crease.second.reversed().or_refuse(KernelStage::Refine, "reversed")? },
2097            ]
2098        } else {
2099            vec![
2100                CoedgeRecord { id: take_id(), edge_id: crease_edge, forward: true, pcurve: crease.second },
2101                CoedgeRecord { id: take_id(), edge_id: crease_edge, forward: false, pcurve: crease.first.reversed().or_refuse(KernelStage::Refine, "reversed")? },
2102            ]
2103        };
2104        loops.push(LoopRecord { id: take_id(), coedges: inner });
2105    }
2106    let blend_face = FaceRecord {
2107        id: take_id(),
2108        surface: rows.surface,
2109        same_sense,
2110        loops,
2111        name: name.map(|value| value.to_string()),
2112    };
2113    let shell_index = result
2114        .shells
2115        .iter()
2116        .position(|shell| shell.faces.iter().any(|face| face.id == first.face.id))
2117        .ok_or(KernelRefusal::internal(KernelStage::Sew, "mate_shell", "blend: mate shell lost during surgery"))?;
2118    result.shells[shell_index].faces.push(blend_face);
2119
2120    let used_edges: std::collections::HashSet<u64> = result
2121        .shells
2122        .iter()
2123        .flat_map(|shell| &shell.faces)
2124        .flat_map(|face| &face.loops)
2125        .flat_map(|loop_record| &loop_record.coedges)
2126        .map(|coedge| coedge.edge_id)
2127        .collect();
2128    result
2129        .edges
2130        .retain(|candidate| used_edges.contains(&candidate.id));
2131    let used_vertices: std::collections::HashSet<u64> = result
2132        .edges
2133        .iter()
2134        .flat_map(|candidate| [candidate.start_vertex_id, candidate.end_vertex_id])
2135        .collect();
2136    result
2137        .vertices
2138        .retain(|candidate| used_vertices.contains(&candidate.id));
2139    // A surgery that had to REPAIR a neighbour trim took a branch no existing
2140    // fixture exercises, so it does not get the benefit of the doubt: prove the
2141    // result before returning it.  Paths that never repaired are untouched (the
2142    // check does not run), so this cannot slow or change anything that already
2143    // works — and the new branch can never ship a plausible-looking wrong solid
2144    // the way the un-repaired trim did.
2145    if repaired {
2146        let problems = result.validate_memoised();
2147        if !problems.is_empty() {
2148            return Err(KernelRefusal::internal(KernelStage::Validate, "neighbour_trim_closure", format!(
2149                "blend: the repaired neighbour trim did not close ({} issue(s), first: {})",
2150                problems.len(),
2151                problems
2152                    .first()
2153                    .map(|issue| issue.message.as_str())
2154                    .unwrap_or("unknown")
2155            )));
2156        }
2157    }
2158    Ok(result)
2159}
2160
2161/// Replace the blended edge's coedge in one mate's loop with the support
2162/// pieces (edge id, fit-space window, forward pcurve) in u order, and pull
2163/// the loop's seam-meridian pcurves that met the removed vertex down to the
2164/// support crossing at `uv_new` on this carrier. `true` when a neighbour trim
2165/// was repaired. The closed lane's own surgery and the rollover's share it.
2166pub(in crate::blend) fn replace_rim_in_face(
2167    result: &mut BrepSolid,
2168    edge: &EdgeRecord,
2169    mate: &BlendMate,
2170    pieces: &[(u64, [f64; 2], NurbsCurve)],
2171    uv_new: [f64; 2],
2172) -> Result<bool, KernelRefusal> {
2173    let old_vertex = edge.start_vertex_id;
2174    let v_new = uv_new[1];
2175    // (edge id, the START vertex is the removed one, the END vertex is).
2176    let seam_edge_ends: Vec<(u64, bool, bool)> = result
2177        .edges
2178        .iter()
2179        .filter(|candidate| {
2180            candidate.id != edge.id
2181                && (candidate.start_vertex_id == old_vertex
2182                    || candidate.end_vertex_id == old_vertex)
2183        })
2184        .map(|candidate| {
2185            (
2186                candidate.id,
2187                candidate.start_vertex_id == old_vertex,
2188                candidate.end_vertex_id == old_vertex,
2189            )
2190        })
2191        .collect();
2192    let seam_edge_ids: Vec<u64> = seam_edge_ends.iter().map(|(id, ..)| *id).collect();
2193    let pcurve_band = crate::KernelTolerances::for_solid(result, 1e-7).pcurve_consistency;
2194    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
2195    let face = result
2196        .shells
2197        .iter_mut()
2198        .flat_map(|shell| &mut shell.faces)
2199        .find(|face| face.id == mate.face.id)
2200        .ok_or(KernelRefusal::internal(KernelStage::Sew, "mate_face", "blend: mate face lost during surgery"))?;
2201    let face_id = face.id;
2202    let FaceRecord { surface, loops, .. } = &mut *face;
2203    let loop_record = &mut loops[mate.loop_index];
2204    let position = loop_record
2205        .coedges
2206        .iter()
2207        .position(|coedge| coedge.edge_id == edge.id)
2208        .ok_or(KernelRefusal::internal(KernelStage::Sew, "edge_coedge", "blend: edge coedge lost during surgery"))?;
2209    let old_forward = loop_record.coedges[position].forward;
2210    let old_seam_v = {
2211        let pcurve = &loop_record.coedges[position].pcurve;
2212        let [d0, _] = pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
2213        pcurve.evaluate(d0).or_refuse(KernelStage::Refine, "evaluate")?.y
2214    };
2215    // Replacement coedges: pieces run in u order; a reversed loop use
2216    // takes them in reverse order, each reversed.
2217    let mut replacements = Vec::new();
2218    let ordered: Vec<&(u64, [f64; 2], NurbsCurve)> = if old_forward {
2219        pieces.iter().collect()
2220    } else {
2221        pieces.iter().rev().collect()
2222    };
2223    for (index, (edge_id, _, pcurve)) in ordered.iter().enumerate() {
2224        replacements.push(CoedgeRecord {
2225            id: if index == 0 {
2226                loop_record.coedges[position].id
2227            } else {
2228                0 // patched by the caller with fresh ids
2229            },
2230            edge_id: *edge_id,
2231            forward: old_forward,
2232            pcurve: if old_forward {
2233                pcurve.clone()
2234            } else {
2235                pcurve.reversed().or_refuse(KernelStage::Refine, "reversed")?
2236            },
2237        });
2238    }
2239    loop_record
2240        .coedges
2241        .splice(position..=position, replacements);
2242    let mut repaired = false;
2243    if loop_record.coedges.len() > 1 {
2244        // Anchored carrier: the loop's other coedges ride the seam
2245        // meridian between the old edge and the rest of the trim.
2246        // Pull the pcurve endpoint that met the old edge down to the
2247        // support crossing.  (The seam EDGE itself is trimmed after
2248        // both replacements, outside this borrow.)
2249        for coedge in &mut loop_record.coedges {
2250            if pieces
2251                .iter()
2252                .any(|(edge_id, ..)| *edge_id == coedge.edge_id)
2253                || !seam_edge_ids.contains(&coedge.edge_id)
2254            {
2255                continue;
2256            }
2257            let controls = &coedge.pcurve.control_points;
2258            let last_index = controls.len() - 1;
2259            let first_u = controls[0].x / controls[0].w;
2260            let last_u = controls[last_index].x / controls[last_index].w;
2261            let constant_u = (first_u - last_u).abs()
2262                <= 1e-9 * (1.0 + first_u.abs().max(last_u.abs()));
2263            // Which end of the pcurve met the removed vertex, and the uv
2264            // the crossing sits at on this carrier.
2265            let (target, target_uv, fraction) = if constant_u {
2266                // Seam MERIDIAN pcurve: constant u, runs along the v
2267                // direction; the endpoint at the removed edge's v moves
2268                // onto the support crossing.
2269                let first_v = controls[0].y / controls[0].w;
2270                let last_v = controls[last_index].y / controls[last_index].w;
2271                let target = if (first_v - old_seam_v).abs() < (last_v - old_seam_v).abs() {
2272                    0
2273                } else {
2274                    last_index
2275                };
2276                let span = last_v - first_v;
2277                let fraction = if span.abs() > 0.0 { (v_new - first_v) / span } else { 0.0 };
2278                (target, [first_u, v_new], fraction)
2279            } else {
2280                // The adjacent trim runs along U at constant v — the
2281                // carrier's OTHER (v) seam, which is what a closed edge
2282                // lying on one whole MERIDIAN borders (an axial-plane
2283                // collar on a torus).  Its endpoint moves in U, not V,
2284                // and the v-distance rule above cannot pick the end at
2285                // all: both ends share the same v, so it always lands on
2286                // `last_index`, which is wrong for one of the seam PAIR
2287                // (the v-seam edge appears twice in the loop, at v = 0
2288                // and v = 1).  Take the end from the TOPOLOGY.
2289                let Some((_, start_is_old, end_is_old)) = seam_edge_ends
2290                    .iter()
2291                    .find(|(id, ..)| *id == coedge.edge_id)
2292                    .copied()
2293                else {
2294                    continue;
2295                };
2296                if start_is_old == end_is_old {
2297                    return Err(KernelRefusal::ill_posed(KernelStage::Sew, "neighbour_trim_end", format!(
2298                        "blend: neighbour edge {} meets the blended edge at both ends; \
2299                         its trim end is ambiguous",
2300                        coedge.edge_id
2301                    )));
2302                }
2303                // `forward` maps the coedge's pcurve domain start onto the
2304                // edge's t0 (its start vertex).
2305                let target = if start_is_old == coedge.forward { 0 } else { last_index };
2306                let v_end = controls[target].y / controls[target].w;
2307                let span = last_u - first_u;
2308                let fraction = if span.abs() > 0.0 { (uv_new[0] - first_u) / span } else { 0.0 };
2309                (target, [uv_new[0], v_end], fraction)
2310            };
2311            // The trim is a SPLIT of the pcurve at the crossing's own
2312            // parameter, never a moved control point.  Moving the end
2313            // control point of a pcurve with interior knots re-slopes its
2314            // end span alone and breaks the pcurve ↔ edge parameter
2315            // correspondence validate reads (measured 2026-10-03 on the
2316            // torus-box-edge and axial-collar documents: the torus's
2317            // v-seam pcurve, a 3-span polyline, read 0.548 mm off its
2318            // edge at the same parameter while its image was on the edge
2319            // to 1e-10).  The seam-edge pass below projects the same
2320            // physical point onto the edge curve for the edge's own
2321            // parameter, so both sides keep the correspondence they had.
2322            let [q0, q1] = coedge.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
2323            let target_point = surface
2324                .evaluate_extended(target_uv[0], target_uv[1])
2325                .or_refuse(KernelStage::Refine, "evaluate_extended")?;
2326            // Seeded at the AFFINE fraction of the pcurve's extent in the
2327            // moving direction (the seed `trim_edge_at` uses), not at the
2328            // pcurve's end: a crossing deep in a long seam would hand the
2329            // point solver a far seed and turn a blend that built into a
2330            // refusal.  The solver refines the seed to the physical point.
2331            let seed = (q0 + (q1 - q0) * fraction).clamp(q0.min(q1), q0.max(q1));
2332            let q_split = trim_parameter_at_point(
2333                surface, &coedge.pcurve, seed, target_point, pcurve_band,
2334            )?;
2335            let interior = q_split > q0 + 1e-9 * (q1 - q0) && q_split < q1 - 1e-9 * (q1 - q0);
2336            if debug {
2337                eprintln!(
2338                    "closed-edge seam trim: face {face_id} edge {} coedge {} ({}): {} at q {q_split:.9} of [{q0:.6}, {q1:.6}], {} control points",
2339                    coedge.edge_id, coedge.id, if constant_u { "meridian, constant u" } else { "along u" },
2340                    if interior { "SPLIT" } else { "EXTEND" }, controls.len()
2341                );
2342            }
2343            if interior {
2344                let (low, high) = coedge.pcurve.split(q_split).or_refuse(KernelStage::Refine, "split")?;
2345                coedge.pcurve = if target == 0 { high } else { low };
2346            } else {
2347                // The crossing lies at or past the pcurve's end: the seam
2348                // EXTENDS to meet it.  Exact for a two-point linear
2349                // pcurve, whose one span IS the whole parameterisation;
2350                // anything else would need a refit and is refused by name.
2351                if coedge.pcurve.degree != 1 || controls.len() != 2 {
2352                    return Err(KernelRefusal::unsupported(KernelStage::Sew, "neighbour_seam_extend_curved", format!(
2353                        "blend: neighbour seam edge {} would have to extend past its own end to meet the blend's support crossing, and its pcurve is not a single straight span (degree {}, {} control points)",
2354                        coedge.edge_id, coedge.pcurve.degree, controls.len()
2355                    )));
2356                }
2357                let w = coedge.pcurve.control_points[target].w;
2358                coedge.pcurve.control_points[target] = crate::Vec4::from_point(
2359                    Vec3::new(target_uv[0], target_uv[1], 0.0), w,
2360                );
2361            }
2362            repaired = true;
2363        }
2364    }
2365    Ok(repaired)
2366}
2367
2368/// Trim the seam EDGES that ended on the removed vertex: each endpoint moves
2369/// onto the support crossing on ITS carrier — an edge of the first mate's
2370/// face to `first_target`, any other to `second_target`, each a (vertex,
2371/// seam-meridian parameter, point). `new_edge_ids` are the surgery's own
2372/// edges, skipped. `true` when a trim had to be re-projected (repaired).
2373pub(in crate::blend) fn trim_seam_edges(
2374    result: &mut BrepSolid,
2375    edge: &EdgeRecord,
2376    new_edge_ids: &[u64],
2377    first_face_edges: &[u64],
2378    first_target: (u64, f64, Vec3),
2379    second_target: (u64, f64, Vec3),
2380) -> Result<bool, KernelRefusal> {
2381    let old_vertex = edge.start_vertex_id;
2382    let mut repaired = false;
2383    let (vertex1_id, v1_new, cr_start) = first_target;
2384    let (second_seam_vertex, v2_new, second_seam_point) = second_target;
2385    for seam_edge in result.edges.iter_mut() {
2386        if new_edge_ids.contains(&seam_edge.id) {
2387            continue;
2388        }
2389        if seam_edge.start_vertex_id != old_vertex && seam_edge.end_vertex_id != old_vertex {
2390            continue;
2391        }
2392        let (target_vertex, target_v, target_point) = if first_face_edges.contains(&seam_edge.id) {
2393            (vertex1_id, v1_new, cr_start)
2394        } else {
2395            (second_seam_vertex, v2_new, second_seam_point)
2396        };
2397        let [c0, c1] = seam_edge.curve.domain().or_refuse(KernelStage::Refine, "domain")?;
2398        let clamped = target_v.clamp(c0.min(c1), c0.max(c1));
2399        // Using the support crossing's V as the neighbour's CURVE parameter is
2400        // only valid when that neighbour is the carrier's seam MERIDIAN, whose
2401        // 3D curve is parameterized by v.  Verify it against the vertex the
2402        // endpoint is moving to; a neighbour running along U instead (the
2403        // carrier's v-seam, bordered by a collar edge that lies on one whole
2404        // meridian) lands nowhere near it — the 2026-09-01 report trimmed the
2405        // torus' equator seam to u = 0, 10.885 away from its own vertex, and
2406        // the solid failed validation with "curve start does not match vertex".
2407        let band = 1e-6 * (1.0 + target_point.length());
2408        let split_parameter = if seam_edge.id == edge.id {
2409            // The BLENDED edge itself still carries the removed vertex at this
2410            // point.  Its coedges have already been replaced in both mates, so
2411            // the used-edge sweep below discards it; leave its (meaningless)
2412            // trim exactly as it was rather than asking a doomed edge to pass
2413            // through the support start.
2414            clamped
2415        } else {
2416            match seam_edge.curve.evaluate(clamped) {
2417                Ok(point) if point.sub(target_point).length() <= band => clamped,
2418                _ => {
2419                    repaired = true;
2420                    let projection =
2421                        crate::project_point_to_curve(&seam_edge.curve, target_point).or_refuse(KernelStage::Refine, "project_point_to_curve")?;
2422                    if projection.distance > band {
2423                        return Err(KernelRefusal::unsupported(KernelStage::Sew, "neighbour_off_support", format!(
2424                            "blend: neighbour edge {} does not pass through the blend's support \
2425                             start (off by {:.9}); the trim has no parameter to move to",
2426                            seam_edge.id, projection.distance
2427                        )));
2428                    }
2429                    projection.u.clamp(c0.min(c1), c0.max(c1))
2430                }
2431            }
2432        };
2433        if seam_edge.start_vertex_id == old_vertex {
2434            seam_edge.t0 = split_parameter;
2435            seam_edge.start_vertex_id = target_vertex;
2436        }
2437        if seam_edge.end_vertex_id == old_vertex {
2438            seam_edge.t1 = split_parameter;
2439            seam_edge.end_vertex_id = target_vertex;
2440        }
2441    }
2442    Ok(repaired)
2443}