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