Skip to main content

brep_blend/blending/blend/edge/
closed.rs

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