Skip to main content

brep_blend/blending/fillet/
edges.rs

1use super::*;
2
3/// Constant-radius rolling-ball fillet of one edge (Golovanov §4.9 march,
4/// §6.9 surgery; the cutter only where the march refuses).
5pub fn fillet_edge(
6    solid: &BrepSolid,
7    edge_id: u64,
8    radius: f64,
9    name: Option<&str>,
10) -> Result<BrepSolid, KernelRefusal> {
11    // One blend operation: the reports of an earlier one, never consumed, are
12    // dropped as it starts (nested calls keep this operation's).
13    let _operation = crate::blend::BlendOperation::enter();
14    check_mixed_concavity(solid, edge_id, "fillet_edge")?;
15    check_support_extent_clipping(solid, edge_id, radius, "fillet_edge")?;
16    fillet_or_chamfer(solid, edge_id, radius, false, name, ToolEnds::default(), Lane::GeneralFirst)
17        .map_err(|refusal| size_refusal(solid, edge_id, radius, false, name, "fillet_edge", refusal))
18}
19
20/// A blend refused because the rolling ball's contact system has no solution
21/// (`Newton is singular`) says so by name, with the size that does build.
22///
23/// A ball that does not fit beside the edge has no contact points to solve
24/// for: on the rim of a bore through a fillet (a wall 1.5 thick between the
25/// bore and the fillet's torus) no ball wider than the wall rolls, and every
26/// lane's solver stops singular, which was reported as an internal error of
27/// three lanes. A chamfer's distance is its ball's radius, so the same holds
28/// for it. This runs only after such a refusal: the same blend is tried at
29/// half, a quarter and an eighth of the size, and where one builds the
30/// largest size that does is bracketed in five more tries and named. Where
31/// none builds, the refusal is returned as it came.
32fn size_refusal(
33    solid: &BrepSolid,
34    edge_id: u64,
35    size: f64,
36    chamfer: bool,
37    name: Option<&str>,
38    entry: &str,
39    refusal: KernelRefusal,
40) -> KernelRefusal {
41    if !refusal.message.contains("Newton is singular") {
42        return refusal;
43    }
44    let builds = |size: f64| fillet_or_chamfer(solid, edge_id, size, chamfer, name, ToolEnds::default(), Lane::GeneralFirst).is_ok();
45    let mut too_large = size;
46    let mut fits = None;
47    for fraction in [0.5, 0.25, 0.125] {
48        if builds(size * fraction) {
49            fits = Some(size * fraction);
50            break;
51        }
52        too_large = size * fraction;
53    }
54    let Some(mut fits) = fits else {
55        return refusal;
56    };
57    for _ in 0..5 {
58        let middle = 0.5 * (fits + too_large);
59        if builds(middle) {
60            fits = middle;
61        } else {
62            too_large = middle;
63        }
64    }
65    KernelRefusal::input(
66        KernelStage::Refine,
67        "blend_size",
68        format!(
69            "{entry}: no rolling ball of radius {size} was found along this edge (a {kind}'s size is its ball's radius); \
70             a size up to about {fits:.3} builds. The solver's own words: {message}",
71            kind = if chamfer { "chamfer" } else { "fillet" },
72            message = refusal.message
73        ),
74    )
75}
76
77
78/// Equal-leg chamfer of one edge (Golovanov §6.11: the same construction
79/// with the arc's chord).
80pub fn chamfer_edge(
81    solid: &BrepSolid,
82    edge_id: u64,
83    distance: f64,
84    name: Option<&str>,
85) -> Result<BrepSolid, KernelRefusal> {
86    // One blend operation: the reports of an earlier one, never consumed, are
87    // dropped as it starts (nested calls keep this operation's).
88    let _operation = crate::blend::BlendOperation::enter();
89    check_mixed_concavity(solid, edge_id, "chamfer_edge")?;
90    check_support_extent(solid, edge_id, distance, "chamfer_edge")?;
91    fillet_or_chamfer(solid, edge_id, distance, true, name, ToolEnds::default(), Lane::GeneralFirst)
92        .map_err(|refusal| size_refusal(solid, edge_id, distance, true, name, "chamfer_edge", refusal))
93}
94
95/// Build and apply the chamfer tool for one straight edge from an already-built
96/// cross-section profile (curve index 1 is the chamfer chord / blend wall).
97/// Shared by the two-distance and distance-angle asymmetric entries.
98fn apply_chamfer_offsets_profile(
99    solid: &BrepSolid,
100    cross: &EdgeCross,
101    profile: &[NurbsCurve],
102    name: Option<&str>,
103    edge_id: u64,
104) -> Result<BrepSolid, KernelRefusal> {
105    // Run through to the faces the edge's ends meet where the rails go on past
106    // them (`BREP_CHAMFER_THROUGH_END_FACES`, default on; `=0` restores); the flush cutter
107    // below answers everything else.
108    if let Some(result) = super::tool::chamfer_through_end_faces(solid, edge_id, cross, profile, name) {
109        return Ok(settle_cutter_scaffold(result));
110    }
111    let mut tool = match &cross.path {
112        EdgePath::Straight { direction, length } => {
113            extrude_profile_brep(profile, *direction, *length)?
114        }
115        // A circular edge between carriers rotationally symmetric about its
116        // axis with straight meridians (`analyze_edge` admits nothing else):
117        // the legs lie on the meridians, so the chordal setbacks are also the
118        // distances along the faces, and the same section revolved about the
119        // axis is the exact tool (`BREP_CHAMFER_ASYM_CURVED`, default on).
120        EdgePath::Circular { .. } if chamfer_asym_curved_on() => {
121            super::tool::build_exact_tool(cross, profile, 0.0, ToolEnds::default(), name)?
122        }
123        EdgePath::Circular { .. } => {
124            return Err(KernelRefusal::unsupported(
125                KernelStage::Classify,
126                "asymmetric_curved_edge",
127                "chamfer_edge_asymmetric: only straight edges on planar faces are supported \
128                 in this slice (asymmetric chamfer on general/curved edges is out of scope)",
129            ));
130        }
131    };
132    // Side faces are emitted in input-curve order; the chamfer wall is the
133    // second profile curve (index 1). Every other face is the cutter's
134    // scaffold, tagged and settled exactly as the symmetric cutter's is.
135    let mut side_index = 0usize;
136    for shell in &mut tool.shells {
137        for face in &mut shell.faces {
138            if side_index == 1 {
139                if face.name.is_none() {
140                    face.name = name.map(str::to_string);
141                }
142            } else {
143                face.name = Some(scaffold_tag(name));
144            }
145            side_index += 1;
146        }
147    }
148    apply_tool(solid, &tool, cross.convex).map(settle_cutter_scaffold)
149}
150
151/// Asymmetric chamfers on curved edges (two-distance and distance-angle):
152/// on by default; `BREP_CHAMFER_ASYM_CURVED=0` restores the refusal
153/// `asymmetric_curved_edge`.
154pub fn chamfer_asym_curved_on() -> bool {
155    switch!("BREP_CHAMFER_ASYM_CURVED", true)
156}
157
158/// Asymmetric (two-distance) chamfer of one STRAIGHT edge between two planar
159/// faces (Golovanov §6.11): setback `d1` along face 1 and `d2` along face 2 —
160/// the standard CAD "d1 × d2" bevel.  General/curved edges are out of scope for
161/// this slice and return a clear error.
162pub fn chamfer_edge_asymmetric(
163    solid: &BrepSolid,
164    edge_id: u64,
165    d1: f64,
166    d2: f64,
167    name: Option<&str>,
168) -> Result<BrepSolid, KernelRefusal> {
169    // One blend operation: the reports of an earlier one, never consumed, are
170    // dropped as it starts (nested calls keep this operation's).
171    let _operation = crate::blend::BlendOperation::enter();
172    if !(d1 > 0.0) || !(d2 > 0.0) || !d1.is_finite() || !d2.is_finite() {
173        return Err(KernelRefusal::input(
174            KernelStage::Collect,
175            "setback_distances",
176            "chamfer_edge_asymmetric: both setback distances must be positive",
177        ));
178    }
179    // `analyze_edge` only uses the radius to size the orientation probe step;
180    // the smaller setback keeps that probe inside both faces.
181    let cross = match analyze_edge(solid, edge_id, d1.min(d2)) {
182        Ok(cross) => cross,
183        Err(refusal) if chamfer_asym_curved_on() => {
184            let faces = setback_faces(solid, edge_id).map_err(|_| refusal)?;
185            let law = crate::blend::setback::SetbackLaw::Distances { faces, distances: [d1, d2] };
186            return chamfer_by_setback_law(solid, edge_id, law, name, "chamfer_edge_asymmetric", false);
187        }
188        Err(refusal) => return Err(refusal),
189    };
190    let profile = chamfer_cross_section_offsets(&cross, d1, d2)?;
191    apply_chamfer_offsets_profile(solid, &cross, &profile, name, edge_id)
192}
193
194/// Conic-section blend of one edge: the rolling ball's two contacts joined by
195/// a conic instead of the ball's arc.
196///
197/// `radius` places the contacts exactly where `fillet_edge` places them, the
198/// distance `radius / tan(θ/2)` from the edge on each face (θ the angle
199/// between the faces; `radius` itself at a right angle). The section is the
200/// rational quadratic through those contacts whose middle pole is the point
201/// where the two faces' section lines meet (a point of the edge), with weights
202/// `1, rho / (1 − rho), 1`. It is tangent to both faces at the contacts. `rho`
203/// in `(0, 1)` is the fraction of the way from the contacts' chord to the edge
204/// that the section's middle reaches: `0.5` is a parabola, below it an ellipse,
205/// above it a hyperbola, and `sin(θ/2) / (1 + sin(θ/2))` (`√2 − 1` at a right
206/// angle) is the ball's own arc.
207///
208/// Built here for a straight edge between two planes, and for a circular edge
209/// between surfaces of revolution about its axis whose meridians are straight
210/// (a plane, a cylinder, a cone); any other edge is refused `conic_edge` by
211/// name. An edge that runs on into its neighbours is cut through to them, as
212/// a chamfer's is.
213pub fn fillet_edge_conic(
214    solid: &BrepSolid,
215    edge_id: u64,
216    radius: f64,
217    rho: f64,
218    name: Option<&str>,
219) -> Result<BrepSolid, KernelRefusal> {
220    let _operation = crate::blend::BlendOperation::enter();
221    if !(radius > 0.0) || !radius.is_finite() {
222        return Err(KernelRefusal::input(
223            KernelStage::Collect,
224            "conic_radius",
225            "fillet_edge_conic: the radius must be positive",
226        ));
227    }
228    if !(rho > 0.0 && rho < 1.0) {
229        return Err(KernelRefusal::input(
230            KernelStage::Collect,
231            "conic_rho",
232            "fillet_edge_conic: rho must lie strictly between 0 and 1",
233        ));
234    }
235    let cross = analyze_edge(solid, edge_id, radius).map_err(|refusal| {
236        KernelRefusal::unsupported(
237            KernelStage::Classify,
238            "conic_edge",
239            format!(
240                "fillet_edge_conic: a conic blend is built only on a straight edge between planes or a \
241                 circular edge between straight-sided surfaces about its axis ({})",
242                refusal.message
243            ),
244        )
245    })?;
246    if matches!(cross.path, EdgePath::Circular { .. }) && !chamfer_asym_curved_on() {
247        return Err(KernelRefusal::unsupported(
248            KernelStage::Classify,
249            "conic_edge",
250            "fillet_edge_conic: circular edges are switched off (BREP_CHAMFER_ASYM_CURVED=0)",
251        ));
252    }
253    let profile = super::tool::conic_cross_section(&cross, radius, rho)?;
254    let result = apply_chamfer_offsets_profile(solid, &cross, &profile, name, edge_id)?;
255    refuse_invalid_result(&result, "fillet_edge_conic")?;
256    Ok(result)
257}
258
259/// `fillet_edge_conic` for edges picked by a point on each. The edges are
260/// blended one after another and independently: where two of them meet, the
261/// vertex stays sharp between the two blends (no corner is built).
262pub fn fillet_edges_conic(
263    solid: &BrepSolid,
264    edge_points: &[Vec3],
265    edge_names: Option<&[String]>,
266    radius: f64,
267    rho: f64,
268    name: Option<&str>,
269) -> Result<BrepSolid, KernelRefusal> {
270    let _operation = crate::blend::BlendOperation::enter();
271    if edge_points.is_empty() {
272        return Err(KernelRefusal::input(
273            KernelStage::Collect,
274            "conic_selection",
275            "fillet_edges_conic: no edges selected",
276        ));
277    }
278    let mut result = solid.clone();
279    for (index, point) in edge_points.iter().enumerate() {
280        let edge_id = resolve_edge_by_point(&result, *point)?;
281        result = fillet_edge_conic(&result, edge_id, radius, rho, per_edge_name(edge_names, name, index))?;
282    }
283    Ok(result)
284}
285
286/// The ids of the edge's two faces in `analyze_edge`'s order (face 1 first):
287/// the faces the setbacks `d1` and `d2` are measured on.
288fn setback_faces(solid: &BrepSolid, edge_id: u64) -> Result<[u64; 2], KernelRefusal> {
289    let (_, faces) = super::analyze::edge_and_faces(solid, edge_id)?;
290    match faces.as_slice() {
291        [first, second] if first.id != second.id => Ok([first.id, second.id]),
292        _ => Err(KernelRefusal::input(
293            KernelStage::Collect,
294            "edge_faces",
295            format!("asymmetric chamfer: edge {edge_id} does not join two faces"),
296        )),
297    }
298}
299
300/// The input positions of the selected points that resolve onto the smooth
301/// chain through `edge_id`, when the chain has two or more edges and the
302/// not-yet-chamfered selection covers every one of them; else `None`.
303fn selected_chain(
304    solid: &BrepSolid,
305    edge_id: u64,
306    edge_points: &[Vec3],
307    done: &[bool],
308) -> Result<Option<Vec<usize>>, KernelRefusal> {
309    let Ok((members, _closed)) = crate::blend::smooth_chain_members(solid, edge_id) else {
310        return Ok(None);
311    };
312    if members.len() < 2 {
313        return Ok(None);
314    }
315    let mut positions = Vec::new();
316    for member in &members {
317        let position = edge_points.iter().enumerate().position(|(index, point)| {
318            !done[index] && resolve_edge_by_point(solid, *point).is_ok_and(|id| id == *member)
319        });
320        match position {
321            Some(position) => positions.push(position),
322            None => return Ok(None),
323        }
324    }
325    Ok(Some(positions))
326}
327
328/// An asymmetric chamfer the exact cutters do not cover (a curved edge on
329/// carriers that are not coaxial straight-meridian revolutions): the closed
330/// rim's march with its stations solved from the setback law
331/// (`blend/setback.rs`): a closed edge as its own rim, an open edge as the
332/// closed smooth chain it lies on or else alone, and with `walk_chain` the
333/// whole smooth chain (open or closed) a selection covers.
334fn chamfer_by_setback_law(
335    solid: &BrepSolid,
336    edge_id: u64,
337    law: crate::blend::setback::SetbackLaw,
338    name: Option<&str>,
339    entry: &str,
340    walk_chain: bool,
341) -> Result<BrepSolid, KernelRefusal> {
342    let edge = solid
343        .edges
344        .iter()
345        .find(|edge| edge.id == edge_id)
346        .ok_or_else(|| KernelRefusal::input(KernelStage::Collect, "edge", format!("{entry}: edge {edge_id} not found")))?;
347    let closed = edge.start_vertex_id == edge.end_vertex_id;
348    // The operand heal the symmetric ladder runs first (ids preserved).
349    let mut healed = solid.clone();
350    let policy = crate::KernelTolerances::for_solid(&healed, 1e-7);
351    crate::heal::heal_operands(&mut healed, &policy)?;
352    let reach = law.reach();
353    let mut result = crate::blend::setback::with_setback_law(law, || {
354        if walk_chain {
355            crate::blend::blend_smooth_chain(&healed, edge_id, reach, true, name)
356        } else if closed {
357            crate::blend::blend_closed_edge(&healed, edge_id, reach, true, name)
358        } else {
359            // An arc of a closed smooth chain (a rim the carriers' seams
360            // split) is chamfered as the whole rim; a lone open edge on its
361            // own.  An open tangent chain is not walked from one of its edges
362            // (`chamfer_edges_asymmetric` takes a whole selected chain).
363            crate::blend::blend_smooth_chain_if_closed(&healed, edge_id, reach, true, name).or_else(|refusal| {
364                let lone = matches!(&refusal.class, RefusalClass::Internal { what } if what == "chain_single_segment");
365                if lone {
366                    crate::blend::blend_open_edge(&healed, edge_id, reach, true, name)
367                } else {
368                    Err(refusal)
369                }
370            })
371        }
372    })?;
373    heal_edge_vertex_gaps(&mut result, reach)?;
374    crate::blend::fit_planar_charts_to_trims(&healed, &mut result)?;
375    crate::blend::same_parameter_trims(&healed, &mut result);
376    let result = settle_cutter_scaffold(result);
377    refuse_invalid_result(&result, entry)?;
378    super::analyze::check_blend_interference(&healed, &result, &[edge_id], "chamfer")?;
379    super::analyze::check_blend_wall_loops(&result, "chamfer")?;
380    Ok(result)
381}
382
383/// Distance-angle chamfer of one STRAIGHT edge between two planar faces
384/// (Golovanov §6.11): setback `d1` along face 1 and angle `angle_rad` between
385/// the chamfer face and face 1.  `d2` is constructed geometrically in the
386/// cross-section plane (see `chamfer_angle_second_distance`), then the
387/// two-distance builder is applied.
388pub fn chamfer_edge_angle(
389    solid: &BrepSolid,
390    edge_id: u64,
391    d1: f64,
392    angle_rad: f64,
393    name: Option<&str>,
394) -> Result<BrepSolid, KernelRefusal> {
395    // One blend operation: the reports of an earlier one, never consumed, are
396    // dropped as it starts (nested calls keep this operation's).
397    let _operation = crate::blend::BlendOperation::enter();
398    if !(d1 > 0.0) || !d1.is_finite() {
399        return Err(KernelRefusal::input(
400            KernelStage::Collect,
401            "setback_d1",
402            "chamfer_edge_angle: setback distance d1 must be positive",
403        ));
404    }
405    let cross = match analyze_edge(solid, edge_id, d1) {
406        Ok(cross) => cross,
407        Err(refusal) if chamfer_asym_curved_on() => {
408            let [first, _] = setback_faces(solid, edge_id).map_err(|_| refusal)?;
409            if !(angle_rad > 1e-9) || !(angle_rad < std::f64::consts::PI) {
410                return Err(KernelRefusal::input(
411                    KernelStage::Collect,
412                    "chamfer_angle",
413                    format!("chamfer_edge_angle: angle {angle_rad} must be positive"),
414                ));
415            }
416            let law = crate::blend::setback::SetbackLaw::Angle { first, distance: d1, angle: angle_rad };
417            return chamfer_by_setback_law(solid, edge_id, law, name, "chamfer_edge_angle", false);
418        }
419        Err(refusal) => return Err(refusal),
420    };
421    let d2 = chamfer_angle_second_distance(&cross, d1, angle_rad)?;
422    let profile = chamfer_cross_section_offsets(&cross, d1, d2)?;
423    apply_chamfer_offsets_profile(solid, &cross, &profile, name, edge_id)
424}
425
426/// Snap small trim/intersection gaps between blend edges and their vertices.
427/// The boolean endpoint welder preserves gaps already inside the validation
428/// band and limits repairs to `max(|radius| * 1e-3, 1e-4)`.
429pub(super) fn heal_edge_vertex_gaps(
430    solid: &mut BrepSolid,
431    radius: f64,
432) -> Result<(), KernelRefusal> {
433    let search = (radius.abs() * 1e-3).max(1e-7);
434    crate::boolean::commit_nearby_edge_endpoints(solid, search)
435}
436
437/// The fillet pipeline's exit acceptance: a solid with a validation ERROR is
438/// refused by name, never returned.
439///
440/// Warnings do not refuse; only the issues `validate()` itself calls errors.
441fn refuse_invalid_result(result: &BrepSolid, entry: &str) -> Result<(), KernelRefusal> {
442    let errors: Vec<_> = result.validate_memoised().into_iter().filter(|issue| issue.severity == "error").collect();
443    let Some(first) = errors.first() else {
444        return Ok(());
445    };
446    Err(KernelRefusal::new(
447        RefusalClass::InvalidResultTopology { issues: errors.len() as u32 },
448        KernelStage::Validate,
449        format!(
450            "{entry}: the blend built a solid that fails validation ({} errors, first: {}); \
451             refused rather than returned",
452            errors.len(),
453            first.message
454        ),
455    ))
456}
457
458/// `BREP_FILLET_PICK_SKIPS_SEAM` (default on; `=0` restores): a pick point that lies as near a
459/// SEAM (an edge one face uses on both sides) as a blendable edge picks the
460/// blendable one.
461///
462/// Cause (brep-bench probe, a ball r 5 bored through by a cylinder r 2, its rim
463/// filleted or chamfered from the point (0, 2, √21), refused "edge 4 borders 1
464/// faces"): the point is the vertex where the rim meets the bore's seam, both
465/// edges read distance 0, and the first found, the seam, was taken. A seam has
466/// one face on both sides and can never be blended, so it loses every tie.
467fn pick_skips_seam_on() -> bool {
468    switch!("BREP_FILLET_PICK_SKIPS_SEAM", true)
469}
470
471/// Whether `edge_id` is a seam: every coedge of it lies on one face.
472fn is_seam(solid: &BrepSolid, edge_id: u64) -> bool {
473    let users = solid
474        .shells
475        .iter()
476        .flat_map(|shell| &shell.faces)
477        .filter(|face| face.loops.iter().flat_map(|loop_record| &loop_record.coedges).any(|coedge| coedge.edge_id == edge_id))
478        .count();
479    users == 1
480}
481
482/// Resolve a point within 1e-3 of a trimmed edge.
483pub fn resolve_edge_by_point(solid: &BrepSolid, point: Vec3) -> Result<u64, KernelRefusal> {
484    let nearest = crate::topology::nearest_edge(solid, point);
485    if pick_skips_seam_on() {
486        if let Some((edge_id, distance)) = nearest {
487            if distance <= 1e-3 && is_seam(solid, edge_id) {
488                let tie = distance + 1e-9 * (1.0 + point.length());
489                let blendable = solid.edges.iter().filter(|edge| edge.id != edge_id && !edge.degenerate).find(|edge| {
490                    crate::project_point_to_curve(&edge.curve, point).ok().is_some_and(|projection| {
491                        let at = projection.u.clamp(edge.t0.min(edge.t1), edge.t0.max(edge.t1));
492                        edge.curve.evaluate(at).is_ok_and(|sample| sample.sub(point).length() <= tie)
493                    }) && !is_seam(solid, edge.id)
494                });
495                if let Some(edge) = blendable {
496                    return Ok(edge.id);
497                }
498            }
499        }
500    }
501    match nearest {
502        Some((edge_id, distance)) if distance <= 1e-3 => Ok(edge_id),
503        Some((_, distance)) => Err(KernelRefusal::input(
504            KernelStage::Collect,
505            "edge_point",
506            format!(
507                "fillet_edges: no edge within tolerance of the point (nearest {distance:.6})"
508            ),
509        )),
510        None => Err(KernelRefusal::input(
511            KernelStage::Collect,
512            "no_edges",
513            "fillet_edges: solid has no edges",
514        )),
515    }
516}
517
518/// Fillet (or chamfer) a GROUP of edges as ONE operation, and — for fillets —
519/// round the convex "star" vertices where three or more of the selected edges
520/// meet (Golovanov §6.9.7).  This is the whole multi-edge fillet in a single
521/// kernel call: the caller passes the object plus one 3D point on each edge,
522/// and the kernel orchestrates the filleting and corner blending against the
523/// full topology (so acute corners resolve coherently instead of being
524/// stitched edge-by-edge by the app).  A corner the kernel cannot round (e.g.
525/// non-orthogonal beyond support, or a general no-common-ball star) is left as
526/// the edge fillets rather than failing the whole group.
527///
528/// When the WHOLE selection cannot be blended as one unit — a shared convex
529/// corner where a revolve axis/pole edge meets the adjacent cap edges can
530/// defeat the sequential corner surgery even though each edge and every proper
531/// SUBSET of the selection blends cleanly (the three fillets converge on the
532/// pole with no single end face across the corner) — a maximal-valid-SUBSET
533/// search blends the largest subset that works, dropping only the edges that
534/// cannot co-blend.  That is a real outcome and [`fillet_edges_reported`]
535/// returns it, WITH the list of edges it could not blend.
536///
537/// This entry point does not.  A solid holding eight of the ten walls that
538/// were asked for is not the answer to the question that was asked, and
539/// returning it as a plain `Ok` reports success for a different result; so an
540/// incomplete selection is an error here, naming every edge that was dropped
541/// and the group refusal behind them.  A caller that genuinely wants the
542/// partial answer asks for it by name.
543///
544/// `edge_names` (when `Some`) is the per-edge blend-FACE name parallel to
545/// `edge_points` — each grown wall is named after ITS originating edge; `None`
546/// names every wall with the single base `name` (the legacy/test behavior,
547/// byte-identical to before). The whole `*_edges` family takes the same
548/// `edge_names` slot in the same position.
549pub fn fillet_edges(
550    solid: &BrepSolid,
551    edge_points: &[Vec3],
552    edge_names: Option<&[String]>,
553    radius: f64,
554    chamfer: bool,
555    name: Option<&str>,
556) -> Result<BrepSolid, KernelRefusal> {
557    // A selected closed rim with a corner at its one vertex, on a mate creased
558    // along its own seam, is blended on the body canonicalised for it — the
559    // mate split along a smooth meridian so the network's miter closes the
560    // crease — and the walls are merged back afterwards
561    // (`blend/creased_rim.rs`). Every other selection takes the body as it
562    // came.
563    let prepared = crate::blend::creased_rim::split_creased_rims(solid, edge_points, edge_names, &resolve_edge_by_point)?;
564    match prepared {
565        Some(prepared) => {
566            let names = prepared.names.as_deref();
567            let built = fillet_edges_prepared(&prepared.solid, &prepared.points, names, radius, chamfer, name)?;
568            Ok(prepared.rejoin(built))
569        }
570        None => {
571            // A chamfer selection holding a MIXED STAR (one concave and two
572            // convex selected edges at a vertex, the convex two on one cap) is
573            // built in two phases (`fillet/chamfer_star.rs`); a phase that
574            // refuses hands the selection to the ordinary path below.
575            if chamfer {
576                let build = |body: &BrepSolid, points: &[Vec3], names: Option<&[String]>| {
577                    fillet_edges_prepared(body, points, names, radius, true, name)
578                };
579                if let Some(built) = super::chamfer_star::chamfer_mixed_stars(solid, edge_points, edge_names, &build) {
580                    return Ok(built);
581                }
582            }
583            let ordinary = fillet_edges_prepared(solid, edge_points, edge_names, radius, chamfer, name);
584            // A closed rim written as a chain of edges along the halves of a
585            // split carrier, refused because only the closed-rim rollover
586            // follows its ball and that lane takes one closed edge, is blended
587            // on the body with those halves merged and the chain joined into one
588            // closed edge (`blend/split_rim.rs`; default on,
589            // `BREP_SPLIT_RIM_MERGE=0` off). Only that refusal asks: a selection
590            // the ordinary path builds keeps its body and names.
591            let answered = match ordinary {
592                Err(refusal)
593                    if crate::blend::split_rim::split_rim_merge_on()
594                        && matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what } if what == super::analyze::TANGENT_ROLLOVER_ONLY_WHAT) =>
595                {
596                    match crate::blend::split_rim::merge_split_rims(solid, edge_points, edge_names, &resolve_edge_by_point) {
597                        // The merged attempt's own reason is appended: the
598                        // first refusal names the lane that is missing, the
599                        // second why the canonical body did not answer either
600                        // (lane F's open item).
601                        Some(merged) => fillet_edges_prepared(&merged.solid, &merged.points, merged.names.as_deref(), radius, chamfer, name)
602                            .map_err(|merged_refusal| {
603                                refusal.with_message(|message| {
604                                    format!("{message} The rim merged into one closed edge refused too: {}", merged_refusal.message)
605                                })
606                            }),
607                        None => Err(refusal),
608                    }
609                }
610                other => other,
611            };
612            // A closed ridge split into two arcs because its walls' seams sit
613            // a hair apart is blended on the body with one wall turned about
614            // the axis onto the other's seam and the arcs joined into one
615            // closed edge (`blend/turned_rim.rs`; default on,
616            // `BREP_FILLET_TURNED_RIM=0` off). Only a refusal asks.
617            let answered = match answered {
618                Err(refusal) if crate::blend::turned_rim::turned_rim_on() => {
619                    match crate::blend::turned_rim::turn_rim_seams_together(solid, edge_points, edge_names, &resolve_edge_by_point) {
620                        Some(turned) => fillet_edges_prepared(&turned.solid, &turned.points, turned.names.as_deref(), radius, chamfer, name)
621                            .map_err(|turned_refusal| {
622                                refusal.with_message(|message| {
623                                    format!("{message} The rim turned into one closed edge refused too: {}", turned_refusal.message)
624                                })
625                            }),
626                        None => Err(refusal),
627                    }
628                }
629                other => other,
630            };
631            // A sheet's edge that runs out at the free boundary has no face
632            // across its end: each such end is closed by a temporary planar
633            // face, the body blended, and the faces removed again
634            // (`blend/sheet_ends.rs`; default on, `BREP_SHEET_FREE_END=0` off).
635            // Only a refused sheet selection asks; the refusal stands unless
636            // the reopened sheet validates.
637            match answered {
638                Err(refusal) if solid.kind == crate::BodyKind::Sheet && crate::blend::sheet_ends::sheet_free_end_on() => {
639                    let edge_ids = edge_points.iter().map(|point| resolve_edge_by_point(solid, *point)).collect::<Result<Vec<_>, _>>();
640                    let Ok(edge_ids) = edge_ids else { return Err(refusal) };
641                    let Some(closed) = crate::blend::sheet_ends::close_free_ends(solid, &edge_ids) else { return Err(refusal) };
642                    let count = crate::blend::sheet_ends::temporary_faces(&closed);
643                    match fillet_edges_prepared(&closed, edge_points, edge_names, radius, chamfer, name) {
644                        Ok(built) => crate::blend::sheet_ends::open_free_ends(built, count).ok_or(refusal),
645                        Err(closed_refusal) => Err(refusal.with_message(|message| {
646                            format!("{message} The sheet with its free ends closed refused too: {}", closed_refusal.message)
647                        })),
648                    }
649                }
650                other => other,
651            }
652        }
653    }
654}
655
656fn fillet_edges_prepared(
657    solid: &BrepSolid,
658    edge_points: &[Vec3],
659    edge_names: Option<&[String]>,
660    radius: f64,
661    chamfer: bool,
662    name: Option<&str>,
663) -> Result<BrepSolid, KernelRefusal> {
664    // One blend operation: the reports of an earlier one, never consumed, are
665    // dropped as it starts (nested calls keep this operation's).
666    let _operation = crate::blend::BlendOperation::enter();
667    // Each operation pays for the first read of every body it validates
668    // (`BrepSolid::validate_memoised`, lane R1 row 3).
669    BrepSolid::clear_validate_memo();
670    // One coedge-check memo per operation, as a boolean opens one (lane R1
671    // row 3b): the surgery's, the group lane's
672    // and the exit's validations re-read the coedges the rims left unchanged.
673    let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
674    let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
675    // The search is capped at one dropped edge here (lane F row 3);
676    // `BREP_SUBSET_SEARCH_FULL=1` restores the full search.
677    let cap = std::env::var_os("BREP_SUBSET_SEARCH_FULL").is_none().then_some(1);
678    let _cap = SubsetDropCap::set(cap);
679    let (result, selection) = match fillet_edges_reported(solid, edge_points, edge_names, radius, chamfer, name) {
680        // A wall that folds is relieved where it folds, not refused
681        // (`blend/relief.rs`).
682        Err(fold) if !chamfer && crate::blend::is_wall_fold(&fold) && crate::blend::relief::radius_relief_on() => {
683            let misfit = crate::blend::relief::is_misfit_fold(&fold);
684            let relieved = relieve_fold(solid, edge_points, edge_names, radius, name, fold);
685            // A misfit (a lane's refusal read as the ball not fitting) took
686            // the group off the ladder that follows the network; when no
687            // relief builds, that ladder answers, as it did before the relief.
688            if relieved.is_err() && misfit {
689                let _off = crate::blend::relief::MisfitOff::enter();
690                return fillet_edges(solid, edge_points, edge_names, radius, chamfer, name);
691            }
692            return relieved;
693        }
694        reported => reported?,
695    };
696    if selection.is_complete() {
697        return Ok(result);
698    }
699    // Every dropped edge BY NAME: the caller's own per-edge name when it gave
700    // one, and always its index and the point it was selected by.
701    let dropped: Vec<String> = selection
702        .rejected
703        .iter()
704        .map(|index| {
705            let point = edge_points[*index];
706            let named = edge_names
707                .and_then(|names| names.get(*index))
708                .map(|name| format!("`{name}` "))
709                .unwrap_or_default();
710            format!(
711                "{named}#{index} at ({:.6}, {:.6}, {:.6})",
712                point.x, point.y, point.z
713            )
714        })
715        .collect();
716    // The selection, as specified, has no single answer the kernel will
717    // stand behind: the group refusal behind the drop travels as TEXT in
718    // `BlendSelection::reason`, so this refusal carries its own class.
719    Err(KernelRefusal::ill_posed(
720        KernelStage::Select,
721        "incomplete_selection",
722        format!(
723            "{entry}: {} of the {} selected edges were blended — {} could not co-blend with the \
724             rest of the selection and carry no wall in the result ({}). The group refusal was: \
725             {}. Blend them separately, or call the reported entry point to accept the partial \
726             selection deliberately.",
727            selection.applied.len(),
728            selection.requested,
729            selection.rejected.len(),
730            dropped.join(", "),
731            selection
732                .reason
733                .as_deref()
734                .unwrap_or("the whole group built but not every edge grew a wall"),
735        ),
736    ))
737}
738
739/// The fillet a constant `radius` would fold: rebuilt with the radius reduced
740/// only where it does not fit (`blend/relief.rs`), and a note saying where
741/// and to what. Selected edges joined (through shared vertices) to no relief
742/// zone are built at the constant radius first; each relieved group is then
743/// built by the taper network on that body. A relief that still folds is
744/// planned again with a wider margin; when none builds, the fold stands with
745/// the last relief's reason appended.
746fn relieve_fold(
747    solid: &BrepSolid,
748    edge_points: &[Vec3],
749    edge_names: Option<&[String]>,
750    radius: f64,
751    name: Option<&str>,
752    fold: KernelRefusal,
753) -> Result<BrepSolid, KernelRefusal> {
754    let _relieving = crate::blend::relief::Relieving::enter();
755    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
756    let selected: Vec<u64> = edge_points.iter().map(|point| resolve_edge_by_point(solid, *point)).collect::<Result<_, _>>()?;
757    // One edge per carrier continued (`relief::join_continuations`): the
758    // selection is read again on the joined body, two points on one joined
759    // edge selecting it once.
760    let joined = crate::blend::relief::join_continuations(solid, &selected);
761    let solid = joined.as_ref().unwrap_or(solid);
762    let mut ids: Vec<u64> = Vec::with_capacity(edge_points.len());
763    let mut points: Vec<Vec3> = Vec::with_capacity(edge_points.len());
764    let mut names: Vec<String> = Vec::with_capacity(edge_points.len());
765    for (index, point) in edge_points.iter().enumerate() {
766        let id = resolve_edge_by_point(solid, *point)?;
767        if !ids.contains(&id) {
768            ids.push(id);
769            points.push(*point);
770            if let Some(name) = edge_names.and_then(|names| names.get(index)) {
771                names.push(name.clone());
772            }
773        }
774    }
775    let (edge_points, edge_names) = (&points[..], edge_names.map(|_| &names[..]));
776    if debug && joined.is_some() {
777        eprintln!("radius relief: joined continuation edges, {} selected edges become {}", selected.len(), ids.len());
778    }
779    let started = web_time::Instant::now();
780    let measured = match crate::blend::relief::measure_ceilings(solid, &ids, radius) {
781        Ok(measured) => measured,
782        Err(refusal) => return Err(fold.with_message(|message| format!("{message}; the relief could not measure the edges: {refusal}"))),
783    };
784    if debug {
785        eprintln!("radius relief: ceilings measured in {:.1} ms", started.elapsed().as_secs_f64() * 1e3);
786    }
787    // A relief is LOCAL: the requested radius stands where it fits. Where it
788    // fits nowhere on the selection (a ball wider than a rod's rim, the whole
789    // rim short alike) a radius lowered everywhere is a different request,
790    // and the fold stands, naming the largest ball that does fit.
791    let largest = measured.iter().flatten().map(|(_, ceiling)| *ceiling).fold(0.0_f64, f64::max);
792    if largest < radius {
793        return Err(fold.with_message(|message| {
794            format!("{message}; r {radius} fits nowhere along the selection, so it is not reduced locally: the largest ball that fits anywhere on it is {largest:.6}")
795        }));
796    }
797    let mut last: Option<KernelRefusal> = None;
798    for attempt in 0..crate::blend::relief::ATTEMPTS {
799        let plan = match crate::blend::relief::plan_relief(solid, &ids, radius, &measured, attempt) {
800            Ok(Some(plan)) => plan,
801            // The ball fits everywhere the probe reads: the fold is not one
802            // a smaller radius answers.
803            Ok(None) => break,
804            Err(refusal) => {
805                last = Some(refusal);
806                break;
807            }
808        };
809        let mark = crate::blend::blend_notes_mark();
810        match build_relief_plan(solid, edge_points, edge_names, &ids, radius, name, &plan) {
811            Ok(body) => {
812                for zone in &plan.zones {
813                    let near: Vec<String> = zone
814                        .edges
815                        .iter()
816                        .filter_map(|index| solid.edges.iter().find(|edge| edge.id == ids[*index]))
817                        .map(|edge| edge.name.clone().unwrap_or_else(|| format!("edge #{}", edge.id)))
818                        .map(|label| format!("`{label}`"))
819                        .collect();
820                    // The note states what was built: where the law never
821                    // climbs back to the requested radius on the zone's edges
822                    // (the sculpted-cap report's rim, 1.08 to 1.78 against r 2.2), it
823                    // says so instead of "locally".
824                    let (low, high) = zone
825                        .edges
826                        .iter()
827                        .flat_map(|index| plan.stops[*index].iter().map(|(_, r)| *r))
828                        .fold((f64::INFINITY, 0.0_f64), |(low, high), r| (low.min(r), high.max(r)));
829                    let note = if high < radius * (1.0 - 1e-9) {
830                        format!(
831                            "radius reduced over the whole of {}: {low:.2} to {high:.2}, so r {radius} is reached nowhere \
832                             on them (where they turn tightest the largest ball that fits is {:.2})",
833                            near.join(", "),
834                            zone.ceiling,
835                        )
836                    } else {
837                        format!(
838                            "radius reduced to {:.2} locally near {}: r {radius} does not fit there (the largest ball that does is {:.2})",
839                            zone.radius,
840                            near.join(", "),
841                            zone.ceiling,
842                        )
843                    };
844                    crate::blend::record_blend_note(note);
845                }
846                return Ok(body);
847            }
848            Err(refusal) => {
849                crate::blend::blend_notes_truncate(mark);
850                if debug {
851                    eprintln!("radius relief attempt {attempt} refused at {:.1} ms: {refusal}", started.elapsed().as_secs_f64() * 1e3);
852                }
853                last = Some(refusal);
854            }
855        }
856    }
857    Err(match last {
858        Some(last) => fold.with_message(|message| format!("{message}; a locally reduced radius did not build either: {last}")),
859        None => fold,
860    })
861}
862
863/// Build one relief plan (see [`relieve_fold`]).
864fn build_relief_plan(
865    solid: &BrepSolid,
866    edge_points: &[Vec3],
867    edge_names: Option<&[String]>,
868    ids: &[u64],
869    radius: f64,
870    name: Option<&str>,
871    plan: &crate::blend::relief::ReliefPlan,
872) -> Result<BrepSolid, KernelRefusal> {
873    // Groups of selected edges joined through shared vertices.
874    let count = ids.len();
875    let mut group: Vec<usize> = (0..count).collect();
876    let find = |group: &mut Vec<usize>, mut index: usize| {
877        while group[index] != index {
878            group[index] = group[group[index]];
879            index = group[index];
880        }
881        index
882    };
883    let vertices: Vec<[u64; 2]> = ids
884        .iter()
885        .map(|id| {
886            solid.edges.iter().find(|edge| edge.id == *id).map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).unwrap_or([u64::MAX; 2])
887        })
888        .collect();
889    for a in 0..count {
890        for b in a + 1..count {
891            if vertices[a].iter().any(|vertex| *vertex != u64::MAX && vertices[b].contains(vertex)) {
892                let (root_a, root_b) = (find(&mut group, a), find(&mut group, b));
893                group[root_a] = root_b;
894            }
895        }
896    }
897    let reduced: Vec<bool> = plan.stops.iter().map(|stops| stops.iter().any(|(_, r)| *r < radius)).collect();
898    let relieved_group: Vec<bool> = (0..count)
899        .map(|index| {
900            let root = find(&mut group, index);
901            (0..count).any(|other| reduced[other] && find(&mut group, other) == root)
902        })
903        .collect();
904    let pick = |want: bool| -> (Vec<Vec3>, Option<Vec<String>>, Vec<Vec<(f64, f64)>>) {
905        let indices: Vec<usize> = (0..count).filter(|index| relieved_group[*index] == want).collect();
906        (
907            indices.iter().map(|index| edge_points[*index]).collect(),
908            edge_names.map(|names| indices.iter().filter_map(|index| names.get(*index).cloned()).collect()),
909            indices.iter().map(|index| plan.stops[*index].clone()).collect(),
910        )
911    };
912    let (constant_points, constant_names, _) = pick(false);
913    let (relieved_points, relieved_names, relieved_stops) = pick(true);
914    let mut body = solid.clone();
915    if !constant_points.is_empty() {
916        body = fillet_edges(&body, &constant_points, constant_names.as_deref(), radius, false, name)?;
917    }
918    let built = fillet_edges_variable_impl(
919        &body,
920        &relieved_points,
921        relieved_names.as_deref(),
922        &relieved_stops,
923        false,
924        name,
925        "fillet_edges",
926        false,
927    )?;
928    let issues = built.validate();
929    if !issues.is_empty() {
930        return Err(KernelRefusal::internal(
931            KernelStage::Validate,
932            "relief_validate",
933            format!("radius relief: the relieved fillet does not validate: {issues:?}"),
934        ));
935    }
936    Ok(built)
937}
938
939/// What a blend selection actually achieved.
940///
941/// The kernel can answer a group blend with fewer walls than were asked for —
942/// the maximal-valid-subset search drops the edges that cannot co-blend at a
943/// shared corner rather than failing outright. This says WHICH, so partial
944/// fulfilment is a statement instead of a silence.
945#[derive(Clone, Debug)]
946pub struct BlendSelection {
947    /// How many edges the caller selected.
948    pub requested: usize,
949    /// Indices into that selection that carry a blend wall in the result.
950    pub applied: Vec<usize>,
951    /// Indices that do not.
952    pub rejected: Vec<usize>,
953    /// Why the whole selection could not be built, when something was dropped.
954    pub reason: Option<String>,
955}
956
957impl BlendSelection {
958    /// Every requested edge carries a wall.
959    pub fn is_complete(&self) -> bool {
960        self.rejected.is_empty()
961    }
962}
963
964/// [`fillet_edges`] with the selection outcome reported rather than refused.
965///
966/// The result is the same solid `fillet_edges` would build; the difference is
967/// that an incomplete selection comes back as `Ok` with the misses named,
968/// which is the explicit partial-result contract. Every named refusal that
969/// applies to the WHOLE selection — mixed concavity, a radius the local wall
970/// cannot hold, a mixed-convexity corner — is still an `Err`: dropping edges
971/// cannot rescue those, so a partial answer would be a different defect.
972/// [`fillet_edges_reported`] with the solid and the edge points translated by
973/// `offset` for the operation and the result translated back. Refusal
974/// messages name the translated coordinates.
975pub fn fillet_edges_reported_at_offset(
976    solid: &BrepSolid,
977    edge_points: &[Vec3],
978    edge_names: Option<&[String]>,
979    radius: f64,
980    chamfer: bool,
981    name: Option<&str>,
982    offset: Vec3,
983) -> Result<(BrepSolid, BlendSelection), KernelRefusal> {
984    fillet_translated(solid, edge_points, edge_names, radius, chamfer, name, offset, crate::recentre::EntryKind::Control)
985}
986
987/// The translated run behind the control and the guard.
988#[allow(clippy::too_many_arguments)]
989fn fillet_translated(
990    solid: &BrepSolid,
991    edge_points: &[Vec3],
992    edge_names: Option<&[String]>,
993    radius: f64,
994    chamfer: bool,
995    name: Option<&str>,
996    offset: Vec3,
997    kind: crate::recentre::EntryKind,
998) -> Result<(BrepSolid, BlendSelection), KernelRefusal> {
999    let _entry = crate::recentre::TranslatedEntry::open(kind);
1000    let translate = |solid: &BrepSolid, offset: Vec3| {
1001        crate::recentre::translate_solid(solid, offset).map_err(|message| {
1002            KernelRefusal::internal(
1003                KernelStage::Collect,
1004                "translation_control",
1005                format!("fillet_edges: the translation control could not move the solid: {message}"),
1006            )
1007        })
1008    };
1009    let moved = translate(solid, offset)?;
1010    let points: Vec<Vec3> = edge_points.iter().map(|point| point.add(offset)).collect();
1011    let (result, selection) = fillet_edges_reported(&moved, &points, edge_names, radius, chamfer, name)?;
1012    Ok((translate(&result, offset.scale(-1.0))?, selection))
1013}
1014
1015pub fn fillet_edges_reported(
1016    solid: &BrepSolid,
1017    edge_points: &[Vec3],
1018    edge_names: Option<&[String]>,
1019    radius: f64,
1020    chamfer: bool,
1021    name: Option<&str>,
1022) -> Result<(BrepSolid, BlendSelection), KernelRefusal> {
1023    // `BREP_BLEND_SAME_PARAMETER`: the operation's iso-line trims take their
1024    // edges' parameter, read against the solid the operation started from so
1025    // every face it made counts as touched (corner sectors and patches close
1026    // after the per-edge lanes, past their own post-passes). No-op off.
1027    let (mut result, selection) = fillet_edges_reported_inner(solid, edge_points, edge_names, radius, chamfer, name)?;
1028    crate::blend::same_parameter_trims(solid, &mut result);
1029    Ok((result, selection))
1030}
1031
1032fn fillet_edges_reported_inner(
1033    solid: &BrepSolid,
1034    edge_points: &[Vec3],
1035    edge_names: Option<&[String]>,
1036    radius: f64,
1037    chamfer: bool,
1038    name: Option<&str>,
1039) -> Result<(BrepSolid, BlendSelection), KernelRefusal> {
1040    // The translation control (`BREP_TRANSLATION_CONTROL`, `brep/recentre.rs`):
1041    // the outermost entry runs the fillet on a translated solid.
1042    if let Some(offset) = crate::recentre::control_offset_at_entry() {
1043        return fillet_edges_reported_at_offset(solid, edge_points, edge_names, radius, chamfer, name, offset);
1044    }
1045    // The recentre guard: a solid far from the origin in its own units
1046    // is filleted at the origin.
1047    let bounds = crate::recentre::solid_bounds(solid);
1048    if let Some(offset) = crate::recentre::guard_offset(bounds) {
1049        crate::recentre::profile_fired("fillet", offset, bounds);
1050        return fillet_translated(solid, edge_points, edge_names, radius, chamfer, name, offset, crate::recentre::EntryKind::Guard);
1051    }
1052    // One blend operation: the reports of an earlier one, never consumed, are
1053    // dropped as it starts (nested calls keep this operation's).
1054    let _operation = crate::blend::BlendOperation::enter();
1055    // Dropped before `_operation`, so the total is on the ledger when the
1056    // outermost operation prints it.
1057    let _total = crate::blend::BlendTimer::start("timing.total_ms");
1058    if !(radius > 0.0) || !radius.is_finite() {
1059        return Err(KernelRefusal::input(
1060            KernelStage::Collect,
1061            "radius",
1062            "fillet_edges: radius must be positive",
1063        ));
1064    }
1065    if edge_points.is_empty() {
1066        return Err(KernelRefusal::input(
1067            KernelStage::Collect,
1068            "selection",
1069            "fillet_edges: no edges selected",
1070        ));
1071    }
1072    // The rolling ball must reach both supports of every SELECTED edge — see
1073    // `check_support_extent`.  Checked ONCE, here, against the solid the
1074    // selection was made on: inside the group build the faces have already
1075    // been eaten into by earlier blends of the same selection, and a fillet
1076    // legitimately runs off that remainder (two rounds pinching on a shared
1077    // face).  Dropping edges cannot rescue an oversized radius either, so
1078    // this runs before the subset search rather than inside it.
1079    let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
1080    let mut selected_ids = Vec::with_capacity(edge_points.len());
1081    if crate::blend::blend_operation_outermost() {
1082        super::analyze::clear_rollover_only();
1083    }
1084    let selection_checks = crate::blend::BlendTimer::start("timing.selection_checks_ms");
1085    let _boundaries = super::analyze::SupportBoundaryScope::open();
1086    for point in edge_points {
1087        let resolve = crate::blend::BlendTimer::start("timing.selection_checks.resolve_ms");
1088        let edge_id = resolve_edge_by_point(solid, *point)?;
1089        resolve.stop();
1090        let concavity = crate::blend::BlendTimer::start("timing.selection_checks.concavity_ms");
1091        check_mixed_concavity(solid, edge_id, entry)?;
1092        concavity.stop();
1093        let _extent = crate::blend::BlendTimer::start("timing.selection_checks.extent_ms");
1094        // A lone fillet edge may take the clipped concave fill (lane F row 5).
1095        if edge_points.len() == 1 && !chamfer {
1096            check_support_extent_clipping(solid, edge_id, radius, entry)?;
1097        } else {
1098            check_support_extent(solid, edge_id, radius, entry)?;
1099        }
1100        selected_ids.push(edge_id);
1101    }
1102    drop(_boundaries);
1103    selection_checks.stop();
1104    // A corner where the selection mixes convexity — a convex edge dying into
1105    // the concave edges it meets — has no rolling-ball closure at all: the
1106    // blends run out against each other partway along, which is the vertex
1107    // blend the stripe network does not construct yet.  It is TERMINAL, and
1108    // for the same reason as the two checks above it runs once, here: neither
1109    // the cutter composition nor the subset search below can rescue it.  The
1110    // cutter "succeeds" on this shape by shredding the solid (a sliver end cap
1111    // per corner, the carrier face split and renamed), which is worse than
1112    // the named refusal — see the 2026-09-09 rib-spine report.
1113    //
1114    // Nor can PARTITIONING the selection at the corner rescue it, which is why
1115    // this is still a refusal and not a split (measured 2026-09-13, the
1116    // partition record): the two convexity-pure halves each build on the
1117    // network, and composing them walls every selected edge and leaves every
1118    // other face's area identical to twelve digits — but the convex wall comes
1119    // out as the full untrimmed quarter-round prism (2·(1 − π/4)·r²·L to
1120    // 2.2e-10, with NO rolled-corner term) because its contact rail runs off
1121    // its own face at the TRI-TANGENT STATION and the surgery splices the
1122    // overhang in rather than clipping it. The faces it runs along come back
1123    // with self-crossing loops that `validate()`, `solid_self_intersections`,
1124    // the connectivity report and the Euler check all pass — and that
1125    // `check_loop_self_crossings` REFUSES, so the split is not a route to ten
1126    // walls either: blend the concave half first and the acceptance refuses
1127    // every convex edge whose wall runs out into it — on the rib both spines,
1128    // at that same station, so that feature fails outright; blend the convex
1129    // half first and the maximal-valid-subset search drops one ring edge and
1130    // returns NINE walls of ten. The construction that is missing is the
1131    // runout itself: past that station the ball rolls on one input face and on
1132    // the concave stripe's own surface, so the march needs a STRIPE as its
1133    // second carrier.
1134    //
1135    // And more than that, measured 2026-09-13 (`blend/runout.rs`, which this
1136    // refusal now reports): the KEPT mate runs out too, at the mirror-image
1137    // station, so the FIRST carrier becomes the other concave stripe and the
1138    // last stretch rolls on two stripes; that stretch ends in a POLE where the
1139    // two stripes' rails on the face they share meet and the section shrinks
1140    // to a point. Two carrier switches and a degenerate terminus, not a march
1141    // with a stop.
1142    // A convex spine dying into two concave edges on a CURVED floor is built
1143    // spine first, then the rest with the spine's foot on the floor added to
1144    // the concave chain (`spine_first.rs`); taken by the selection's shape
1145    // alone, and declined to the lanes below when a stage does not build.
1146    // Here only where the corner analysis below sees no mixed corner (a
1147    // closed edge in the selection, such as the cylinder's rim, blinds it):
1148    // where it sees them, the rounded-boss and runout compositions go first
1149    // (they build the 2026-10-12 sprocket's spine over its cylindrical rim),
1150    // and spine-first is tried again only when every one of them declines.
1151    // Blind, no composition below closes a planar floor's corner either (a
1152    // block's edge dying through a cylinder's flat cap), so spine-first takes
1153    // planar floors here too.
1154    if !chamfer && crate::blend::mixed_convexity_corners(solid, &selected_ids, radius).is_empty() {
1155        if let Some(built) = super::spine_first::spine_first_composition(
1156            solid, &selected_ids, edge_points, edge_names, radius, name, true,
1157        ) {
1158            return Ok(built);
1159        }
1160    }
1161    if !chamfer {
1162        // The class is BUILT where the runout composition applies — the ring
1163        // first, then one wall per spine from pole to pole (`blend/runout.rs`,
1164        // the 2026-09-30 record §5) — and refused by name, with the
1165        // composition's own reason appended, where it does not.
1166        let corner_analysis = crate::blend::BlendTimer::start("timing.corner_analysis_ms");
1167        let mut corners = crate::blend::mixed_convexity_corners(solid, &selected_ids, radius);
1168        corners.extend(crate::blend::runout::one_ended_runout_corners(solid, &selected_ids, radius));
1169        corner_analysis.stop();
1170        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1171            for corner in &corners {
1172                eprintln!(
1173                    "mixed corner at vertex {} ({:.4}, {:.4}, {:.4}): convex {:?} concave {:?}",
1174                    corner.vertex, corner.point.x, corner.point.y, corner.point.z,
1175                    corner.convex.iter().map(|index| selected_ids[*index]).collect::<Vec<_>>(),
1176                    corner.concave.iter().map(|index| selected_ids[*index]).collect::<Vec<_>>()
1177                );
1178            }
1179        }
1180        if !corners.is_empty() {
1181            // BREP lane L: begin walls_missing_tie_all_stations_20261015
1182            // Cleared on entry: only THIS composition's runout may set it.
1183            RUNOUT_RING_IS_NETWORK.with(|flag| flag.set(false));
1184            // BREP lane L: end walls_missing_tie_all_stations_20261015
1185            let composed = rounded_boss_composition(
1186                solid, &selected_ids, edge_points, edge_names, radius, name, &corners,
1187            ).or_else(|error| {
1188                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1189                    eprintln!("rounded boss composition refused: {error}");
1190                }
1191                runout_composition(
1192                    solid, &selected_ids, edge_points, edge_names, radius, name, &corners, entry,
1193                )
1194            }).or_else(|error| {
1195                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1196                    eprintln!("runout composition refused: {error}");
1197                }
1198                // The open-pad composition (2026-10-17 face-ring report): one
1199                // convex and one concave edge at each mixed corner over a
1200                // planar face, the concave pads continued onto the convex
1201                // walls. Declines by name on any other corner shape, so the
1202                // runout's refusal stands where it stood.
1203                open_pad_composition(
1204                    solid, &selected_ids, edge_points, edge_names, radius, name, &corners, entry,
1205                ).map_err(|pad_error| {
1206                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1207                        eprintln!("open-pad composition refused: {pad_error}");
1208                    }
1209                    // The decline is carried in the refusal's CLASS (`what`),
1210                    // never in its text: 2026-10-18 the text test let the
1211                    // decline replace the runout's named refusal on the
1212                    // nine-pick wedge (three lib tests).
1213                    let declined = matches!(&pad_error.class, crate::RefusalClass::UnsupportedGeometry { what } if what == "open_pad_shape");
1214                    if declined { error } else { pad_error }
1215                })
1216            }).or_else(|error| {
1217                // The cusp composition (the straight-sliver and cusp-chain reports): every
1218                // mixed corner a CUSP, the convex and concave edges leaving it
1219                // tangent. Declines by class on any other corner, and every
1220                // other refusal keeps the one before it: it is the last try.
1221                cusp_composition(solid, &selected_ids, edge_points, edge_names, radius, name, &corners).map_err(|cusp_error| {
1222                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1223                        eprintln!("cusp composition refused: {cusp_error}");
1224                    }
1225                    error
1226                })
1227            });
1228            match composed {
1229                Ok(result) => {
1230                    // BREP lane L: begin walls_missing_tie_all_stations_20261015
1231                    // The runout composition's walls are built and checked by
1232                    // construction; a station its OWN neighbouring wall consumes
1233                    // (a runout trimmed at an edge's end) is not a missing wall.
1234                    // Only on the NETWORK's ring: there every concave edge has its
1235                    // own wall by construction and a runout trims at most its
1236                    // ends; a ring the cutter fallback built keeps the strict
1237                    // first-station rule (the rounded boss path too).
1238                    let network_ring = RUNOUT_RING_IS_NETWORK.with(|flag| flag.replace(false));
1239                    // Integrator merge 2026-10-16 (lanes F + L): the flag above is consumed
1240                    // BEFORE lane F's exit acceptance can return early, so a refused result
1241                    // never leaves it set for the next call on this thread.
1242                    refuse_invalid_result(&result, entry)?;
1243                    let missing = walls_missing_ties(
1244                        solid, &result, edge_points, &(0..edge_points.len()).collect::<Vec<_>>(), radius, chamfer, entry, network_ring,
1245                    )?;
1246                    // BREP lane L: end walls_missing_tie_all_stations_20261015
1247                    if !missing.is_empty() {
1248                        return Err(KernelRefusal::internal(
1249                            KernelStage::Validate,
1250                            "runout_walls_missing",
1251                            format!(
1252                                "{entry}: the composition built a solid with no wall on {}",
1253                                missing.iter().map(|index| selection_label(*index, edge_points, edge_names, name)).collect::<Vec<_>>().join(", ")
1254                            ),
1255                        ));
1256                    }
1257                    let n = edge_points.len();
1258                    return Ok((
1259                        result,
1260                        BlendSelection { requested: n, applied: (0..n).collect(), rejected: Vec::new(), reason: None },
1261                    ));
1262                }
1263                Err(error) => {
1264                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1265                        eprintln!("runout composition refused: {error}");
1266                    }
1267                    // Where the corner analysis sees the corners but no
1268                    // composition above closes them, a spine dying into a
1269                    // curved floor still builds spine first: the spine's
1270                    // round turns its corner into a smooth concave chain, so
1271                    // the corner is no longer mixed once the spine is built
1272                    // (a block's top edges into a cylinder with that
1273                    // cylinder's bottom rim picked and its top rim not).
1274                    if let Some(built) = super::spine_first::spine_first_composition(
1275                        solid, &selected_ids, edge_points, edge_names, radius, name, false,
1276                    ) {
1277                        return Ok(built);
1278                    }
1279                    check_mixed_corner_convexity(
1280                        solid, &selected_ids, edge_points, edge_names, radius, name, Some(&error),
1281                    )?;
1282                }
1283            }
1284        }
1285        // A selection whose corner setbacks consume a whole edge — the exact
1286        // degenerate radius, every face shrunk to a point — has no strip for
1287        // the network to build and nothing the cutter or the subset search
1288        // can rescue (the search answered the r = 10 cube with nine walls and
1289        // a 5174 volume against the sphere's 4189).  Terminal, by name, here.
1290        let corner_analysis = crate::blend::BlendTimer::start("timing.corner_analysis_ms");
1291        check_degenerate_corner_setbacks(
1292            solid,
1293            &selected_ids,
1294            edge_points,
1295            edge_names,
1296            radius,
1297            name,
1298        )?;
1299        corner_analysis.stop();
1300    }
1301
1302    let n = edge_points.len();
1303    let complete = |applied: Vec<usize>| BlendSelection {
1304        requested: n,
1305        applied,
1306        rejected: Vec::new(),
1307        reason: None,
1308    };
1309    // Every subset below is built against the SAME solid, and a selection of
1310    // several components is composed one component at a time in input order,
1311    // so two subsets that keep the same leading components rebuild the same
1312    // intermediate solids. The memo keeps each component's result under the
1313    // chain of components composed before it, which is everything that result
1314    // depends on here (the solid, radius, chamfer and name are fixed for the
1315    // call), so the search returns what it did without the memo, only without
1316    // the rebuilding. On the 2026-09-26 cross-drilled sphere report four bored
1317    // rims were re-blended ahead of the same failing component in each of the
1318    // (up to 372) subsets tried: 13 min 25 s for one refusal, 34 s with it.
1319    let mut memo = ComponentMemo::default();
1320    let profile = crate::profile::profile_enabled();
1321    let group_started = web_time::Instant::now();
1322    let group = fillet_edges_group_in(
1323        solid,
1324        edge_points,
1325        edge_names,
1326        radius,
1327        chamfer,
1328        name,
1329        Some(&mut memo),
1330    );
1331    if profile {
1332        profile_line!(
1333            "blend.selection group edges={n} ok={} ms={:.3}",
1334            group.is_ok(),
1335            group_started.elapsed().as_secs_f64() * 1e3
1336        );
1337    }
1338    let group_err = match group {
1339        // A group solid that fails `validate()` is never returned: it becomes
1340        // the group's refusal, so the subset search below (which validates
1341        // every subset it builds) still gets its turn, and a selection with
1342        // nothing to drop refuses by that name.
1343        Ok(result) if refuse_invalid_result(&result, entry).is_err() => {
1344            refuse_invalid_result(&result, entry).unwrap_err()
1345        }
1346        Ok(result) => {
1347            // The group returned a solid, which is NOT the same as the group
1348            // having blended every edge.  `validate()` cannot tell the
1349            // difference — it checks incidence, and a solid missing a wall is
1350            // perfectly incident — so the walls are COUNTED.
1351            let missing =
1352                walls_missing(solid, &result, edge_points, &(0..n).collect::<Vec<_>>(), radius, chamfer, entry)?;
1353            if missing.is_empty() {
1354                return Ok((result, complete((0..n).collect())));
1355            }
1356            let applied: Vec<usize> = (0..n).filter(|index| !missing.contains(index)).collect();
1357            return Ok((
1358                result,
1359                BlendSelection {
1360                    requested: n,
1361                    applied,
1362                    rejected: missing,
1363                    reason: None,
1364                },
1365            ));
1366        }
1367        Err(error) => error,
1368    };
1369    // A wall that FOLDS THROUGH ITSELF is terminal for the whole selection, and
1370    // for the reason the two checks above are: dropping edges cannot rescue it.
1371    // The subset search would happily answer this document's two collars with
1372    // the ONE that does not fold, and return a solid whose volume is a blend
1373    // short — the same silent partial `both_collars_add_independently` exists
1374    // to catch.  Reported by name instead (`blend/fold.rs`).
1375    // A miter past the sharp edge's far vertex needs support-face switching,
1376    // not a smaller selection. Do not let the subset search mask the limit.
1377    // Nor can dropping another edge close a tangential end whose taper failed.
1378    if crate::blend::is_wall_fold(&group_err) || crate::blend::is_miter_support_overrun(&group_err)
1379        || crate::blend::is_tangential_transverse_end(&group_err)
1380        || matches!(&group_err.class, RefusalClass::UnsupportedGeometry { what } if what == "canal_footprint_bound")
1381        || crate::blend::is_ball_does_not_fit(&group_err)
1382    {
1383        return Err(group_err);
1384    }
1385    // Fewer than two edges: nothing to drop, so the group error is final.
1386    // Cap the combinatorial search so a large malformed selection cannot
1387    // explode (the full group carries the common case; the search is a
1388    // rare fallback).
1389    if n < 2 || n > 12 {
1390        return Err(group_err);
1391    }
1392    // Drop the fewest edges first (largest surviving subset), trying the
1393    // drop-sets in lexicographic order so the result is deterministic.
1394    // Take the first subset that blends to a valid solid IN WHICH EVERY KEPT
1395    // EDGE GREW A WALL: a subset that itself silently drops one of its own
1396    // edges is not the maximal subset, it is a smaller one wearing a larger
1397    // one's label.
1398    let max_drop = SUBSET_DROP_CAP.with(|cap| cap.get()).map_or(n - 1, |cap| cap.min(n - 1));
1399    for drop in 1..=max_drop {
1400        for dropped in index_combinations(n, drop) {
1401            let keep: Vec<usize> = (0..n).filter(|i| !dropped.contains(i)).collect();
1402            let points: Vec<Vec3> = keep.iter().map(|i| edge_points[*i]).collect();
1403            // Subset the per-edge blend-face names with the IDENTICAL
1404            // drop-set so `kept_names[k]` still names `kept[k]`.
1405            let kept_names: Option<Vec<String>> =
1406                edge_names.map(|names| keep.iter().map(|i| names[*i].clone()).collect());
1407            crate::blend::record_count("count.subset.builds", 1);
1408            let subset_started = web_time::Instant::now();
1409            let subset = fillet_edges_group_in(
1410                solid,
1411                &points,
1412                kept_names.as_deref(),
1413                radius,
1414                chamfer,
1415                name,
1416                Some(&mut memo),
1417            );
1418            if profile {
1419                profile_line!(
1420                    "blend.selection subset dropped={dropped:?} ok={} ms={:.3}",
1421                    subset.is_ok(),
1422                    subset_started.elapsed().as_secs_f64() * 1e3
1423                );
1424            }
1425            let result = match subset {
1426                Ok(result) => result,
1427                Err(error) => {
1428                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1429                        eprintln!("subset dropped={dropped:?} refused: {error}");
1430                    }
1431                    continue;
1432                }
1433            };
1434            if !result.validate().is_empty() {
1435                continue;
1436            }
1437            if !walls_missing(solid, &result, edge_points, &keep, radius, chamfer, entry)?.is_empty() {
1438                continue;
1439            }
1440            return Ok((
1441                result,
1442                BlendSelection {
1443                    requested: n,
1444                    applied: keep,
1445                    rejected: dropped,
1446                    reason: Some(group_err.message),
1447                },
1448            ));
1449        }
1450    }
1451    Err(group_err)
1452}
1453
1454
1455/// Which of `selected` (indices into the caller's own selection) carry NO blend
1456/// wall in `result` — decided by the MATERIAL, not by a name.
1457///
1458/// A blended edge is an edge whose material changed: a convex blend removes
1459/// the sliver under the edge, so a point of the original edge ends up OUTSIDE
1460/// the answer; a concave one pads the crease, so it ends up INSIDE. An edge
1461/// the selection dropped is still the sharp edge it was, and its points still
1462/// lie ON the skin. That statement holds for every caller and every lane,
1463/// which the previous attribution did not: it looked for one face per edge
1464/// carrying the caller's per-edge name, so a caller passing `None` (the wasm
1465/// ABI, `fillet_edges_json`) got NO count at all, and a caller passing names
1466/// was told a wall was missing where the network had merged two coaxial walls
1467/// into one face (the U-channel at half its width keeps one name for two
1468/// edges) or collapsed the walls of a full-width star into its corner patch
1469/// (`{base}:CORNER:…`, and no wall name at all). Both were measured
1470/// 2026-09-26; the named path REFUSED those complete blends.
1471///
1472/// The classifier answers `On` inside a band, so the check states how far
1473/// the blend of THIS size moves the edge at each probed station — `r·(1/cos(α/2)
1474/// − 1)` for a fillet and `d·sin(α/2)` for a chamfer, `α` the angle between the
1475/// two faces' outward normals there — and probes the station the blend moves
1476/// MOST. An edge that is tangent at one end (the miter seam two rounds leave
1477/// runs to 180° at its pole) is still attributed where it is sharp. Only when
1478/// no station clears the band is the selection refused by name, rather than
1479/// an unseeable move read as a missing wall.
1480pub fn walls_missing(
1481    original: &BrepSolid,
1482    result: &BrepSolid,
1483    edge_points: &[Vec3],
1484    selected: &[usize],
1485    size: f64,
1486    chamfer: bool,
1487    entry: &str,
1488) -> Result<Vec<usize>, KernelRefusal> {
1489    walls_missing_ties(original, result, edge_points, selected, size, chamfer, entry, false)
1490}
1491
1492// BREP lane L: begin walls_missing_tie_all_stations_20261015
1493/// [`walls_missing`], with `tie_majority`: on a clearance TIE (a uniform
1494/// dihedral, every station moving the same) the first station stands for
1495/// all of them unless this is set, when a wall is missing only if MORE THAN
1496/// HALF of the tied stations still lie on the skin (an unwalled edge whose
1497/// two ends neighbouring walls consume — the wedge nine-pick's unselected
1498/// side A ∩ wall — still reads missing; "every tied station" did not).  Only the runout composition sets it: its
1499/// own neighbouring wall may consume an edge's end (the rib nine-edge
1500/// selection's trimmed runout over the wall ∩ roof pad's first tenth read
1501/// as that pad having no wall), while elsewhere the first station is what
1502/// catches a cutter composition's wrong corners (the one-ended channel with
1503/// its runout switched off: stations ON at both ends of an edge whose middle
1504/// is walled — a measured 1253.219 against its 1253.373 body) and a station
1505/// reading alone cannot tell the two apart.
1506#[allow(clippy::too_many_arguments)]
1507pub fn walls_missing_ties(
1508    original: &BrepSolid,
1509    result: &BrepSolid,
1510    edge_points: &[Vec3],
1511    selected: &[usize],
1512    size: f64,
1513    chamfer: bool,
1514    entry: &str,
1515    tie_majority: bool,
1516) -> Result<Vec<usize>, KernelRefusal> {
1517// BREP lane L: end walls_missing_tie_all_stations_20261015
1518    use crate::{PointClass, SolidClassifier};
1519    if selected.is_empty() {
1520        return Ok(Vec::new());
1521    }
1522    let _timing = crate::blend::BlendTimer::start("timing.walls_missing_ms");
1523    crate::classification::classify_profile_begin();
1524    crate::classification::containment_profile_begin();
1525    let band = crate::KernelTolerances::for_solid(result, 1e-7).model;
1526    // `classify` reads `On` within ten times its band; attribution needs the
1527    // move to clear that by the same margin again.
1528    let visible = band * 100.0;
1529    let build_timing = crate::blend::BlendTimer::start("timing.walls_missing.classifier_ms");
1530    let classifier = SolidClassifier::new(result, band)
1531        .or_refuse(KernelStage::Validate, "wall_classifier")?;
1532    // Lane R1: a station's On-or-not is read
1533    // off its nearest face first (`NearestFaceSide`, the classifier's own On
1534    // band of ten `band`s, answering only where the read is rigorous); the
1535    // ray answers whatever it declines.
1536    let nearest = Some(super::analyze::NearestFaceSide::new(result, band).or_refuse(KernelStage::Validate, "wall_nearest_face")?);
1537    let reads_on = |point: Vec3| -> Result<bool, KernelRefusal> {
1538        if let Some(class) = nearest.as_ref().and_then(|nearest| nearest.side(point)) {
1539            crate::blend::record_count("count.walls_missing.nearest", 1);
1540            return Ok(class == PointClass::On);
1541        }
1542        Ok(classifier.classify(point).or_refuse(KernelStage::Validate, "wall_classify")?.class == PointClass::On)
1543    };
1544    build_timing.stop();
1545    const STATIONS: usize = 9;
1546    let mut missing = Vec::new();
1547    for &index in selected {
1548        let point = edge_points[index];
1549        let edge_id = resolve_edge_by_point(original, point)?;
1550        let (edge, faces) = super::analyze::edge_and_faces(original, edge_id)?;
1551        // The station the blend moves most, and how far.
1552        let mut best: Option<(Vec3, f64)> = None;
1553        // BREP lane L: begin walls_missing_tie_all_stations_20261015
1554        let mut read: Vec<(Vec3, f64)> = Vec::with_capacity(STATIONS);
1555        // BREP lane L: end walls_missing_tie_all_stations_20261015
1556        for step in 1..=STATIONS {
1557            let t = edge.t0 + (edge.t1 - edge.t0) * step as f64 / (STATIONS + 1) as f64;
1558            let Ok(station) = edge.curve.evaluate(t) else {
1559                continue;
1560            };
1561            let clearance = match faces[..] {
1562                [first, second] => {
1563                    let (Ok((_, a)), Ok((_, b))) = (
1564                        super::analyze::face_plane_normal(first, station),
1565                        super::analyze::face_plane_normal(second, station),
1566                    ) else {
1567                        continue;
1568                    };
1569                    let half: f64 = 0.5 * a.dot(b).clamp(-1.0, 1.0).acos();
1570                    if chamfer {
1571                        size * half.sin()
1572                    } else {
1573                        size * (1.0 / half.cos().max(1e-12) - 1.0)
1574                    }
1575                }
1576                // No dihedral to read: probe anyway, unguarded.
1577                _ => f64::INFINITY,
1578            };
1579            if best.map_or(true, |(_, known)| clearance > known) {
1580                best = Some((station, clearance));
1581            }
1582            // BREP lane L: begin walls_missing_tie_all_stations_20261015
1583            read.push((station, clearance));
1584            // BREP lane L: end walls_missing_tie_all_stations_20261015
1585        }
1586        let Some((station, clearance)) = best else {
1587            return Err(KernelRefusal::internal(
1588                KernelStage::Validate,
1589                "wall_attribution_stations",
1590                format!(
1591                    "{entry}: cannot attribute a wall to edge #{index} at ({:.6}, {:.6}, {:.6}) — no \
1592                     station of it could be evaluated",
1593                    point.x, point.y, point.z
1594                ),
1595            ));
1596        };
1597        if !(clearance > visible) {
1598            // The faces themselves put the move under the band: the input
1599            // leaves the attribution undecidable, and it is refused rather
1600            // than guessed.
1601            return Err(KernelRefusal::ill_posed(
1602                KernelStage::Validate,
1603                "wall_attribution_band",
1604                format!(
1605                    "{entry}: cannot attribute a wall to edge #{index} at ({:.6}, {:.6}, {:.6}) — \
1606                     its faces are so nearly tangent that a size-{size} blend moves the edge by at \
1607                     most {clearance:.3e}, inside the {visible:.3e} the classifier can see; the \
1608                     selection is refused rather than reported on a guess",
1609                    point.x, point.y, point.z
1610                ),
1611            ));
1612        }
1613        let classify_timing = crate::blend::BlendTimer::start("timing.walls_missing.classify_ms");
1614        // The question is On or not On, never In against Out: a station the
1615        // certificate below puts farther than `visible` from every face of
1616        // the result cannot read On by the classifier's band pass (a foot on
1617        // a carrier within ten bands) nor by its ray pass (a hit within ten
1618        // bands), so it is not asked. Anything the certificate declines is
1619        // classified as before.
1620        let certified = station_clear_of_skin(result, station, band * 10.0, visible)
1621            || station_clear_of_trimmed_skin(result, station, band * 10.0, visible);
1622        let on = if certified {
1623            crate::blend::record_count("count.walls_missing.certified", 1);
1624            false
1625        } else {
1626            crate::blend::record_count("count.walls_missing.classified", 1);
1627            reads_on(station)?
1628        };
1629        classify_timing.stop();
1630        // BREP lane L: begin walls_missing_tie_all_stations_20261015
1631        let on = on && (!tie_majority || {
1632            // The most-moved station read On; on a tie, so must more than
1633            // half of the tied stations (itself included).
1634            let tolerance = 1e-12 * clearance.abs().max(1.0);
1635            let (mut tied, mut on_skin) = (1usize, 1usize);
1636            for (other, other_clearance) in read.iter().copied() {
1637                if other.sub(station).length() == 0.0 || clearance - other_clearance > tolerance {
1638                    continue;
1639                }
1640                tied += 1;
1641                if !station_clear_of_skin(result, other, band * 10.0, visible) && reads_on(other)? {
1642                    on_skin += 1;
1643                }
1644            }
1645            2 * on_skin > tied
1646        });
1647        // BREP lane L: end walls_missing_tie_all_stations_20261015
1648        if on {
1649            missing.push(index);
1650        }
1651    }
1652    crate::classification::classify_profile_report("blend.walls_missing");
1653    crate::classification::containment_profile_report("blend.walls_missing");
1654    Ok(missing)
1655}
1656
1657
1658
1659/// Is `station` certainly farther than `margin` from every face of `result`,
1660/// trims included, read without a classifier query? `true` only when every
1661/// face is certified by one of three readings, each a lower bound on the
1662/// distance from the station to that face's trimmed carrier:
1663///
1664/// - its control-point box, widened by `on_band`, does not hold the station
1665///   (the carrier lies in the hull of positively weighted control points);
1666/// - its carrier is a recognised revolution (`NurbsSurface::analytic`,
1667///   matched to 1e-9 relative): a sphere or torus farther than `margin` in
1668///   closed form; a cone, cylinder or straight-generatrix partial sweep
1669///   whose PATCH is farther than `margin` by the larger of three lower
1670///   bounds, the meridian distance to the generatrix line, the axial
1671///   clearance from the generatrix's slab and the clearance from the
1672///   sweep's wedge (a station on one box edge lies ON the infinite cylinder
1673///   of each neighbouring wall, a radius from its centre line, and is a
1674///   radius short of its slab);
1675/// - its carrier is a recognised plane, the station's foot on it is
1676///   `Outside` the trims (`parameter_point_in_face`, the kernel's own lane
1677///   at the band the classifier would use), every loop pcurve is a straight
1678///   two-point unit-weight chord (so its image under the affine chart is a
1679///   straight 3-D segment, and the trim polygon is exact), and the station
1680///   is farther than `margin` from every chord's segment: a foot outside the
1681///   region is nearer to the region's boundary than to any of its points.
1682///
1683/// Any face none of the three reads (an unrecognised carrier, a plane the
1684/// station lies on whose trims are curved, a foot inside or on the trims)
1685/// declines the whole station to the classifier. The recogniser's 1e-9
1686/// relative bar sits four orders below the `margin` the caller passes
1687/// (a hundred model bands), which is what absorbs it.
1688fn station_clear_of_skin(result: &BrepSolid, station: Vec3, on_band: f64, margin: f64) -> bool {
1689    use crate::AnalyticSurface;
1690    // The station in a revolution frame: (ρ, h) in the meridian plane and
1691    // its azimuth θ in [0, 2π) from the frame's x axis.
1692    let meridian = |frame: &crate::RevolutionFrame| -> (f64, f64, f64) {
1693        let offset = station.sub(frame.origin);
1694        let axial = offset.dot(frame.axis);
1695        let radial = offset.sub(frame.axis.scale(axial));
1696        let mut azimuth = radial.dot(frame.y_axis).atan2(radial.dot(frame.x_axis));
1697        if azimuth < 0.0 {
1698            azimuth += std::f64::consts::TAU;
1699        }
1700        (radial.length(), axial, azimuth)
1701    };
1702    // A patch of a revolution lies inside the axial slab of its generatrix
1703    // and inside the wedge of its sweep, so the station's clearance from
1704    // either is a lower bound on its distance to the patch.
1705    let axial_clearance = |axial: f64, h0: f64, h1: f64| (h0.min(h1) - axial).max(axial - h0.max(h1)).max(0.0);
1706    let wedge_clearance = |radial: f64, azimuth: f64, sweep: f64| -> f64 {
1707        if sweep >= std::f64::consts::TAU || azimuth <= sweep {
1708            return 0.0;
1709        }
1710        // Outside the sweep: the angle to the nearer bounding meridian.
1711        let turn = (azimuth - sweep).min(std::f64::consts::TAU - azimuth);
1712        if turn >= std::f64::consts::FRAC_PI_2 { radial } else { radial * turn.sin() }
1713    };
1714    // Distance in the meridian plane from (ρ, h) to the LINE through two
1715    // generatrix points: a lower bound for a cone or cylinder's carrier.
1716    let line_distance = |radial: f64, axial: f64, (rho0, h0): (f64, f64), (rho1, h1): (f64, f64)| -> Option<f64> {
1717        let (du, dv) = (rho1 - rho0, h1 - h0);
1718        let length = (du * du + dv * dv).sqrt();
1719        (length > 0.0).then(|| ((radial - rho0) * dv - (axial - h0) * du).abs() / length)
1720    };
1721    let clear = |distance: f64| distance.is_finite() && distance > margin;
1722    for face in result.shells.iter().flat_map(|shell| &shell.faces) {
1723        let Ok(controls) = crate::Aabb::from_surface_controls(&face.surface) else { return false };
1724        if !controls.expanded(on_band).contains(station) {
1725            continue;
1726        }
1727        let certified = match face.surface.analytic() {
1728            Some(AnalyticSurface::RuledRevolution { frame, rho0, rho1, height }) => {
1729                let (radial, axial, _) = meridian(frame);
1730                let Some(line) = line_distance(radial, axial, (*rho0, 0.0), (*rho1, *height)) else { return false };
1731                clear(line.max(axial_clearance(axial, 0.0, *height)))
1732            }
1733            Some(AnalyticSurface::Sphere { frame, radius }) => clear((station.sub(frame.origin).length() - radius).abs()),
1734            Some(AnalyticSurface::Torus { frame, major_radius, minor_radius }) => {
1735                let (radial, axial, _) = meridian(frame);
1736                let tube = radial - major_radius;
1737                clear(((tube * tube + axial * axial).sqrt() - minor_radius).abs())
1738            }
1739            Some(AnalyticSurface::Revolution { frame, sweep, generatrix, .. }) => {
1740                // A STRAIGHT generatrix in the frame's zero meridian (the
1741                // extruded-arc walls: a line parallel to the axis at the
1742                // radius): its two control points read as (ρ, h), and the
1743                // patch's distance is bounded below by the meridian line
1744                // distance, the axial clearance and the wedge clearance
1745                // together. A curved or off-meridian generatrix declines.
1746                let [a, b] = generatrix.control_points.as_slice() else { return false };
1747                if generatrix.degree != 1 || a.w != 1.0 || b.w != 1.0 {
1748                    return false;
1749                }
1750                let meridian_of = |point: Vec3| -> Option<(f64, f64)> {
1751                    let offset = point.sub(frame.origin);
1752                    let axial = offset.dot(frame.axis);
1753                    let radial = offset.sub(frame.axis.scale(axial));
1754                    let rho = radial.length();
1755                    let on_meridian = radial.dot(frame.y_axis).abs() <= 1e-9 * rho.max(1.0) && radial.dot(frame.x_axis) >= -1e-9 * rho.max(1.0);
1756                    on_meridian.then_some((rho, axial))
1757                };
1758                let (Some(p0), Some(p1)) = (meridian_of(Vec3::new(a.x, a.y, a.z)), meridian_of(Vec3::new(b.x, b.y, b.z))) else {
1759                    return false;
1760                };
1761                let (radial, axial, azimuth) = meridian(frame);
1762                let Some(line) = line_distance(radial, axial, p0, p1) else { return false };
1763                // The TRIMMED face's slab is narrower than the surface's:
1764                // a station on one box edge lies on the untrimmed surface
1765                // of each perpendicular wall (that wall's rail line runs
1766                // through the corner), a radius short of its trimmed face.
1767                let slab = trimmed_axial_slab(face, frame).unwrap_or((p0.1, p1.1));
1768                clear(line.max(axial_clearance(axial, slab.0, slab.1)).max(wedge_clearance(radial, azimuth, *sweep)))
1769            }
1770            Some(plane @ AnalyticSurface::Plane { origin, u_dir, v_dir, .. }) => {
1771                let Ok(normal) = u_dir.cross(*v_dir).normalized() else { return false };
1772                if clear(station.sub(*origin).dot(normal).abs()) {
1773                    true
1774                } else {
1775                    planar_trims_clear_of(face, plane, station, on_band, margin)
1776                }
1777            }
1778            None => false,
1779        };
1780        if !certified {
1781            return false;
1782        }
1783    }
1784    true
1785}
1786
1787/// A tighter sufficient Not-On certificate. General carriers use subdivided
1788/// positive-weight hulls. Analytic carriers retain the projector and trim
1789/// band used by the nearest-face reader; an exterior foot also needs every
1790/// exact boundary edge farther than the existing attribution margin.
1791/// Any inconclusive read leaves the original nearest/ray query in charge.
1792fn station_clear_of_trimmed_skin(result: &BrepSolid, point: Vec3, on_band: f64, margin: f64) -> bool {
1793    let _timer = crate::blend::BlendTimer::start("timing.walls_missing.trimmed_bound_ms");
1794    if !point.x.is_finite() || !point.y.is_finite() || !point.z.is_finite()
1795        || !margin.is_finite() || !(margin > on_band && on_band > 0.0)
1796    { return false; }
1797    for face in result.shells.iter().flat_map(|shell| &shell.faces) {
1798        let Ok(bounds) = crate::Aabb::from_surface_controls(&face.surface) else { return false; };
1799        if !bounds.expanded(margin).contains(point) { continue; }
1800        if face.surface.analytic().is_none() {
1801            if general_carrier_clear(&face.surface, point, margin) { continue; }
1802            return false;
1803        }
1804        // Within `margin`, these regular carriers have a unique nearest
1805        // foot; every other stationary foot is farther than the margin.
1806        // The sphere/torus medial sets and spindle/horn tori decline. Thus
1807        // an exterior nearest foot can meet a trimmed region within the
1808        // margin only by crossing a boundary edge inside that same ball.
1809        match face.surface.analytic() {
1810            Some(crate::AnalyticSurface::Plane { .. }) => {},
1811            Some(crate::AnalyticSurface::Sphere { radius, .. }) if *radius > 4.0 * margin => {},
1812            Some(crate::AnalyticSurface::Torus { major_radius, minor_radius, .. })
1813                if *minor_radius > 4.0 * margin && *major_radius > *minor_radius + 4.0 * margin => {},
1814            _ => return false,
1815        }
1816        let Ok(projection) = crate::project_point_to_surface(&face.surface, point) else { return false; };
1817        if !projection.distance.is_finite() { return false; }
1818        if projection.distance > margin { continue; }
1819        let band = crate::classification::surface_uv_band(&face.surface, projection.u, projection.v, on_band);
1820        let Ok(inside) = crate::parameter_point_in_face(face, crate::Vec2 { x: projection.u, y: projection.v }, band) else { return false; };
1821        if inside != crate::PolygonClass::Outside { return false; }
1822        let mut edges = 0;
1823        for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
1824            let Some(edge) = result.edges.iter().find(|edge| edge.id == coedge.edge_id) else { return false; };
1825            let Some(piece) = super::analyze::edge_piece(&edge.curve, edge.t0.min(edge.t1), edge.t0.max(edge.t1)) else { return false; };
1826            let Ok(foot) = crate::project_point_to_curve(&piece, point) else { return false; };
1827            if !foot.distance.is_finite() || foot.distance <= margin { return false; }
1828            edges += 1;
1829        }
1830        if edges == 0 { return false; }
1831    }
1832    true
1833}
1834
1835/// A sufficient clearance test for a general carrier, without finding its
1836/// nearest point. Positive-weight Bezier patches lie inside their control
1837/// hulls. Decompose both clamped knot vectors, then bisect only boxes still
1838/// within `margin` of the query. Any unsupported net or exhausted work budget
1839/// declines to the existing classifier; no approximate distance is accepted.
1840fn general_carrier_clear(surface: &crate::NurbsSurface, point: Vec3, margin: f64) -> bool {
1841    use crate::Vec4;
1842    let rows = surface.control_points.len();
1843    let columns = surface.control_points.first().map_or(0, Vec::len);
1844    if rows == 0 || columns == 0 || rows.saturating_mul(columns) > 4096
1845        || surface.degree_u > 16 || surface.degree_v > 16 || surface.control_points.iter().any(|row| row.len() != columns)
1846        || !margin.is_finite() || margin <= 0.0
1847        || !point.x.is_finite() || !point.y.is_finite() || !point.z.is_finite()
1848    { return false; }
1849    let mut scale = 1.0_f64;
1850    for control in surface.control_points.iter().flatten() {
1851        if !(control.w > 0.0) || !control.w.is_finite() { return false; }
1852        let Ok(p) = control.point() else { return false; };
1853        if !p.x.is_finite() || !p.y.is_finite() || !p.z.is_finite() { return false; }
1854        scale = scale.max(p.x.abs()).max(p.y.abs()).max(p.z.abs());
1855    }
1856    // Leave a rounding cushion far below the caller's existing model margin.
1857    // Unsupported scales decline rather than consume the classification band.
1858    let roundoff = 256.0 * f64::EPSILON * scale * (surface.degree_u + 1) as f64 * (surface.degree_v + 1) as f64;
1859    if roundoff >= margin * 0.01 { return false; }
1860    let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1861    let blend = |a: Vec4, b: Vec4, alpha: f64| a.scale(alpha).add(b.scale(1.0 - alpha));
1862    let mut fibres = Vec::with_capacity(columns);
1863    for column in 0..columns {
1864        let controls: Vec<_> = surface.control_points.iter().map(|row| row[column]).collect();
1865        let Some(spans) = crate::curve::bezier_decompose_raw(&surface.knots_u, &controls, surface.degree_u, zero, blend) else { return false; };
1866        fibres.push(spans);
1867    }
1868    let mut budget = 256usize;
1869    for u_span in 0..fibres[0].len() {
1870        let mut across = Vec::with_capacity(surface.degree_u + 1);
1871        for row in 0..=surface.degree_u {
1872            let controls: Vec<_> = fibres.iter().map(|fibre| fibre[u_span][row]).collect();
1873            let Some(spans) = crate::curve::bezier_decompose_raw(&surface.knots_v, &controls, surface.degree_v, zero, blend) else { return false; };
1874            across.push(spans);
1875        }
1876        for v_span in 0..across[0].len() {
1877            let net = across.iter().map(|row| row[v_span].clone()).collect();
1878            if !bezier_box_clear(net, point, margin + roundoff, 0, &mut budget) { return false; }
1879        }
1880    }
1881    true
1882}
1883
1884fn bezier_box_clear(net: Vec<Vec<crate::Vec4>>, point: Vec3, margin: f64, depth: usize, budget: &mut usize) -> bool {
1885    if *budget == 0 { return false; }
1886    *budget -= 1;
1887    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
1888    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
1889    for control in net.iter().flatten() {
1890        if !(control.w > 0.0) || !control.w.is_finite() { return false; }
1891        let Ok(p) = control.point() else { return false; };
1892        if !p.x.is_finite() || !p.y.is_finite() || !p.z.is_finite() { return false; }
1893        low.x = low.x.min(p.x); low.y = low.y.min(p.y); low.z = low.z.min(p.z);
1894        high.x = high.x.max(p.x); high.y = high.y.max(p.y); high.z = high.z.max(p.z);
1895    }
1896    // One separating coordinate is enough, and avoids a rounded square root.
1897    if point.x < low.x - margin || point.x > high.x + margin
1898        || point.y < low.y - margin || point.y > high.y + margin
1899        || point.z < low.z - margin || point.z > high.z + margin
1900    { return true; }
1901    if depth == 10 { return false; }
1902    let rows = net.len();
1903    let columns = net[0].len();
1904    let mut left = net.clone();
1905    let mut right = net.clone();
1906    // Alternate directions: every child covers exactly half the parent's
1907    // parameter rectangle; both must prove clearance.
1908    if depth % 2 == 0 {
1909        for column in 0..columns {
1910            let mut work: Vec<_> = net.iter().map(|row| row[column]).collect();
1911            for level in 1..rows {
1912                for i in 0..rows - level { work[i] = work[i].scale(0.5).add(work[i + 1].scale(0.5)); }
1913                left[level][column] = work[0];
1914                right[rows - level - 1][column] = work[rows - level - 1];
1915            }
1916        }
1917    } else {
1918        for row in 0..rows {
1919            let mut work = net[row].clone();
1920            for level in 1..columns {
1921                for i in 0..columns - level { work[i] = work[i].scale(0.5).add(work[i + 1].scale(0.5)); }
1922                left[row][level] = work[0];
1923                right[row][columns - level - 1] = work[columns - level - 1];
1924            }
1925        }
1926    }
1927    bezier_box_clear(left, point, margin, depth + 1, budget)
1928        && bezier_box_clear(right, point, margin, depth + 1, budget)
1929}
1930
1931/// The axial range `(h_low, h_high)` of a face's TRIMMED region on a
1932/// revolution whose generatrix is straight: the region lies in the uv box
1933/// of its straight-chord loops (every pcurve a two-point unit-weight
1934/// chord), the surface is a tensor product in which the axial coordinate
1935/// `h = (S − origin)·axis` depends on one parameter only and affinely
1936/// (degree 1, two control points along it), so `h` over the box is the
1937/// range between its values at the box's corners. `None` when any of that
1938/// is not read: a curved chord, an `h` that moves along both parameters,
1939/// a degree or control count that is not affine, an evaluation that fails.
1940fn trimmed_axial_slab(face: &FaceRecord, frame: &crate::RevolutionFrame) -> Option<(f64, f64)> {
1941    let (mut u_low, mut u_high, mut v_low, mut v_high) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);
1942    for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1943        let pcurve = &coedge.pcurve;
1944        let [a, b] = pcurve.control_points.as_slice() else { return None };
1945        if pcurve.degree != 1 || a.w != 1.0 || b.w != 1.0 {
1946            return None;
1947        }
1948        for control in [a, b] {
1949            u_low = u_low.min(control.x);
1950            u_high = u_high.max(control.x);
1951            v_low = v_low.min(control.y);
1952            v_high = v_high.max(control.y);
1953        }
1954    }
1955    if !(u_low <= u_high && v_low <= v_high) {
1956        return None;
1957    }
1958    let axial_at = |u: f64, v: f64| face.surface.evaluate(u, v).ok().map(|point| point.sub(frame.origin).dot(frame.axis));
1959    let corners = [axial_at(u_low, v_low)?, axial_at(u_high, v_low)?, axial_at(u_low, v_high)?, axial_at(u_high, v_high)?];
1960    let scale = corners.iter().fold(1.0_f64, |scale, h| scale.max(h.abs()));
1961    let same = |a: f64, b: f64| (a - b).abs() <= 1e-9 * scale;
1962    let surface = &face.surface;
1963    // h constant along u (the generatrix runs along v), or along v.
1964    let affine_in_v = same(corners[0], corners[1]) && same(corners[2], corners[3])
1965        && surface.degree_v == 1 && surface.control_points.first().is_some_and(|row| row.len() == 2);
1966    let affine_in_u = same(corners[0], corners[2]) && same(corners[1], corners[3])
1967        && surface.degree_u == 1 && surface.control_points.len() == 2;
1968    if !(affine_in_v || affine_in_u) {
1969        return None;
1970    }
1971    let low = corners.iter().copied().fold(f64::INFINITY, f64::min);
1972    let high = corners.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1973    (low.is_finite() && high.is_finite()).then_some((low, high))
1974}
1975
1976/// The planar reading of [`station_clear_of_skin`]: the station's foot on
1977/// the plane lies `Outside` the face's trims and every straight loop chord's
1978/// 3-D segment is farther than `margin` from the station.
1979fn planar_trims_clear_of(
1980    face: &FaceRecord,
1981    plane: &crate::AnalyticSurface,
1982    station: Vec3,
1983    on_band: f64,
1984    margin: f64,
1985) -> bool {
1986    use crate::PolygonClass;
1987    let Some(foot) = plane.project(&face.surface, station) else { return false };
1988    let uv_band = crate::classification::surface_uv_band(&face.surface, foot.u, foot.v, on_band);
1989    match crate::parameter_point_in_face(face, crate::Vec2 { x: foot.u, y: foot.v }, uv_band) {
1990        Ok(PolygonClass::Outside) => {}
1991        _ => return false,
1992    }
1993    for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1994        let pcurve = &coedge.pcurve;
1995        let [a, b] = pcurve.control_points.as_slice() else { return false };
1996        if pcurve.degree != 1 || a.w != 1.0 || b.w != 1.0 {
1997            return false;
1998        }
1999        let (Ok(start), Ok(end)) = (face.surface.evaluate(a.x, a.y), face.surface.evaluate(b.x, b.y)) else { return false };
2000        let chord = end.sub(start);
2001        let length_squared = chord.dot(chord);
2002        let offset = station.sub(start);
2003        let along = if length_squared > 0.0 { (offset.dot(chord) / length_squared).clamp(0.0, 1.0) } else { 0.0 };
2004        let distance = offset.sub(chord.scale(along)).length();
2005        if !(distance.is_finite() && distance > margin) {
2006            return false;
2007        }
2008    }
2009    true
2010}
2011
2012/// The blend-FACE name for the `i`-th selected edge: its per-edge name when the
2013/// caller supplied the parallel `edge_names` (feature path — each wall named
2014/// after its originating edge, `{fid}:BLEND:{edge}`), else the single base
2015/// `name` for every wall (the legacy/test path, byte-identical to before).
2016fn per_edge_name<'a>(
2017    edge_names: Option<&'a [String]>,
2018    base: Option<&'a str>,
2019    i: usize,
2020) -> Option<&'a str> {
2021    match edge_names {
2022        Some(names) => names.get(i).map(|value| value.as_str()),
2023        None => base,
2024    }
2025}
2026
2027/// The star-corner patch name: `{base}:CORNER:{sorted+join of adjacent edge
2028/// names}` when per-edge names were supplied (feature path), else the single
2029/// `base` (legacy/test path — the corner keeps the wall name, pre-change
2030/// behavior).  `base` is `{fid}:BLEND` and each `edge_names[i]` is the composed
2031/// `{fid}:BLEND:{edge}`, so stripping the `{base}:` prefix recovers the bare
2032/// originating-edge name for the join.  Unique per corner: two distinct corners
2033/// never share the same set of >=3 selected edges.
2034fn corner_face_name(
2035    edge_names: Option<&[String]>,
2036    base: Option<&str>,
2037    adjacent: &[usize],
2038) -> Option<String> {
2039    match (edge_names, base) {
2040        (Some(names), Some(base)) => {
2041            let prefix = format!("{base}:");
2042            let mut raws: Vec<&str> = adjacent
2043                .iter()
2044                .filter_map(|&i| names.get(i))
2045                .map(|composed| composed.strip_prefix(&prefix).unwrap_or(composed.as_str()))
2046                .collect();
2047            raws.sort_unstable();
2048            raws.dedup();
2049            Some(format!("{base}:CORNER:{}", raws.join("+")))
2050        }
2051        _ => base.map(|value| value.to_string()),
2052    }
2053}
2054
2055/// Round a connected group of convex edges first, including its ordinary
2056/// convex corner patches, then blend the concave rim across a curved bridge
2057/// at each transverse mixed corner. The spine's carriers and the cap may be
2058/// planes or curved analytic faces alike: transversality is read from the
2059/// three normals at the corner, and the rim network marches the bridge on the
2060/// actual carriers. Without these bridges the rim stripes would remain
2061/// disconnected. Redispatch the remaining selection: other mixed corners may
2062/// need another convex group or a pole-to-pole runout.
2063/// Each step removes the rounded group from the pending selection.
2064#[allow(clippy::too_many_arguments)]
2065fn rounded_boss_composition(
2066    solid: &BrepSolid,
2067    selected_ids: &[u64],
2068    edge_points: &[Vec3],
2069    edge_names: Option<&[String]>,
2070    radius: f64,
2071    name: Option<&str>,
2072    corners: &[crate::blend::MixedCorner],
2073) -> Result<BrepSolid, KernelRefusal> {
2074    // The legacy API gives every wall the same base name (or none). Use
2075    // distinct temporary identities through the recursive composition so a
2076    // bridge can be attributed to its own convex wall. Restore that API's
2077    // naming contract after the whole selection has been built.
2078    if edge_names.is_none() {
2079        let prefix = "FILLET:COMPOSITION";
2080        let names: Vec<_> = selected_ids
2081            .iter()
2082            .map(|id| format!("{prefix}:{id}"))
2083            .collect();
2084        let mut result = rounded_boss_composition(
2085            solid,
2086            selected_ids,
2087            edge_points,
2088            Some(&names),
2089            radius,
2090            Some(prefix),
2091            corners,
2092        )?;
2093        for face in result.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
2094            if face
2095                .name
2096                .as_deref()
2097                .is_some_and(|value| value.starts_with("FILLET:COMPOSITION:"))
2098            {
2099                face.name = name.map(str::to_owned);
2100            }
2101        }
2102        return Ok(result);
2103    }
2104    let decline = || {
2105        KernelRefusal::unsupported(KernelStage::Classify, "rounded_boss_selection",
2106        "the rounded boss composition requires a convex group meeting transverse mixed corners at one end of each spine")
2107    };
2108    if std::env::var("BREP_NO_NETWORK").is_ok() {
2109        return Err(decline());
2110    }
2111    // Select by topology id so reversing the requested edges preserves the
2112    // construction order. Two-ended spines are left for runout composition.
2113    let corner = corners
2114        .iter()
2115        .filter(|corner| {
2116            corner.convex.len() == 1
2117                && corner.concave.len() == 2
2118                && corners
2119                    .iter()
2120                    .filter(|other| other.convex.contains(&corner.convex[0]))
2121                    .count()
2122                    == 1
2123        })
2124        .min_by_key(|corner| selected_ids[corner.convex[0]])
2125        .ok_or_else(decline)?;
2126    let convexity =
2127        crate::blend::selection_convexity(solid, selected_ids, radius).ok_or_else(decline)?;
2128    if !convexity[corner.convex[0]] {
2129        return Err(decline());
2130    }
2131    let spine_index = corner.convex[0];
2132    // Resolve once so a missing selected edge refuses before connectivity
2133    // traversal rather than panicking inside the adjacency predicate.
2134    let selected_edges: Vec<&EdgeRecord> = selected_ids
2135        .iter()
2136        .map(|id| {
2137            solid
2138                .edges
2139                .iter()
2140                .find(|edge| edge.id == *id)
2141                .ok_or_else(|| {
2142                    KernelRefusal::internal(
2143                        KernelStage::Collect,
2144                        "rounded_boss_selected_edge",
2145                        format!("rounded boss composition: selected edge {id} is missing"),
2146                    )
2147                })
2148        })
2149        .collect::<Result<_, _>>()?;
2150    // Round the connected convex selection together. Its far corners need
2151    // their usual vertex patches before a concave rim can cross these walls.
2152    let mut rounded_indices = vec![spine_index];
2153    loop {
2154        let next = (0..selected_ids.len()).find(|index| {
2155            convexity[*index]
2156                && !rounded_indices.contains(index)
2157                && rounded_indices.iter().any(|other| {
2158                    let edge = selected_edges[*index];
2159                    let mate = selected_edges[*other];
2160                    [edge.start_vertex_id, edge.end_vertex_id]
2161                        .iter()
2162                        .any(|v| *v == mate.start_vertex_id || *v == mate.end_vertex_id)
2163                })
2164        });
2165        match next {
2166            Some(index) => rounded_indices.push(index),
2167            None => break,
2168        }
2169    }
2170    // Keep complete stars together. A selected concave edge between two
2171    // convex rims is part of their vertex blend, even though it is not part
2172    // of the convex flood above. Rounding the rims without it builds a horn
2173    // torus for an *unselected* third edge; adding that edge later leaves a
2174    // flat cap against the torus instead of the selected star's tangent sector.
2175    // Only absorb an edge whose selected neighbours are already in this
2176    // group at BOTH ends. In particular, never pull in a concave rim leading
2177    // to another mixed corner: that rim still needs the bridge below.
2178    loop {
2179        let next = (0..selected_ids.len()).find(|&index| {
2180            if convexity[index] || rounded_indices.contains(&index) {
2181                return false;
2182            }
2183            let edge = selected_edges[index];
2184            let mut has_star = false;
2185            for vertex in [edge.start_vertex_id, edge.end_vertex_id] {
2186                let neighbours: Vec<_> = selected_edges.iter().enumerate()
2187                    .filter(|(other, mate)| *other != index
2188                        && (mate.start_vertex_id == vertex || mate.end_vertex_id == vertex))
2189                    .map(|(other, _)| other)
2190                    .collect();
2191                if neighbours.iter().any(|other| !rounded_indices.contains(other)) {
2192                    return false;
2193                }
2194                has_star |= neighbours.len() >= 2;
2195            }
2196            has_star
2197        });
2198        match next {
2199            Some(index) => rounded_indices.push(index),
2200            None => break,
2201        }
2202    }
2203    rounded_indices.sort_by_key(|index| selected_ids[*index]);
2204    let mixed: Vec<_> = corners
2205        .iter()
2206        .filter(|corner| {
2207            corner
2208                .convex
2209                .iter()
2210                .any(|index| rounded_indices.contains(index))
2211        })
2212        .collect();
2213    if mixed.iter().any(|corner| {
2214        corner.convex.len() != 1
2215            || corner.concave.len() != 2
2216            || corners
2217                .iter()
2218                .filter(|other| other.convex.contains(&corner.convex[0]))
2219                .count()
2220                != 1
2221    }) {
2222        return Err(decline());
2223    }
2224    let uses = |face: &FaceRecord, edge: u64| {
2225        face.loops
2226            .iter()
2227            .flat_map(|rim| &rim.coedges)
2228            .any(|coedge| coedge.edge_id == edge)
2229    };
2230    let mut caps = Vec::new();
2231    for corner in &mixed {
2232        let spine_id = selected_ids[corner.convex[0]];
2233        let cap = solid
2234            .shells
2235            .iter()
2236            .flat_map(|shell| &shell.faces)
2237            .find(|face| {
2238                corner
2239                    .concave
2240                    .iter()
2241                    .all(|index| uses(face, selected_ids[*index]))
2242            })
2243            .ok_or_else(decline)?;
2244        let faces: Vec<_> = solid
2245            .shells
2246            .iter()
2247            .flat_map(|shell| &shell.faces)
2248            .filter(|face| face.id == cap.id || uses(face, spine_id))
2249            .collect();
2250        // The normals at the corner: a plane's from its frame, any other
2251        // carrier's at the corner's own foot on it.  The 2026-10-12 sprocket
2252        // report (`inbox_20261012_sprocket_fillet`) was the first curved CAP;
2253        // the 2026-10-13 reports on the same part put the SPINE on a cylinder
2254        // (the rim top's arc, rim wall ∩ rim top, dying into the spoke wall)
2255        // and were declined here before anything was tried, which handed the
2256        // whole selection to the runout lane and its refusal
2257        // (`inbox_20261013_sprocket_spoke_fillet`).
2258        let normals: Option<Vec<Vec3>> = faces
2259            .iter()
2260            .map(|face| match face.surface.analytic() {
2261                Some(crate::AnalyticSurface::Plane { u_dir, v_dir, .. }) => {
2262                    u_dir.cross(*v_dir).normalized().ok()
2263                }
2264                _ => {
2265                    let uv = crate::project_point_to_surface(&face.surface, corner.point).ok()?;
2266                    face.surface.normal(uv.u, uv.v).ok()
2267                }
2268            })
2269            .collect();
2270        let normals = normals.ok_or_else(decline)?;
2271        // The cap need not be perpendicular to the spine's two carriers.
2272        // An oblique or cylindrical cap cuts the rounded wall in a curved
2273        // bridge. The rim network marches that bridge on the actual carriers.
2274        // Test transversality at the corner; a cylindrical cap need not be
2275        // replaced by its tangent plane to build this composition.
2276        if normals.len() != 3
2277            || normals[0].cross(normals[1]).dot(normals[2]).abs() < 1e-6
2278        {
2279            return Err(decline());
2280        }
2281        caps.push(cap.id);
2282    }
2283    // Give unnamed walls distinct identities too: bridges are located by
2284    // their two carriers, never proximity to the old corner.
2285    let rounded_names: Vec<String> = rounded_indices
2286        .iter()
2287        .map(|index| {
2288            per_edge_name(edge_names, name, *index)
2289                .map(str::to_owned)
2290                .unwrap_or_else(|| format!("FILLET:ROUNDED_BOSS_SPINE:{index}"))
2291        })
2292        .collect();
2293    let rounded_points: Vec<Vec3> = rounded_indices
2294        .iter()
2295        .map(|index| edge_points[*index])
2296        .collect();
2297    let rounded = fillet_edges_group_in(
2298        solid,
2299        &rounded_points,
2300        Some(&rounded_names),
2301        radius,
2302        false,
2303        name,
2304        None,
2305    )?;
2306    let mut bridges = Vec::new();
2307    for (corner, cap) in mixed.iter().zip(&caps) {
2308        let wall_index = rounded_indices
2309            .iter()
2310            .position(|index| *index == corner.convex[0])
2311            .ok_or_else(|| {
2312                KernelRefusal::internal(
2313                    KernelStage::Classify,
2314                    "rounded_boss_bridge_wall",
2315                    format!(
2316                        "rounded boss composition: no convex wall for corner {}",
2317                        corner.vertex
2318                    ),
2319                )
2320            })?;
2321        let candidates: Vec<_> = rounded
2322            .edges
2323            .iter()
2324            .filter(|edge| {
2325                let faces: Vec<_> = rounded
2326                    .shells
2327                    .iter()
2328                    .flat_map(|shell| &shell.faces)
2329                    .filter(|face| uses(face, edge.id))
2330                    .collect();
2331                faces.iter().any(|face| face.id == *cap)
2332                    && faces
2333                        .iter()
2334                        .any(|face| face.name.as_deref() == Some(&rounded_names[wall_index]))
2335            })
2336            .collect();
2337        if candidates.len() != 1 {
2338            return Err(decline());
2339        }
2340        bridges.push(candidates[0]);
2341    }
2342    let rim_ids: Vec<u64> = selected_ids
2343        .iter()
2344        .enumerate()
2345        .filter(|(index, _)| !rounded_indices.contains(index))
2346        .map(|(_, id)| *id)
2347        .collect();
2348    // Both ends must join requested rim edges: never extend a selection
2349    // into an unselected perimeter.
2350    if !bridges.iter().all(|bridge| {
2351        [bridge.start_vertex_id, bridge.end_vertex_id]
2352            .iter()
2353            .all(|vertex| {
2354                rounded.edges.iter().any(|edge| {
2355                    rim_ids.contains(&edge.id)
2356                        && (edge.start_vertex_id == *vertex || edge.end_vertex_id == *vertex)
2357                })
2358            })
2359    }) {
2360        return Err(decline());
2361    }
2362    let mut points = Vec::new();
2363    let mut names = Vec::new();
2364    for (index, id) in selected_ids.iter().enumerate() {
2365        if rounded_indices.contains(&index) {
2366            continue;
2367        }
2368        let edge = rounded
2369            .edges
2370            .iter()
2371            .find(|edge| edge.id == *id)
2372            .ok_or_else(decline)?;
2373        points.push(
2374            edge.curve
2375                .evaluate(0.5 * (edge.t0 + edge.t1))
2376                .or_refuse(KernelStage::Collect, "rim_midpoint")?,
2377        );
2378        names.push(
2379            per_edge_name(edge_names, name, index)
2380                .unwrap_or("FILLET:RIM")
2381                .to_owned(),
2382        );
2383    }
2384    for (corner, bridge) in mixed.iter().zip(&bridges) {
2385        points.push(
2386            bridge
2387                .curve
2388                .evaluate(0.5 * (bridge.t0 + bridge.t1))
2389                .or_refuse(KernelStage::Collect, "bridge_midpoint")?,
2390        );
2391        let mut adjacent = corner.concave.clone();
2392        adjacent.push(corner.convex[0]);
2393        names.push(
2394            corner_face_name(edge_names, name, &adjacent)
2395                .unwrap_or_else(|| format!("FILLET:BOSS_CORNER:{}", corner.vertex)),
2396        );
2397    }
2398    // A partial rim would leave an open mixed-corner construction. Require
2399    // every pending wall, including each bridge, before accepting composition.
2400    fillet_edges_reported(&rounded, &points, Some(&names), radius, false, name).and_then(
2401        |(result, selection)| {
2402            if selection.applied.len() != points.len() {
2403                Err(decline())
2404            } else {
2405                Ok(result)
2406            }
2407        },
2408    )
2409}
2410
2411// A corner with two concave edges and a convex one requires composition.
2412//
2413// Where selected edges meet, the rolling ball has to touch every face around
2414// the vertex from ONE side. A convex edge running into the concave edges it
2415// meets (a rib spine dying into the fillets at its own base) asks the ball to
2416// sit under the shared face for one blend and over it for the other, so no
2417// ball seats there and the corner has no closure: physically the convex blend
2418// runs out against the concave beads partway along the edge, which is a vertex
2419// blend the stripe network does not construct.
2420//
2421// The re-entrant vertex of a notch — ONE concave edge, the rest convex — is
2422// NOT this: the ball rolls round that single concave edge from one convex
2423// blend to the next, and `round_concave_chain_corner` / `round_convex_corner`
2424// close it with the horn-torus sector.  Only its mirror is refused.
2425//
2426// This is TERMINAL — deliberately not a fall-through to the cutter
2427// composition. The cutter answers this shape with a watertight but shredded
2428// solid: a sliver end cap at each unclosed corner and the carrier face split
2429// so the original name lands on a fragment, which breaks every downstream
2430// reference to it. A named refusal that says which edges to separate is
2431// worth more than that solid. The runout composition (the 2026-09-30 record
2432// §5): a selection whose convex edges die into concave ones at
2433// mixed-convexity corners is built in two stages — the CONCAVE edges first,
2434// through the ordinary group path (exactly the ring the user gets selecting
2435// them alone), then one runout wall per convex spine on that ring result,
2436// marched from pole to pole with its carriers switching onto the ring's own
2437// pads. Accepted under the network's own checks.
2438//
2439// The class built here: every convex edge of the selection ends on a mixed
2440// corner at BOTH ends and shares no vertex with another convex edge, and
2441// every other selected edge is concave.  Anything else keeps the named
2442// refusal.
2443#[allow(clippy::too_many_arguments)]
2444/// The OPEN-PAD composition (the 2026-10-17 "fillet takes way too long"
2445/// face-ring report): a selection whose every mixed corner is ONE convex edge
2446/// meeting ONE concave edge over the planar face they share, the third edge
2447/// at the corner either a tangent rail (the convex edge is a blend's own end
2448/// cut by the plane, the concave one the boss it was blended to: a zero-angle
2449/// sliver on the plane) or a sharp concave edge (the boss meeting the convex
2450/// edge's other mate). Neither the rounded-boss nor the runout composition
2451/// admits it (flush-joined convex chains, concave pads ending at the corners,
2452/// no concave ring).
2453///
2454/// Built in two stages on the stripe network, each an ordinary group build:
2455///
2456/// 1. Every CONVEX edge first. A convex chain's free end at a mixed corner
2457///    is the §6.9 transverse construction against the boss as the end face:
2458///    the wall is trimmed where its envelope enters the boss, the sliver tip
2459///    of the planar face goes, and the boss skin that lay under it is exposed
2460///    along the trim curve (no cliff: the trim runs from the wall's floor
2461///    rail to its rail on the other mate, which at a tangent-rail corner
2462///    lands on that rail where wall and boss are tangent).
2463/// 2. Every CONCAVE edge on the stage-1 body, EXTENDED by the trim curves it
2464///    now continues into G1 at each trimmed end (floor|boss into wall|boss
2465///    across the wall's floor rail, a tangent seam): a flush join with a seam
2466///    at the trim's start, and at the trim's far end a pole where the wall
2467///    is tangent to the boss, or a cap where the trim meets an unselected
2468///    sharp edge. The pad rides the wall past the floor rails' crossing.
2469///
2470/// The walls are named after their edges; a trim continuation is named
2471/// `{base}:RUNOUT:{pad}+{wall}` from the two bare edge names.
2472#[allow(clippy::too_many_arguments)]
2473fn open_pad_composition(
2474    solid: &BrepSolid,
2475    selected_ids: &[u64],
2476    edge_points: &[Vec3],
2477    edge_names: Option<&[String]>,
2478    radius: f64,
2479    name: Option<&str>,
2480    corners: &[crate::blend::MixedCorner],
2481    entry: &str,
2482) -> Result<BrepSolid, KernelRefusal> {
2483    let shape = |message: String| KernelRefusal::unsupported(KernelStage::Classify, "open_pad_shape", message);
2484    if std::env::var("BREP_NO_NETWORK").is_ok() {
2485        return Err(shape("the open-pad composition is a network construction and BREP_NO_NETWORK is set".into()));
2486    }
2487    if corners.is_empty() || corners.iter().any(|corner| corner.convex.len() != 1 || corner.concave.len() != 1) {
2488        return Err(shape("the open-pad composition is built for corners of one convex and one concave edge".into()));
2489    }
2490    let convexity = crate::blend::selection_convexity(solid, selected_ids, radius)
2491        .ok_or_else(|| shape("the selection's convexity could not be read edge by edge".into()))?;
2492    let concave: Vec<usize> = (0..selected_ids.len()).filter(|index| !convexity[*index]).collect();
2493    let convex: Vec<usize> = (0..selected_ids.len()).filter(|index| convexity[*index]).collect();
2494    if concave.is_empty() || convex.is_empty() {
2495        return Err(shape("the open-pad composition needs convex and concave edges".into()));
2496    }
2497    // Every concave edge ends at mixed corners (an open pad), and the face
2498    // the two edges share at each corner is planar.
2499    let mates = crate::blend::selection_mates(solid, selected_ids, radius)
2500        .map_err(|error| shape(format!("the selection's mates could not be read: {error}")))?;
2501    for corner in corners {
2502        let (_, convex_faces) = &mates[corner.convex[0]];
2503        let (_, concave_faces) = &mates[corner.concave[0]];
2504        let Some(shared) = convex_faces.iter().find(|face| concave_faces.iter().any(|other| other.id == face.id)) else {
2505            return Err(shape(format!("the two edges at vertex {} share no face", corner.vertex)));
2506        };
2507        if !matches!(shared.surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) {
2508            return Err(shape(format!("the face {} the edges share at vertex {} is not planar", shared.id, corner.vertex)));
2509        }
2510    }
2511    for &index in &concave {
2512        let edge = mates[index].0;
2513        for vertex in [edge.start_vertex_id, edge.end_vertex_id] {
2514            if !corners.iter().any(|corner| corner.vertex == vertex && corner.concave[0] == index) {
2515                return Err(shape(format!(
2516                    "concave {} does not end at a mixed corner at vertex {vertex}; the open-pad composition is built for pads that do",
2517                    selection_label(index, edge_points, edge_names, name)
2518                )));
2519            }
2520        }
2521    }
2522    let base = name.unwrap_or("FILLET:OPEN_PAD");
2523    let bare = |index: usize| -> String {
2524        per_edge_name(edge_names, name, index)
2525            .map(|composed| composed.strip_prefix(&format!("{base}:")).unwrap_or(composed).to_string())
2526            .unwrap_or_else(|| selected_ids[index].to_string())
2527    };
2528    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
2529
2530    // ---- Stage 1: the convex edges, as the group they are. ----
2531    let convex_points: Vec<Vec3> = convex.iter().map(|index| edge_points[*index]).collect();
2532    let convex_names: Vec<String> = convex
2533        .iter()
2534        .map(|index| per_edge_name(edge_names, name, *index).map(str::to_owned).unwrap_or_else(|| format!("{base}:WALL:{}", selected_ids[*index])))
2535        .collect();
2536    // Stage 1's body is an intermediate: the bowtie and soundness scans run
2537    // once, on stage 2's body (and the caller's acceptance after it), not on
2538    // a body the pads are about to change (1.2 s of tessellation on the
2539    // reported ring).
2540    // Both stages run as the open-pad composition's network
2541    // (`with_open_pad_network`: carrier-boundary stations, the march
2542    // extended to a section end outside the overshoot); no other network
2543    // takes those, so every body the plain network built stays as it was.
2544    let stage1 = crate::blend::with_open_pad_network(|| {
2545        fillet_edges_group_with_corner_policy(solid, &convex_points, Some(&convex_names), radius, false, name, None, true, false)
2546    })
2547    .map_err(|error| error.with_message(|error| format!("open-pad composition, the convex walls: {error}")))?;
2548    if debug {
2549        eprintln!("open-pad composition: stage 1 built the {} convex walls", convex.len());
2550    }
2551
2552    // ---- Stage 2: each pad with its trim continuations, on the stage-1 body. ----
2553    let uses = |face: &FaceRecord, edge_id: u64| face.loops.iter().flat_map(|l| &l.coedges).any(|c| c.edge_id == edge_id);
2554    let mut points: Vec<Vec3> = Vec::new();
2555    let mut names: Vec<String> = Vec::new();
2556    for &index in &concave {
2557        let (edge, faces) = &mates[index];
2558        let boss_id = if matches!(faces[0].surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) { faces[1].id } else { faces[0].id };
2559        let pad = stage1
2560            .edges
2561            .iter()
2562            .find(|candidate| candidate.id == edge.id)
2563            .ok_or_else(|| KernelRefusal::internal(KernelStage::Classify, "open_pad_edge", format!(
2564                "open-pad composition: concave edge {} vanished from the stage-1 body", edge.id
2565            )))?;
2566        points.push(pad.curve.evaluate(0.5 * (pad.t0 + pad.t1)).or_refuse(KernelStage::Collect, "pad_midpoint")?);
2567        names.push(per_edge_name(edge_names, name, index).map(str::to_owned).unwrap_or_else(|| format!("{base}:PAD:{}", edge.id)));
2568        // The trim continuations: at each end of the (trimmed) pad, the edge
2569        // that borders the boss and a stage-1 wall.
2570        for vertex in [pad.start_vertex_id, pad.end_vertex_id] {
2571            let trims: Vec<&EdgeRecord> = stage1
2572                .edges
2573                .iter()
2574                .filter(|candidate| {
2575                    candidate.id != pad.id
2576                        && !candidate.degenerate
2577                        && (candidate.start_vertex_id == vertex || candidate.end_vertex_id == vertex)
2578                })
2579                .filter(|candidate| {
2580                    let faces: Vec<&FaceRecord> = stage1.shells.iter().flat_map(|shell| &shell.faces).filter(|face| uses(face, candidate.id)).collect();
2581                    faces.iter().any(|face| face.id == boss_id)
2582                        && faces.iter().any(|face| face.name.as_deref().is_some_and(|value| convex_names.iter().any(|wall| wall == value)))
2583                })
2584                .collect();
2585            match trims.as_slice() {
2586                [trim] => {
2587                    let wall_name = stage1
2588                        .shells
2589                        .iter()
2590                        .flat_map(|shell| &shell.faces)
2591                        .filter(|face| uses(face, trim.id))
2592                        .find_map(|face| face.name.clone().filter(|value| convex_names.contains(value)))
2593                        .unwrap_or_default();
2594                    let wall_bare = wall_name.strip_prefix(&format!("{base}:")).unwrap_or(&wall_name).to_string();
2595                    points.push(trim.curve.evaluate(0.5 * (trim.t0 + trim.t1)).or_refuse(KernelStage::Collect, "trim_midpoint")?);
2596                    names.push(format!("{base}:RUNOUT:{}+{wall_bare}", bare(index)));
2597                    if debug {
2598                        eprintln!("open-pad composition: pad {} continues into trim edge {} (wall {wall_name}) at vertex {vertex}", edge.id, trim.id);
2599                    }
2600                }
2601                [] => {
2602                    return Err(KernelRefusal::unsupported(KernelStage::Classify, "open_pad_trim", format!(
2603                        "open-pad composition: at vertex {vertex} the concave {} meets no trim curve of a stage-1 wall on the boss",
2604                        selection_label(index, edge_points, edge_names, name)
2605                    )));
2606                }
2607                _ => {
2608                    return Err(KernelRefusal::unsupported(KernelStage::Classify, "open_pad_trim", format!(
2609                        "open-pad composition: at vertex {vertex} the concave {} meets {} trim curves",
2610                        selection_label(index, edge_points, edge_names, name), trims.len()
2611                    )));
2612                }
2613            }
2614        }
2615    }
2616    let result = crate::blend::with_open_pad_network(|| fillet_edges_group_in(&stage1, &points, Some(&names), radius, false, name, None))
2617        .map_err(|error| error.with_message(|error| format!("open-pad composition, the pads on the walls: {error}")))?;
2618    let _ = entry;
2619    Ok(result)
2620}
2621
2622/// The CUSP composition (2026-10-24/25 straight-sliver and cusp-chain reports): a
2623/// selection whose every mixed corner is a CUSP — a convex edge and a concave
2624/// edge leaving the vertex tangent to each other, the face they share
2625/// narrowing to zero width between them. The cusp-chain report selects the whole
2626/// of E6's start-face sliver outside F2's r 5 round: its two straight convex
2627/// edges run on G1 into the concave arc at both tips.
2628///
2629/// No other composition admits it: the pads of the open-pad composition
2630/// trim into the boss, and here both blends must TAPER to the tip, each
2631/// against the face the other leaves. Built in two stages, each an ordinary
2632/// group build, the order the straight-sliver report took by hand (F9, then F10):
2633///
2634/// 1. Every CONCAVE edge first: its round tapers to zero at each cusp
2635///    (`blend/taper_runout.rs`), leaving a hairline of the shared face
2636///    beside it.
2637/// 2. Every CONVEX edge on the stage-1 body: its round tapers to zero at the
2638///    same tips, with the width read against the stage-1 round's rail (the
2639///    face's boundary past the cusp line, `taper_runout::boundary_chain`).
2640///    The two rounds are G1 to the hairline between them.
2641fn cusp_composition(
2642    solid: &BrepSolid,
2643    selected_ids: &[u64],
2644    edge_points: &[Vec3],
2645    edge_names: Option<&[String]>,
2646    radius: f64,
2647    name: Option<&str>,
2648    corners: &[crate::blend::MixedCorner],
2649) -> Result<BrepSolid, KernelRefusal> {
2650    let shape = |message: String| KernelRefusal::unsupported(KernelStage::Classify, "cusp_composition_shape", message);
2651    if std::env::var("BREP_NO_NETWORK").is_ok() {
2652        return Err(shape("the cusp composition is a network construction and BREP_NO_NETWORK is set".into()));
2653    }
2654    let edge_of = |index: usize| solid.edges.iter().find(|edge| edge.id == selected_ids[index]);
2655    // The unit tangent leaving `vertex` into the edge.
2656    let away = |index: usize, vertex: u64| -> Option<Vec3> {
2657        let edge = edge_of(index)?;
2658        let at_start = edge.start_vertex_id == vertex;
2659        let tangent = edge.curve.unit_tangent(if at_start { edge.t0 } else { edge.t1 }, edge.t0, edge.t1).ok()?;
2660        Some(if at_start { tangent } else { tangent.scale(-1.0) })
2661    };
2662    if corners.is_empty() {
2663        return Err(shape("no mixed corners".into()));
2664    }
2665    for corner in corners {
2666        let cusped = corner.convex.iter().all(|&convex| {
2667            corner.concave.iter().any(|&concave| {
2668                matches!((away(convex, corner.vertex), away(concave, corner.vertex)), (Some(a), Some(b)) if a.dot(b) >= 1.0 - 1e-6)
2669            })
2670        });
2671        if !cusped || corner.convex.is_empty() || corner.concave.is_empty() {
2672            return Err(shape(format!("the mixed corner at vertex {} is not a cusp", corner.vertex)));
2673        }
2674    }
2675    let convexity = crate::blend::selection_convexity(solid, selected_ids, radius)
2676        .ok_or_else(|| shape("the selection's convexity could not be read edge by edge".into()))?;
2677    let concave: Vec<usize> = (0..selected_ids.len()).filter(|index| !convexity[*index]).collect();
2678    let convex: Vec<usize> = (0..selected_ids.len()).filter(|index| convexity[*index]).collect();
2679    if concave.is_empty() || convex.is_empty() {
2680        return Err(shape("the cusp composition needs convex and concave edges".into()));
2681    }
2682    let names_of = |indices: &[usize]| -> Option<Vec<String>> { edge_names.map(|names| indices.iter().map(|index| names[*index].clone()).collect()) };
2683    let points_of = |indices: &[usize]| -> Vec<Vec3> { indices.iter().map(|index| edge_points[*index]).collect() };
2684    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
2685    let stage1 = fillet_edges_group_in(solid, &points_of(&concave), names_of(&concave).as_deref(), radius, false, name, None)
2686        .map_err(|error| error.with_message(|error| format!("cusp composition, the concave rounds: {error}")))?;
2687    if debug {
2688        eprintln!("cusp composition: stage 1 built the {} concave rounds", concave.len());
2689    }
2690    // Each convex edge is read again on the stage-1 body by its point: the
2691    // taper split it only at its hairline's end, beside the tip.
2692    for &index in &convex {
2693        resolve_edge_by_point(&stage1, edge_points[index])
2694            .map_err(|error| error.with_message(|error| format!("cusp composition: a convex edge is not on the stage-1 body: {error}")))?;
2695    }
2696    let result = fillet_edges_group_in(&stage1, &points_of(&convex), names_of(&convex).as_deref(), radius, false, name, None)
2697        .map_err(|error| error.with_message(|error| format!("cusp composition, the convex rounds: {error}")))?;
2698    // Every round here tapers to zero at a tip, and the two rounds meet on
2699    // the hairline of the face between them: an edge's end stations stay ON
2700    // the skin (the concave arc's first tenth, where the convex round's
2701    // contact lands back on the arc), and the wall check reads the majority
2702    // of a tie, as it does for the runout composition's network ring.
2703    RUNOUT_RING_IS_NETWORK.with(|flag| flag.set(true));
2704    Ok(result)
2705}
2706
2707fn runout_composition(
2708    solid: &BrepSolid,
2709    selected_ids: &[u64],
2710    edge_points: &[Vec3],
2711    edge_names: Option<&[String]>,
2712    radius: f64,
2713    name: Option<&str>,
2714    corners: &[crate::blend::MixedCorner],
2715    entry: &str,
2716) -> Result<BrepSolid, KernelRefusal> {
2717    if std::env::var("BREP_NO_NETWORK").is_ok() {
2718        return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_no_network", "the runout composition is a network construction and BREP_NO_NETWORK is set"));
2719    }
2720    let convexity = crate::blend::selection_convexity(solid, selected_ids, radius)
2721        .ok_or(KernelRefusal::unsupported(KernelStage::Classify, "runout_convexity", "the selection's convexity could not be read edge by edge"))?;
2722    let mut spine_ends = vec![0usize; selected_ids.len()];
2723    for corner in corners {
2724        if corner.convex.len() != 1 {
2725            return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_corner_shape", format!(
2726                "the corner at ({:.3}, {:.3}, {:.3}) has {} convex edges; the runout is built for one convex edge dying into concave ones",
2727                corner.point.x, corner.point.y, corner.point.z, corner.convex.len()
2728            )));
2729        }
2730        spine_ends[corner.convex[0]] += 1;
2731    }
2732    let mut spines: Vec<usize> = Vec::new();
2733    let mut concave: Vec<usize> = Vec::new();
2734    for (index, ends) in spine_ends.iter().enumerate() {
2735        match (*ends, convexity[index]) {
2736            (2, true) => spines.push(index),
2737            (1, true) => spines.push(index),
2738            (0, false) => concave.push(index),
2739            (ends, convex) => {
2740                return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_selection_shape", format!(
2741                    "{} is {} and meets a mixed corner at {ends} of its ends; the runout is built for a convex edge running out at both ends among concave edges",
2742                    selection_label(index, edge_points, edge_names, name),
2743                    if convex { "convex" } else { "concave" },
2744                )));
2745            }
2746        }
2747    }
2748    if concave.is_empty() {
2749        return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_selection_shape", "no concave edges to build the ring from"));
2750    }
2751    // Stage 1: the ring, exactly as the concave edges build on their own.
2752    let ring_points: Vec<Vec3> = concave.iter().map(|index| edge_points[*index]).collect();
2753    let ring_names: Option<Vec<String>> = edge_names.map(|names| concave.iter().map(|index| names[*index].clone()).collect());
2754    LAST_NETWORK_REFUSAL.with(|last| *last.borrow_mut() = None);
2755    let ring = fillet_edges_group_with_corner_policy(solid, &ring_points, ring_names.as_deref(), radius, false, name, None, false, true)
2756        .map_err(|error| {
2757            LAST_NETWORK_REFUSAL.with(|last| last.borrow_mut().take());
2758            error.with_message(|error| format!("the concave ring did not build: {error}"))
2759        })?;
2760    // Whether the ring is the NETWORK's ring (no network refusal recorded).
2761    let network_declined = LAST_NETWORK_REFUSAL.with(|last| last.borrow_mut().take());
2762    // BREP lane L: begin walls_missing_tie_all_stations_20261015
2763    let ring_is_network = network_declined.is_none();
2764    // BREP lane L: end walls_missing_tie_all_stations_20261015
2765    // Stage 2: the runout walls on it.
2766    let spine_walls: Vec<(u64, Option<String>)> = spines
2767        .iter()
2768        .map(|index| (selected_ids[*index], per_edge_name(edge_names, name, *index).map(str::to_string)))
2769        .collect();
2770    let spine_ids: Vec<u64> = spine_walls.iter().map(|(id, _)| *id).collect();
2771    let mut result = crate::blend::build_runout_walls(&ring, &spine_walls, radius)?;
2772    heal_edge_vertex_gaps(&mut result, radius)?;
2773    crate::blend::fit_planar_charts_to_trims(&ring, &mut result)?;
2774    crate::blend::same_parameter_trims(&ring, &mut result);
2775    let issues = result.validate();
2776    if !issues.is_empty() {
2777        return Err(KernelRefusal::new(
2778            RefusalClass::InvalidResultTopology { issues: issues.len() as u32 },
2779            KernelStage::Validate,
2780            format!("the runout walls do not validate: {issues:?}"),
2781        ));
2782    }
2783    check_blend_interference(&ring, &result, &spine_ids, entry)?;
2784    check_loop_self_crossings(&result, entry)?;
2785    check_blend_wall_loops(&result, entry)?;
2786    crate::soundness::census::profile_operation(&result, &[solid], None, entry);
2787    let accepted = crate::accept_sound(result, entry)?;
2788    // BREP lane L: begin walls_missing_tie_all_stations_20261015
2789    RUNOUT_RING_IS_NETWORK.with(|flag| flag.set(ring_is_network));
2790    // BREP lane L: end walls_missing_tie_all_stations_20261015
2791    Ok(accepted)
2792}
2793
2794// BREP lane L: begin walls_missing_tie_all_stations_20261015
2795thread_local! {
2796    /// Set by a runout composition that SUCCEEDED on the network's ring (no
2797    /// network refusal recorded while its ring was built), and by a cusp
2798    /// composition that built (`cusp_composition`), read and cleared by the
2799    /// acceptance: only there does a tie take the majority.
2800    static RUNOUT_RING_IS_NETWORK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2801}
2802// BREP lane L: end walls_missing_tie_all_stations_20261015
2803
2804fn check_mixed_corner_convexity(
2805    solid: &BrepSolid,
2806    edge_ids: &[u64],
2807    edge_points: &[Vec3],
2808    edge_names: Option<&[String]>,
2809    radius: f64,
2810    name: Option<&str>,
2811    composition_error: Option<&KernelRefusal>,
2812) -> Result<(), KernelRefusal> {
2813    match crate::blend::mixed_convexity_corner(solid, edge_ids, radius) {
2814        Some(corner) => {
2815            // The refusal carries the RUNOUT's own numbers when they can be
2816            // measured — the station, the carrier pair, the stop and the pole
2817            // — so it says which construction is missing and where, not only
2818            // that the corner has none.  A measurement that fails leaves the
2819            // refusal exactly as it was: the corner is refused either way.
2820            let measured = match crate::blend::plan_runout(solid, edge_ids, radius, &corner) {
2821                Ok(plan) => Some(plan),
2822                Err(error) => {
2823                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
2824                        eprintln!("runout not measured: {error}");
2825                    }
2826                    None
2827                }
2828            };
2829            // "this kernel does not build that runout here": a named deferral,
2830            // carrying why the composition declined this selection.
2831            let mut message = mixed_corner_message(
2832                &corner,
2833                edge_points,
2834                edge_names,
2835                name,
2836                measured.as_ref(),
2837            );
2838            if let Some(error) = composition_error {
2839                message.push_str(&format!(" The runout composition was tried on this selection and refused: {error}"));
2840            }
2841            Err(KernelRefusal::unsupported(
2842                KernelStage::Classify,
2843                "mixed_corner_convexity",
2844                message,
2845            ))
2846        }
2847        None => Ok(()),
2848    }
2849}
2850
2851/// Refuse a selection one of whose edges keeps NO blend strip between the
2852/// corner balls at its two ends (see `degenerate_corner_setbacks`).
2853fn check_degenerate_corner_setbacks(
2854    solid: &BrepSolid,
2855    edge_ids: &[u64],
2856    edge_points: &[Vec3],
2857    edge_names: Option<&[String]>,
2858    radius: f64,
2859    name: Option<&str>,
2860) -> Result<(), KernelRefusal> {
2861    let Some(setback) = crate::blend::degenerate_corner_setbacks(solid, edge_ids, radius) else {
2862        return Ok(());
2863    };
2864    let [from, to] = setback.stops;
2865    let how = if setback.crossed {
2866        format!(
2867            "run {:.3e} PAST each other along it (the radius is beyond the limit)",
2868            setback.strip
2869        )
2870    } else {
2871        format!(
2872            "meet there ({:.3e} apart against a bar of {:.3e})",
2873            setback.strip, setback.bar
2874        )
2875    };
2876    // "The radius is at or past the degenerate limit … reduce it": a
2877    // parameter the geometry refuses, read at `Classify`.
2878    Err(KernelRefusal::input(
2879        KernelStage::Classify,
2880        "degenerate_corner_setbacks",
2881        format!(
2882            "fillet_edges: at r = {radius} the corner setbacks consume the whole of {} — the rolling \
2883             balls seated at its two corners touch face {} at ({:.4}, {:.4}, {:.4}) and ({:.4}, \
2884             {:.4}, {:.4}) and {how}, so no blend strip is left between them and the faces it lies \
2885             on are consumed whole. The radius is at or past the degenerate limit for this \
2886             selection; reduce it.",
2887            selection_label(setback.edge, edge_points, edge_names, name),
2888            setback.face_id,
2889            from.x,
2890            from.y,
2891            from.z,
2892            to.x,
2893            to.y,
2894            to.z,
2895        ),
2896    ))
2897}
2898
2899/// How a refusal names the `index`-th selected edge: its originating edge
2900/// name when the feature layer supplied one (with the feature's base prefix
2901/// stripped), else the picked point.
2902fn selection_label(
2903    index: usize,
2904    edge_points: &[Vec3],
2905    edge_names: Option<&[String]>,
2906    name: Option<&str>,
2907) -> String {
2908    let named = edge_names.and_then(|names| names.get(index)).map(|composed| match name {
2909        Some(base) => composed
2910            .strip_prefix(&format!("{base}:"))
2911            .unwrap_or(composed)
2912            .to_string(),
2913        None => composed.clone(),
2914    });
2915    named.unwrap_or_else(|| match edge_points.get(index) {
2916        Some(point) => format!("the edge at ({:.3}, {:.3}, {:.3})", point.x, point.y, point.z),
2917        None => format!("selection #{}", index + 1),
2918    })
2919}
2920
2921/// The refusal text for [`check_mixed_corner_convexity`], naming the edges the
2922/// way the user selected them (their originating edge names when the feature
2923/// layer supplied them, else the picked point).
2924fn mixed_corner_message(
2925    corner: &crate::blend::MixedCorner,
2926    edge_points: &[Vec3],
2927    edge_names: Option<&[String]>,
2928    name: Option<&str>,
2929    measured: Option<&crate::blend::RunoutPlan>,
2930) -> String {
2931    let label = |index: usize| selection_label(index, edge_points, edge_names, name);
2932    let list = |indices: &[usize]| -> String {
2933        let parts: Vec<String> = indices.iter().map(|index| label(*index)).collect();
2934        match parts.split_last() {
2935            None => "none".to_string(),
2936            Some((last, [])) => last.clone(),
2937            Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
2938        }
2939    };
2940    let mut message = format!(
2941        "fillet_edges: the selection mixes convexity at the corner ({:.3}, {:.3}, {:.3}) — convex \
2942         {} meets concave {} there. One rolling ball cannot touch the face they share from both \
2943         sides at once, so that corner has no closure: the convex blend runs out against the \
2944         concave ones partway along the edge, and this kernel does not build that runout yet. \
2945         Blending the concave edges in one fillet and the convex ones in another does not reach \
2946         a wall on every one of them either: the convex wall comes out at FULL length in either \
2947         order, and its contact leaves the faces it runs along where their own loops would then \
2948         cross. Blend the concave edges first and the blend acceptance refuses each convex edge \
2949         whose wall runs out into them; blend the convex ones first and the subset search drops \
2950         the concave edges it cannot compose instead, leaving those unfilleted.",
2951        corner.point.x,
2952        corner.point.y,
2953        corner.point.z,
2954        list(&corner.convex),
2955        list(&corner.concave),
2956    );
2957    // The runout, measured: where the ball's carriers switch, what they switch
2958    // to, and where the last stretch degenerates.  These are the numbers the
2959    // construction owes, so the refusal states them rather than leaving the
2960    // reader to derive them (`blend/runout.rs`).
2961    if let Some(plan) = measured {
2962        message.push_str(&format!(
2963            " Measured on this selection: the convex edge {}'s ball becomes tangent to face {} — \
2964             the face its two concave neighbours share — at s = {:.6} from the corner, centred \
2965             ({:.6}, {:.6}, {:.6}), where its contact on face {} reaches edge {}'s own rail \
2966             (ball-to-stripe residual {:.3e}). Past that station the second carrier is edge {}'s \
2967             STRIPE SURFACE, not a face of the input, and the march holds on it for {} \
2968             stations that fit rows reproducing their own contacts to {:.3e}. On the way the \
2969             kept mate's contact walks {:.3e} of a span off that face's own patch — into the \
2970             strip the concave stripe's pad ADDS to it — which is the shape, not an escape: \
2971             the bar a march is refused at is a full span.",
2972            plan.convex_edge,
2973            plan.shared_face,
2974            plan.station.s,
2975            plan.station.center.x,
2976            plan.station.center.y,
2977            plan.station.center.z,
2978            plan.replaced_mate,
2979            plan.second_carrier,
2980            plan.station.stripe_residual,
2981            plan.second_carrier,
2982            plan.marched,
2983            plan.fit_residual,
2984            plan.carrier_excursion,
2985        ));
2986        match (&plan.stop, plan.first_carrier) {
2987            (Some(stop), Some(first)) => message.push_str(&format!(
2988                " It does not simply stop there: at s = {:.6} the KEPT mate (face {}) runs out too \
2989                 — the ball's contact on it reaches edge {}'s rail, residual {:.3e} — so the FIRST \
2990                 carrier becomes that stripe as well and the last stretch rolls on two stripes.",
2991                stop.s, plan.kept_mate, first, stop.stripe_residual,
2992            )),
2993            _ => message.push_str(&format!(
2994                " Where the kept mate (face {}) runs out was not measurable on this selection.",
2995                plan.kept_mate
2996            )),
2997        }
2998        if let Some(pole) = plan.pole {
2999            message.push_str(&format!(
3000                " That stretch ends at a POLE, ({:.6}, {:.6}, {:.6}), where the two concave \
3001                 stripes' rails on face {} meet and the ball's two contacts merge, so the blend \
3002                 section shrinks to a point. Two carrier switches and a degenerate terminus is \
3003                 more than a stop station on a stripe, and none of it is composed yet.",
3004                pole.x, pole.y, pole.z, plan.shared_face,
3005            ));
3006        }
3007    }
3008    message
3009}
3010
3011/// All ways to choose `k` distinct indices from `0..n`, in lexicographic order.
3012fn index_combinations(n: usize, k: usize) -> Vec<Vec<usize>> {
3013    let mut out = Vec::new();
3014    if k == 0 || k > n {
3015        return out;
3016    }
3017    let mut idx: Vec<usize> = (0..k).collect();
3018    loop {
3019        out.push(idx.clone());
3020        // Advance to the next combination (like counting with carry).
3021        let mut i = k;
3022        loop {
3023            if i == 0 {
3024                return out;
3025            }
3026            i -= 1;
3027            if idx[i] != i + n - k {
3028                break;
3029            }
3030        }
3031        idx[i] += 1;
3032        for j in (i + 1)..k {
3033            idx[j] = idx[j - 1] + 1;
3034        }
3035    }
3036}
3037
3038thread_local! {
3039    /// Running count (per thread) of group builds that reached the CUTTER
3040    /// COMPOSITION — every network lane above it refused or was rejected.  A
3041    /// zero delta across a call is the witness that the network answered it;
3042    /// a face count or a volume cannot say which lane built a solid, since the
3043    /// cutter can build the same one.  Test-observable; not part of any result.
3044    pub static CUTTER_COMPOSITIONS: std::cell::Cell<u64> =
3045        const { std::cell::Cell::new(0) };
3046}
3047
3048thread_local! {
3049    /// The most edges the maximal-valid-subset search may drop on this
3050    /// thread; `None` searches every subset. Set by [`fillet_edges`] for its
3051    /// own call (lane F row 3, 2026-10-15): that entry refuses any partial
3052    /// selection, so the search there only words the refusal, and a search
3053    /// past one dropped edge cost lCount_125 117 s of booleans (112 subsets)
3054    /// to refuse what the drop-one level refuses in 11 s.
3055    static SUBSET_DROP_CAP: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
3056}
3057
3058/// Restores the previous [`SUBSET_DROP_CAP`] when the strict entry returns.
3059struct SubsetDropCap(Option<usize>);
3060
3061impl SubsetDropCap {
3062    fn set(cap: Option<usize>) -> Self {
3063        Self(SUBSET_DROP_CAP.with(|current| current.replace(cap)))
3064    }
3065}
3066
3067impl Drop for SubsetDropCap {
3068    fn drop(&mut self) {
3069        SUBSET_DROP_CAP.with(|current| current.set(self.0));
3070    }
3071}
3072
3073thread_local! {
3074    /// Running count (per thread) of [`fillet_edges_group_in`] builds, nested
3075    /// component builds included. Test-observable; not part of any result.
3076    pub static GROUP_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
3077    /// The network's last refusal in a group build on this thread, read
3078    /// back by the runout composition when its ring stage fails.
3079    static LAST_NETWORK_REFUSAL: std::cell::RefCell<Option<KernelRefusal>> = const { std::cell::RefCell::new(None) };
3080    /// The wall fold the network refused THIS group build's selection by,
3081    /// scoped to one [`fillet_edges_group_unchecked`] call (nested component
3082    /// builds save and restore it).
3083    static GROUP_NETWORK_FOLD: std::cell::RefCell<Option<KernelRefusal>> = const { std::cell::RefCell::new(None) };
3084}
3085
3086/// One component of a selection: its edge points (as bits, so the key is
3087/// exact) and its per-edge wall names.
3088type ComponentKey = (Vec<[u64; 3]>, Option<Vec<String>>);
3089
3090/// One step of the cutter composition's sequential build: the edge's
3091/// selection point (as bits), its wall name, the cutter's end pads (as bits)
3092/// and the composition lane (0 = general first, 1 = cutter first). The pads
3093/// and the lane are part of the key because both are read off the WHOLE
3094/// selection (its corners), so the same edge can take a different cutter in
3095/// a subset that drops a corner's third edge.
3096type SequentialKey = ([u64; 3], Option<String>, [u64; 2], u8);
3097
3098/// Component results of one [`fillet_edges_reported`] call, keyed by the chain
3099/// of components composed up to and including the one built. Valid only for
3100/// the solid, radius, chamfer flag and name of that call.
3101///
3102/// `sequential` is the same memo one level down, for a single connected
3103/// component: the evolving body of the cutter composition after each edge
3104/// blended, keyed by the chain of steps composed up to and including it. The
3105/// subset search's one-drop subsets of a connected selection mostly open
3106/// with the same edges in the same order, so without it every such subset
3107/// rebuilt the same cutter booleans before reaching the edge that refuses.
3108/// On the 2026-10-17 "fillet takes way too long" report (a 7-edge face ring
3109/// whose second edge refuses after the first edge's 6-8 s cutter boolean)
3110/// that boolean ran six times for one refusal: for the group and for the
3111/// five subsets that keep the first edge.
3112///
3113/// A one-drop subset of a connected ring can split it into two components
3114/// (the ring minus an edge that is not an end of a path), and the component
3115/// chains then differ from subset to subset while the cutter composition's
3116/// first steps do not; so the sequential memo is keyed by the chain of
3117/// components composed BEFORE the body being built (`prefix`, empty for a
3118/// single-component selection) together with the steps, and the component
3119/// builds carry the memo down instead of `None`. A FIRST component's steps
3120/// key under the empty prefix like a single-component selection's, which
3121/// is sound because both start from the same body: the component build
3122/// re-heals the selection's already healed input, and `heal_operands`
3123/// leaves a clean input byte-identical (its contract, stated at the heal
3124/// above; the cross-partition hits on the reported ring are its evidence).
3125#[derive(Default)]
3126struct ComponentMemo {
3127    built: std::collections::HashMap<Vec<ComponentKey>, Result<BrepSolid, KernelRefusal>>,
3128    /// The components composed before the build in progress, from the
3129    /// outermost selection down (set around each component build).
3130    prefix: Vec<ComponentKey>,
3131    sequential: std::collections::HashMap<
3132        (Vec<ComponentKey>, Vec<SequentialKey>),
3133        Result<BrepSolid, KernelRefusal>,
3134    >,
3135}
3136
3137/// [`fillet_edges_group_in`], with the subset search's component memo when
3138/// `memo` is `Some`. The search passes it on its own solid, and the component
3139/// builds pass it on down with `ComponentMemo::prefix` naming the components
3140/// composed before them (see `ComponentMemo::sequential`).
3141fn fillet_edges_group_in(
3142    solid: &BrepSolid,
3143    edge_points: &[Vec3],
3144    edge_names: Option<&[String]>,
3145    radius: f64,
3146    chamfer: bool,
3147    name: Option<&str>,
3148    memo: Option<&mut ComponentMemo>,
3149) -> Result<BrepSolid, KernelRefusal> {
3150    fillet_edges_group_with_corner_policy(solid, edge_points, edge_names, radius, chamfer, name, memo, true, true)
3151}
3152
3153fn fillet_edges_group_with_corner_policy(
3154    solid: &BrepSolid,
3155    edge_points: &[Vec3],
3156    edge_names: Option<&[String]>,
3157    radius: f64,
3158    chamfer: bool,
3159    name: Option<&str>,
3160    memo: Option<&mut ComponentMemo>,
3161    wrap_concave: bool,
3162    accept: bool,
3163) -> Result<BrepSolid, KernelRefusal> {
3164    GROUP_BUILDS.with(|count| count.set(count.get() + 1));
3165    let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
3166    let GroupBody { body: result, bowtie_clean } =
3167        fillet_edges_group_unchecked(solid, edge_points, edge_names, radius, chamfer, name, memo, wrap_concave)?;
3168    if !accept {
3169        return Ok(result);
3170    }
3171    // A body the network or the closed-rim lane already scanned clean and
3172    // handed up untouched is not scanned again (the scan is a pure function
3173    // of the body, 2026-10-12). The composite road and the cutter road hand
3174    // up bodies no lane scanned, and are scanned here.
3175    if bowtie_clean {
3176        crate::blend::record_count("count.bowtie.lane_scan_reused", 1);
3177    } else {
3178        check_loop_self_crossings(&result, entry)?;
3179        check_blend_wall_loops(&result, entry)?;
3180    }
3181    let soundness = crate::blend::BlendTimer::start("timing.soundness_ms");
3182    // The BODY's own soundness, beside the loop's. A blend wall is a FITTED
3183    // surface and a fit can carry two parameters of one wall to one point in
3184    // space — measured on `inbox-20260902-fillet-two-torus-box-edges`, whose
3185    // wall `F8:BLEND:Box_NZ|P.T5_Side[0]` does exactly that while `validate()`,
3186    // connectivity, Euler parity, the loop scan and the face-versus-face scan
3187    // are all silent. Two walls crossing each other is the same class and is
3188    // repaired where it can be. Neither is visible to a volume oracle, so a
3189    // result carrying one reports success for a different shape.
3190    crate::soundness::census::profile_operation(&result, &[solid], None, entry);
3191    let accepted = crate::accept_sound(result, entry);
3192    soundness.stop();
3193    accepted
3194}
3195
3196/// What the unchecked group lane hands up: the body, and whether a lane's
3197/// own acceptance already ran the bowtie scan on exactly this body and
3198/// found it clean (the network and closed-rim exits return the scanned
3199/// body unchanged; the composite and cutter exits do not scan).
3200struct GroupBody {
3201    body: BrepSolid,
3202    bowtie_clean: bool,
3203}
3204
3205/// [`fillet_edges_group_lanes`], answering a selection the network refused
3206/// by a WALL FOLD and the cutter composition then failed too by that fold,
3207/// not by the composition's own text: the fold is the reason, and the
3208/// composition's last cutter ("mates share their end boundary edge" on the
3209/// 2026-10-21 sculpted-cap report) names nothing the user can act
3210/// on. The fold keeps its class, so the subset search above stops on it.
3211fn fillet_edges_group_unchecked(
3212    solid: &BrepSolid,
3213    edge_points: &[Vec3],
3214    edge_names: Option<&[String]>,
3215    radius: f64,
3216    chamfer: bool,
3217    name: Option<&str>,
3218    memo: Option<&mut ComponentMemo>,
3219    wrap_concave: bool,
3220) -> Result<GroupBody, KernelRefusal> {
3221    let outer = GROUP_NETWORK_FOLD.with(|fold| fold.borrow_mut().take());
3222    let built = fillet_edges_group_lanes(solid, edge_points, edge_names, radius, chamfer, name, memo, wrap_concave);
3223    let fold = GROUP_NETWORK_FOLD.with(|fold| std::mem::replace(&mut *fold.borrow_mut(), outer));
3224    match (built, fold) {
3225        (Err(error), Some(fold)) if !crate::blend::is_wall_fold(&error) => Err(fold),
3226        (built, _) => built,
3227    }
3228}
3229
3230/// `BREP_FILLET_CONCAVE_FIRST_STAGES` (default on; `=0` restores the cutter
3231/// composition): a selection the network refuses for MIXED CONVEXITY whose
3232/// concave edges also meet each other at a corner no selected convex edge
3233/// reaches is built in two network stages, concave edges first.
3234///
3235/// Cause: a boss standing across a block's top edge, filleted along its base
3236/// (two vertical concave edges on the block's side, the concave arc on its
3237/// top) together with the boss's bottom face. The bottom corners are
3238/// re-entrant stars (one concave, two convex edges), which the network
3239/// refuses by convexity, so the WHOLE selection went to the sequential
3240/// cutter build; that build runs each concave cutter past the block's sharp
3241/// top edge and closes it with folded flat caps (a crease of 180 degrees)
3242/// instead of the miter the network builds where the two concave pads meet
3243/// over that edge.
3244/// The stage name a concave pad carries between the two stages of
3245/// [`concave_first_stages`], followed by its selection index.
3246const CONCAVE_FIRST_PAD: &str = "FILLET:CONCAVE_FIRST:";
3247
3248fn concave_first_stages_on() -> bool {
3249    switch!("BREP_FILLET_CONCAVE_FIRST_STAGES", true)
3250}
3251
3252/// One network stage of [`concave_first_stages`], under the acceptance the
3253/// group's own network result gets (heal, planar charts, validation,
3254/// interference, loop scans). `None` when the network refuses or the result
3255/// fails any check.
3256fn concave_first_network_stage(
3257    input: &BrepSolid,
3258    edge_ids: &[u64],
3259    network_names: &[Option<String>],
3260    corner_name: &dyn Fn(&[usize]) -> Option<String>,
3261    radius: f64,
3262    wrap_concave: bool,
3263) -> Option<BrepSolid> {
3264    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
3265    let mut body = match crate::blend::blend_star_network_with_corner_policy(
3266        input, edge_ids, radius, false, network_names, corner_name, wrap_concave,
3267    ) {
3268        Ok(body) => body,
3269        Err(refusal) => {
3270            if debug {
3271                eprintln!("concave-first stage on {edge_ids:?} refused: {refusal}");
3272            }
3273            return None;
3274        }
3275    };
3276    let entry = "fillet_edges";
3277    let healed = heal_edge_vertex_gaps(&mut body, radius);
3278    let charts = crate::blend::fit_planar_charts_to_trims(input, &mut body);
3279    crate::blend::same_parameter_trims(input, &mut body);
3280    let issues = body.validate_memoised();
3281    let interference = check_blend_interference(input, &body, edge_ids, entry);
3282    let bowtie = check_loop_self_crossings(&body, entry).and_then(|()| check_blend_wall_loops(&body, entry));
3283    if healed.is_ok() && charts.is_ok() && issues.is_empty() && interference.is_ok() && bowtie.is_ok() {
3284        return Some(body);
3285    }
3286    crate::blend::reject_wrapped_network();
3287    if debug {
3288        eprintln!(
3289            "concave-first stage on {edge_ids:?} rejected: heal={healed:?} charts={charts:?} issues={issues:?} \
3290             interference={interference:?} bowtie={bowtie:?}"
3291        );
3292    }
3293    None
3294}
3295
3296/// The two-stage build [`concave_first_stages_on`] describes: the concave
3297/// edges through the network on the input, then the convex edges through the
3298/// network on that body. Where a concave pad now separates two selected
3299/// convex edges that met it at a re-entrant star, the pad's own edge on their
3300/// shared face joins the second stage, so the star closes as one rounded run
3301/// (named as the star's corner) rather than with flat caps. `None` when the
3302/// selection is not of this shape or either stage fails: the caller's ladder
3303/// then goes on unchanged.
3304#[allow(clippy::too_many_arguments)]
3305fn concave_first_stages(
3306    solid: &BrepSolid,
3307    edge_points: &[Vec3],
3308    edge_names: Option<&[String]>,
3309    selected_edge_ids: &[u64],
3310    radius: f64,
3311    name: Option<&str>,
3312    wrap_concave: bool,
3313) -> Option<BrepSolid> {
3314    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
3315    let convex = crate::blend::selection_convexity(solid, selected_edge_ids, radius)?;
3316    let concave_indices: Vec<usize> = (0..convex.len()).filter(|&index| !convex[index]).collect();
3317    let convex_indices: Vec<usize> = (0..convex.len()).filter(|&index| convex[index]).collect();
3318    if concave_indices.is_empty() || convex_indices.is_empty() {
3319        return None;
3320    }
3321    let edge = |id: u64| solid.edges.iter().find(|edge| edge.id == id);
3322    let ends = |id: u64| edge(id).map(|edge| [edge.start_vertex_id, edge.end_vertex_id]);
3323    // The shape this answers: two concave edges meeting where no selected
3324    // convex edge ends (the miter the cutter build caps).
3325    let concave_corner = concave_indices.iter().enumerate().any(|(slot, &a)| {
3326        concave_indices[slot + 1..].iter().any(|&b| {
3327            let (Some(ends_a), Some(ends_b)) = (ends(selected_edge_ids[a]), ends(selected_edge_ids[b])) else {
3328                return false;
3329            };
3330            ends_a.iter().any(|vertex| {
3331                ends_b.contains(vertex)
3332                    && !convex_indices.iter().any(|&c| ends(selected_edge_ids[c]).is_some_and(|ends_c| ends_c.contains(vertex)))
3333            })
3334        })
3335    });
3336    if !concave_corner {
3337        return None;
3338    }
3339    let names_of = |indices: &[usize]| -> Vec<Option<String>> {
3340        indices.iter().map(|&index| per_edge_name(edge_names, name, index).map(str::to_string)).collect()
3341    };
3342    // Stage 1: the concave edges on the input. Each pad carries a stage name
3343    // of its own until the end, so finding a pad below never depends on the
3344    // names the caller supplied (or did not).
3345    let concave_ids: Vec<u64> = concave_indices.iter().map(|&index| selected_edge_ids[index]).collect();
3346    let stage_name = |index: usize| format!("{CONCAVE_FIRST_PAD}{index}");
3347    let concave_names: Vec<Option<String>> = concave_indices.iter().map(|&index| Some(stage_name(index))).collect();
3348    let concave_corner_name = |adjacent: &[usize]| {
3349        let members: Vec<usize> = adjacent.iter().map(|&slot| concave_indices[slot]).collect();
3350        corner_face_name(edge_names, name, &members)
3351    };
3352    let staged = concave_first_network_stage(solid, &concave_ids, &concave_names, &concave_corner_name, radius, wrap_concave)?;
3353    let original_faces: rustc_hash::FxHashSet<u64> =
3354        solid.shells.iter().flat_map(|shell| &shell.faces).map(|face| face.id).collect();
3355    let faces_of = |id: u64| -> Vec<&FaceRecord> {
3356        staged
3357            .shells
3358            .iter()
3359            .flat_map(|shell| &shell.faces)
3360            .filter(|face| face.loops.iter().flat_map(|rim| &rim.coedges).any(|coedge| coedge.edge_id == id))
3361            .collect()
3362    };
3363    // Stage 2: the convex edges, resolved on the staged body by their pick
3364    // points (a concave pad trims a convex edge at its end, never at the
3365    // point it was picked by).
3366    let mut stage_ids: Vec<u64> = Vec::with_capacity(convex_indices.len() + 2);
3367    let mut members: Vec<Vec<usize>> = Vec::with_capacity(convex_indices.len() + 2);
3368    for &index in &convex_indices {
3369        let id = resolve_edge_by_point(&staged, edge_points[index]).ok()?;
3370        // A pick that now lands on a pad (one made inside the stretch the pad
3371        // trimmed away) is not the convex edge it named.
3372        if stage_ids.contains(&id) || faces_of(id).iter().any(|face| !original_faces.contains(&face.id)) {
3373            return None;
3374        }
3375        stage_ids.push(id);
3376        members.push(vec![index]);
3377    }
3378    let staged_edge = |id: u64| staged.edges.iter().find(|edge| edge.id == id);
3379    let convex_count = stage_ids.len();
3380    for pad in &staged.edges {
3381        if pad.degenerate || stage_ids.contains(&pad.id) || pad.start_vertex_id == pad.end_vertex_id {
3382            continue;
3383        }
3384        let faces = faces_of(pad.id);
3385        if faces.len() != 2 {
3386            continue;
3387        }
3388        // One side is a stage-1 pad, named after the concave edge it rounds.
3389        let Some(concave_index) = faces.iter().find(|face| !original_faces.contains(&face.id)).and_then(|face| {
3390            concave_indices.iter().copied().find(|&index| face.name.as_deref() == Some(stage_name(index).as_str()))
3391        }) else {
3392            continue;
3393        };
3394        // Its two ends are ends of two DIFFERENT selected convex edges.
3395        let ender = |vertex: u64| {
3396            (0..convex_count).find(|&slot| {
3397                staged_edge(stage_ids[slot]).is_some_and(|edge| edge.start_vertex_id == vertex || edge.end_vertex_id == vertex)
3398            })
3399        };
3400        let (Some(first), Some(second)) = (ender(pad.start_vertex_id), ender(pad.end_vertex_id)) else {
3401            continue;
3402        };
3403        if first == second {
3404            continue;
3405        }
3406        // And the other side is a face both of those convex edges run along.
3407        let Some(other) = faces.iter().find(|face| original_faces.contains(&face.id)) else {
3408            continue;
3409        };
3410        let borders = |slot: usize| faces_of(stage_ids[slot]).iter().any(|face| face.id == other.id);
3411        if !borders(first) || !borders(second) {
3412            continue;
3413        }
3414        match super::analyze::scan_dihedral(&staged, pad.id) {
3415            Ok(profile) if profile.samples > 0 && profile.any_convex && !profile.any_concave => {}
3416            _ => continue,
3417        }
3418        let mut star = vec![concave_index, convex_indices[first], convex_indices[second]];
3419        star.sort_unstable();
3420        stage_ids.push(pad.id);
3421        members.push(star);
3422    }
3423    let mut stage_names = names_of(&convex_indices);
3424    stage_names.extend(members[convex_count..].iter().map(|star| corner_face_name(edge_names, name, star)));
3425    let stage_corner_name = |adjacent: &[usize]| {
3426        let mut flat: Vec<usize> = adjacent.iter().flat_map(|&slot| members[slot].iter().copied()).collect();
3427        flat.sort_unstable();
3428        flat.dedup();
3429        corner_face_name(edge_names, name, &flat)
3430    };
3431    let mut built = concave_first_network_stage(&staged, &stage_ids, &stage_names, &stage_corner_name, radius, wrap_concave)?;
3432    for face in built.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
3433        // The stage name, and anything a stage appended to it, back to the
3434        // pad's own name.
3435        let Some(tail) = face.name.as_deref().and_then(|value| value.strip_prefix(CONCAVE_FIRST_PAD)) else {
3436            continue;
3437        };
3438        let digits = tail.bytes().take_while(u8::is_ascii_digit).count();
3439        let Ok(index) = tail[..digits].parse::<usize>() else {
3440            return None;
3441        };
3442        let rest = tail[digits..].to_string();
3443        face.name = per_edge_name(edge_names, name, index).map(|own| format!("{own}{rest}"));
3444    }
3445    if debug {
3446        eprintln!(
3447            "concave-first stages: {} concave, {} convex and {} star pad edge(s) built",
3448            concave_ids.len(),
3449            convex_count,
3450            stage_ids.len() - convex_count
3451        );
3452    }
3453    Some(built)
3454}
3455
3456fn fillet_edges_group_lanes(
3457    solid: &BrepSolid,
3458    edge_points: &[Vec3],
3459    edge_names: Option<&[String]>,
3460    radius: f64,
3461    chamfer: bool,
3462    name: Option<&str>,
3463    mut memo: Option<&mut ComponentMemo>,
3464    wrap_concave: bool,
3465) -> Result<GroupBody, KernelRefusal> {
3466    use rustc_hash::FxHashSet as HashSet;
3467
3468    // Fuse-first operand heal (Lever A) before the multi-edge surgery: snap the
3469    // input's near-coincident / off-plane vertices (e.g. a revolve pole apex
3470    // sitting a few microns off the axis) to exact and re-anchor incident
3471    // edges.  The selected edges are resolved geometrically below, so a
3472    // sub-heal_tol vertex move never changes which edges are picked; a clean
3473    // input is left byte-identical.
3474    let heal = crate::blend::BlendTimer::start("timing.heal_operands_ms");
3475    let mut healed_input = solid.clone();
3476    let heal_policy = crate::KernelTolerances::for_solid(&healed_input, 1e-7);
3477    crate::heal::heal_operands(&mut healed_input, &heal_policy)?;
3478    let solid = &healed_input;
3479    heal.stop();
3480    let group_analysis = crate::blend::BlendTimer::start("timing.group_analysis_ms");
3481
3482    // 1. Detect convex corners from the ORIGINAL solid: a point that is an
3483    //    endpoint of >=3 of the selected edges (a cube/prism-style vertex).
3484    let mut endpoints: Vec<(Vec3, usize)> = Vec::with_capacity(edge_points.len() * 2);
3485    // The extent each selected edge has BEFORE any blend trims it, so the
3486    // sequential build can run every cutter through the shared corners.
3487    let mut original_extents: Vec<(Vec3, Vec3)> = Vec::with_capacity(edge_points.len());
3488    let mut selected_edge_ids: Vec<u64> = Vec::with_capacity(edge_points.len());
3489    for (i, point) in edge_points.iter().enumerate() {
3490        let edge_id = resolve_edge_by_point(solid, *point)?;
3491        let edge = solid
3492            .edges
3493            .iter()
3494            .find(|e| e.id == edge_id)
3495            .ok_or_else(|| {
3496                KernelRefusal::internal(
3497                    KernelStage::Collect,
3498                    "resolved_edge",
3499                    "fillet_edges: resolved edge vanished",
3500                )
3501            })?;
3502        let (start, end) = (
3503            edge.curve
3504                .evaluate(edge.t0)
3505                .or_refuse(KernelStage::Collect, "edge_start")?,
3506            edge.curve
3507                .evaluate(edge.t1)
3508                .or_refuse(KernelStage::Collect, "edge_end")?,
3509        );
3510        endpoints.push((start, i));
3511        endpoints.push((end, i));
3512        original_extents.push((start, end));
3513        selected_edge_ids.push(edge_id);
3514    }
3515    let mut corners: Vec<Vec3> = Vec::new();
3516    // The selected-edge INPUT INDICES meeting at each star corner (parallel to
3517    // `corners`), sorted — used to name the corner patch after its adjacent
3518    // edges (`{fid}:BLEND:CORNER:{e_a}+{e_b}+…`), UNIQUE per corner because no
3519    // two distinct corners share the same set of >=3 selected edges.
3520    let mut corner_edges: Vec<Vec<usize>> = Vec::new();
3521    let mut chain_corner_count = 0usize;
3522    let mut chain_corners: Vec<(Vec3, [usize; 2])> = Vec::new();
3523    let mut used = vec![false; endpoints.len()];
3524    for i in 0..endpoints.len() {
3525        if used[i] {
3526            continue;
3527        }
3528        used[i] = true;
3529        let mut edges_here: HashSet<usize> = HashSet::default();
3530        edges_here.insert(endpoints[i].1);
3531        for j in (i + 1)..endpoints.len() {
3532            if used[j] {
3533                continue;
3534            }
3535            if endpoints[i].0.sub(endpoints[j].0).length() < 1e-6 {
3536                used[j] = true;
3537                edges_here.insert(endpoints[j].1);
3538            }
3539        }
3540        if edges_here.len() >= 3 {
3541            corners.push(endpoints[i].0);
3542            let mut adjacent: Vec<usize> = edges_here.into_iter().collect();
3543            adjacent.sort_unstable();
3544            corner_edges.push(adjacent);
3545        } else if edges_here.len() == 2 {
3546            chain_corner_count += 1;
3547            let mut adjacent = edges_here.into_iter().collect::<Vec<_>>();
3548            adjacent.sort_unstable();
3549            chain_corners.push((endpoints[i].0, [adjacent[0], adjacent[1]]));
3550        }
3551    }
3552
3553    // A FACE selection may contain several disconnected boundary components
3554    // (the common example is an outer perimeter plus a circular hole rim).
3555    // Miter composition is only meaningful inside one connected edge graph.
3556    // Feeding every component into the same INTERSECT/UNION combines multiple
3557    // independently filleted copies of otherwise untouched support faces; the
3558    // boolean then imprints those coincident copies and can leave redundant
3559    // seams (the reported through-hole cylinder split into three faces).
3560    //
3561    // Partition by shared original endpoints and process components in input
3562    // order.  Each recursive call sees one connected component, so it follows
3563    // the existing miter/sequential path without recursion cycling.  Distinct
3564    // components are then composed sequentially on the evolving solid.
3565    let mut component_of = vec![usize::MAX; edge_points.len()];
3566    let mut components: Vec<Vec<usize>> = Vec::new();
3567    for seed in 0..edge_points.len() {
3568        if component_of[seed] != usize::MAX {
3569            continue;
3570        }
3571        let component_index = components.len();
3572        component_of[seed] = component_index;
3573        let mut component = vec![seed];
3574        let mut cursor = 0;
3575        while cursor < component.len() {
3576            let current = component[cursor];
3577            cursor += 1;
3578            for candidate in 0..edge_points.len() {
3579                if component_of[candidate] != usize::MAX {
3580                    continue;
3581                }
3582                let connected = [original_extents[current].0, original_extents[current].1]
3583                    .into_iter()
3584                    .any(|a| {
3585                        [original_extents[candidate].0, original_extents[candidate].1]
3586                            .into_iter()
3587                            .any(|b| a.sub(b).length() < 1e-6)
3588                    });
3589                if connected {
3590                    component_of[candidate] = component_index;
3591                    component.push(candidate);
3592                }
3593            }
3594        }
3595        component.sort_unstable();
3596        components.push(component);
3597    }
3598    group_analysis.stop();
3599    if components.len() > 1 {
3600        let mut separated = solid.clone();
3601        // The chain continues the memo's prefix, so a component composed
3602        // inside another's build keys under the whole path to it.
3603        let mut chain: Vec<ComponentKey> = memo.as_deref().map(|memo| memo.prefix.clone()).unwrap_or_default();
3604        chain.reserve(components.len());
3605        for component in components {
3606            let points = component
3607                .iter()
3608                .map(|index| edge_points[*index])
3609                .collect::<Vec<_>>();
3610            let names = edge_names.map(|all| {
3611                component
3612                    .iter()
3613                    .map(|index| all[*index].clone())
3614                    .collect::<Vec<_>>()
3615            });
3616            let Some(memo) = memo.as_deref_mut() else {
3617                separated = fillet_edges_group_with_corner_policy(
3618                    &separated,
3619                    &points,
3620                    names.as_deref(),
3621                    radius,
3622                    chamfer,
3623                    name,
3624                    None,
3625                    wrap_concave,
3626                    false,
3627                )?;
3628                continue;
3629            };
3630            let bits = points.iter().map(|p| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]);
3631            chain.push((bits.collect(), names.clone()));
3632            let built = match memo.built.get(&chain) {
3633                Some(built) => built.clone(),
3634                None => {
3635                    // The component builds on the body the chain before it
3636                    // composed: its own cutter steps key under that chain.
3637                    let outer_prefix = std::mem::replace(&mut memo.prefix, chain[..chain.len() - 1].to_vec());
3638                    let built = fillet_edges_group_with_corner_policy(
3639                        &separated,
3640                        &points,
3641                        names.as_deref(),
3642                        radius,
3643                        chamfer,
3644                        name,
3645                        Some(&mut *memo),
3646                        wrap_concave,
3647                        false,
3648                    );
3649                    memo.prefix = outer_prefix;
3650                    memo.built.insert(chain.clone(), built.clone());
3651                    built
3652                }
3653            };
3654            separated = built?;
3655        }
3656        return Ok(GroupBody { body: separated, bowtie_clean: false });
3657    }
3658
3659    // 2a. The stripe network (blend/network.rs) is the lane for EVERY
3660    //     selection: each stripe is marched against THIS solid, each shared
3661    //     vertex is solved before anything is cut — a star closed by a patch
3662    //     of the corner ball, a two-edge corner by the seam between the two
3663    //     blends, a re-entrant corner by a horn torus, a tangent pair by a
3664    //     flush join, an unselected tangent continuation by a cap — and
3665    //     nothing is subtracted, so no cutter can overshoot into a neighbour
3666    //     and no leftover cap has to be identified afterwards.  It refuses
3667    //     BY NAME on what it does not yet construct (mixed-convexity corners,
3668    //     no-common-ball stars, pinched edges), and those fall through to the
3669    //     cutter composition below.
3670    //
3671    //     A CLOSED edge is one of those refusals and it has an answer the
3672    //     network is simply not the lane for: a closed rim has no corner to
3673    //     share, so `blend_star_network` says "edge N is closed and has no
3674    //     corner to share" and the composition took it.  `blend_closed_edge`
3675    //     builds exactly that case and the single-edge ladder in `tool.rs`
3676    //     has always tried it first — but this function reached only the
3677    //     network, so a closed rim inside a GROUP went to a cutter that the
3678    //     same rim selected on its own never saw.  A bored hole's rim splits
3679    //     out as its own one-edge component (see the component partition
3680    //     above), so that was every hole rim chamfered as part of a face
3681    //     selection.  Try it here too, under the same acceptance the network
3682    //     result gets, and under the same `BREP_NO_NETWORK` A/B.
3683    if std::env::var("BREP_NO_NETWORK").is_err() {
3684        if selected_edge_ids.len() == 1 {
3685            let edge_id = selected_edge_ids[0];
3686            let closed = solid
3687                .edges
3688                .iter()
3689                .find(|edge| edge.id == edge_id)
3690                .is_some_and(|edge| edge.start_vertex_id == edge.end_vertex_id);
3691            if closed {
3692                let rim_name = per_edge_name(edge_names, name, 0);
3693                match crate::blend::blend_closed_edge(solid, edge_id, radius, chamfer, rim_name) {
3694                    Ok(mut rim) => {
3695                        let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
3696                        let heal = crate::blend::BlendTimer::start("timing.heal_vertex_gaps_ms");
3697                        let healed = heal_edge_vertex_gaps(&mut rim, radius);
3698                        heal.stop();
3699                        // A trim the surgery ran outside its planar carrier's
3700                        // chart is a wrong body the three checks below all pass
3701                        // (`crate::blend::fit_planar_charts_to_trims`), so the
3702                        // carrier is widened here, after the heal has settled
3703                        // the edges the trims are rebuilt from and before the
3704                        // bowtie scan reads them.  Its refusals are TERMINAL:
3705                        // the composition is not a second opinion on a body
3706                        // whose trims left their carrier.
3707                        let charts = crate::blend::BlendTimer::start("timing.planar_charts_ms");
3708                        crate::blend::fit_planar_charts_to_trims(solid, &mut rim)?;
3709                        charts.stop();
3710                        let validate = crate::blend::BlendTimer::start("timing.validate_ms");
3711                        let issues = rim.validate_memoised();
3712                        validate.stop();
3713                        let interference =
3714                            check_blend_interference(solid, &rim, &selected_edge_ids, entry);
3715                        let bowtie = check_loop_self_crossings(&rim, entry).and_then(|()| check_blend_wall_loops(&rim, entry));
3716                        if healed.is_ok()
3717                            && issues.is_empty()
3718                            && interference.is_ok()
3719                            && bowtie.is_ok()
3720                        {
3721                            return Ok(GroupBody { body: rim, bowtie_clean: true });
3722                        }
3723                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3724                            eprintln!(
3725                                "closed-rim result rejected: heal={healed:?} issues={issues:?} \
3726                                 interference={interference:?} bowtie={bowtie:?}"
3727                            );
3728                        }
3729                    }
3730                    Err(refusal) => {
3731                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3732                            eprintln!("closed-rim refused: {refusal}");
3733                        }
3734                    }
3735                }
3736            }
3737        }
3738        let network_names: Vec<Option<String>> = (0..edge_points.len())
3739            .map(|index| per_edge_name(edge_names, name, index).map(str::to_string))
3740            .collect();
3741        let network_corner_name =
3742            |adjacent: &[usize]| corner_face_name(edge_names, name, adjacent);
3743        // BREP lane L: begin lcount229_knot_aware_group_network_20261016 A
3744        // support pcurve off the floor ends the group's network here, and
3745        // the ladder would go on to the cutter composition: re-run the
3746        // network ONCE with the knot-aware support fit; a re-run that also
3747        // fails keeps the first refusal.
3748        let group_network = || {
3749            crate::blend::blend_star_network_with_corner_policy(
3750                solid,
3751                &selected_edge_ids,
3752                radius,
3753                chamfer,
3754                &network_names,
3755                &network_corner_name,
3756                wrap_concave,
3757            )
3758        };
3759        let network_result = group_network().or_else(|first| {
3760            if crate::blend::is_pcurve_floor_refusal(&first) {
3761                crate::blend::with_pcurve_knot_retry(group_network).map_err(|_| first)
3762            } else {
3763                Err(first)
3764            }
3765        });
3766        // BREP lane L: end lcount229_knot_aware_group_network_20261016
3767        // The network's result under its acceptance: `Ok(Some)` accepted,
3768        // `Ok(None)` rejected (the ladder goes on), `Err` terminal.
3769        let accept_network = |mut network: BrepSolid, built_radius: f64| -> Result<Option<GroupBody>, KernelRefusal> {
3770                // Fail-safe like the rest of the ladder: a heal or validation
3771                // problem in the network result falls through to the cutter,
3772                // it does not fail the group.  So does an UNTRIMMED result: the
3773                // network re-trims only each stripe's two mates, and
3774                // `check_blend_interference` is what notices a third face
3775                // crossing the swept volume -- `validate` cannot, because a
3776                // self-intersecting solid is still a watertight one.
3777                let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
3778                let heal = crate::blend::BlendTimer::start("timing.heal_vertex_gaps_ms");
3779                let healed = heal_edge_vertex_gaps(&mut network, built_radius);
3780                heal.stop();
3781                // See the closed-rim lane above: widen a planar carrier the
3782                // surgery overran, or refuse — terminally — rather than fall
3783                // through to a composition that cannot answer that question.
3784                let charts = crate::blend::BlendTimer::start("timing.planar_charts_ms");
3785                crate::blend::fit_planar_charts_to_trims(solid, &mut network)?;
3786                charts.stop();
3787                let validate = crate::blend::BlendTimer::start("timing.validate_ms");
3788                let issues = network.validate_memoised();
3789                validate.stop();
3790                let interference =
3791                    check_blend_interference(solid, &network, &selected_edge_ids, entry);
3792                // And the fourth question, which the other three all pass: does
3793                // any face of the result have a loop that crosses ITSELF? A
3794                // wall whose rail ran off its own face comes back as a bowtie,
3795                // and a bowtie is watertight, incident and connected.
3796                let bowtie = check_loop_self_crossings(&network, entry).and_then(|()| check_blend_wall_loops(&network, entry));
3797                if healed.is_ok() && issues.is_empty() && interference.is_ok() && bowtie.is_ok() {
3798                    return Ok(Some(GroupBody { body: network, bowtie_clean: true }));
3799                }
3800                crate::blend::reject_wrapped_network();
3801                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3802                    eprintln!(
3803                        "network result rejected: heal={healed:?} issues={issues:?} \
3804                         interference={interference:?} bowtie={bowtie:?}"
3805                    );
3806                    dump_loops_debug("INPUT", solid);
3807                    dump_loops_debug("RESULT", &network);
3808                }
3809                Ok(None)
3810        };
3811        match network_result {
3812            Ok(network) => {
3813                if let Some(body) = accept_network(network, radius)? {
3814                    return Ok(body);
3815                }
3816            }
3817            Err(refusal) => {
3818                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3819                    eprintln!("network refused: {refusal}");
3820                }
3821                // A mixed-convexity refusal over a selection whose concave
3822                // edges also miter each other: build them first, then the
3823                // convex edges (`concave_first_stages_on`).
3824                let mixed = matches!(&refusal.class, RefusalClass::UnsupportedGeometry { what } if what == "mixed_convexity");
3825                if !chamfer && mixed && concave_first_stages_on() {
3826                    if let Some(body) = concave_first_stages(
3827                        solid, edge_points, edge_names, &selected_edge_ids, radius, name, wrap_concave,
3828                    ) {
3829                        return Ok(GroupBody { body, bowtie_clean: true });
3830                    }
3831                }
3832                // A stripe whose TAPER to a cusp reaches its full radius only
3833                // inside the corner setback at its other end has no constant
3834                // run at all (the straight-sliver report's F10, 2026-10-24: r 1 on the two
3835                // straight edges of a sliver at most 2 wide within 0.9 of its
3836                // square corner). The round is built at the largest smaller
3837                // radius whose taper clears the setback, and says so, as the
3838                // relief says it over a whole rim. Before 2026-10-26 the group
3839                // fell through to the cutter composition, which closed each
3840                // round on a web and a cap under the neighbouring blend (an
3841                // undercut) in 9 minutes.
3842                let pinched_taper = matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what }
3843                    if what == crate::blend::STRIPE_PINCH_TAPER_WHAT);
3844                if !chamfer && pinched_taper && crate::blend::relief::radius_relief_on() {
3845                    let labels: Vec<String> =
3846                        (0..edge_points.len()).map(|index| selection_label(index, edge_points, edge_names, name)).collect();
3847                    for step in 1..=10u32 {
3848                        let reduced = radius * (1.0 - 0.05 * f64::from(step));
3849                        let built = crate::blend::blend_star_network_with_corner_policy(
3850                            solid, &selected_edge_ids, reduced, chamfer, &network_names, &network_corner_name, wrap_concave,
3851                        );
3852                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3853                            eprintln!(
3854                                "taper pinch ladder: r {reduced:.4} -> {}",
3855                                match &built {
3856                                    Ok(_) => "built".to_string(),
3857                                    Err(error) => format!("refused: {error}"),
3858                                }
3859                            );
3860                        }
3861                        match built {
3862                            Ok(network) => {
3863                                let Some(body) = accept_network(network, reduced)? else { break };
3864                                crate::blend::record_blend_note(format!(
3865                                    "radius reduced over the whole of {} to {reduced:.4}: at r {radius} the round tapering to \
3866                                     its tip reaches the full radius only inside the corner setback at its other end, so \
3867                                     r {radius} is reached nowhere",
3868                                    labels.join(", ")
3869                                ));
3870                                return Ok(body);
3871                            }
3872                            Err(again) if matches!(&again.class, crate::RefusalClass::UnsupportedGeometry { what }
3873                                if what == crate::blend::STRIPE_PINCH_TAPER_WHAT) => continue,
3874                            Err(_) => break,
3875                        }
3876                    }
3877                }
3878                // Independent stripe cutters cannot close a corner whose ball
3879                // exceeds the canal footprint. Preserve the requested radius
3880                // and its named refusal instead of searching partial selections.
3881                if matches!(&refusal.class, RefusalClass::UnsupportedGeometry { what }
3882                    if what == "canal_footprint_bound") || crate::blend::is_ball_does_not_fit(&refusal) {
3883                    return Err(refusal);
3884                }
3885                // The runout composition reads the ring's own classification
3886                // back when the ring stage falls through to the cutter and
3887                // that refuses too (`LAST_NETWORK_REFUSAL`).
3888                LAST_NETWORK_REFUSAL.with(|last| *last.borrow_mut() = Some(refusal.clone()));
3889                if crate::blend::is_wall_fold(&refusal) {
3890                    GROUP_NETWORK_FOLD.with(|fold| *fold.borrow_mut() = Some(refusal.clone()));
3891                }
3892                // A refusal that is not a fold where the ball does not fit
3893                // (the rounded-outline report at r 1.0, a ball the size of the round it
3894                // rides: its centre curve collapses to a point and the station
3895                // Newton is singular) is the fold the relief answers, not a
3896                // question for the composition, which took 143 s over it.
3897                if !chamfer && !crate::blend::is_wall_fold(&refusal) && crate::blend::relief::radius_relief_on() {
3898                    let started = web_time::Instant::now();
3899                    let misfit = crate::blend::relief::first_misfit(solid, &selected_edge_ids, radius);
3900                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3901                        eprintln!("radius relief: misfit probe {misfit:?} in {:.1} ms", started.elapsed().as_secs_f64() * 1e3);
3902                    }
3903                    if let Some((edge_id, least)) = misfit {
3904                        return Err(crate::blend::relief::misfit_fold(edge_id, least, radius, &refusal));
3905                    }
3906                }
3907                // The fail-safe above is for a refusal that says "not this
3908                // lane".  A marched fit that left its carriers does not say
3909                // that, and the cutter's answer to the same selection is not a
3910                // second opinion on it: on the notched cap's stuck connector
3911                // the composition reads 1724.506048919, +1.81e-2 against the
3912                // closed form, and it VALIDATES.  A refusal that falls through
3913                // to a validating wrong solid is not a refusal.
3914                //
3915                // Not every WALL FOLD, though the single-edge tool reads them all
3916                // as terminal (`is_terminal_blend_refusal`): a fold of the lens
3917                // between the rails is one the composition's cutter carves
3918                // (`inbox_20260902_corner_torus_collar_fillet::each_collar_has_its_own_fold_threshold`,
3919                // the r 2.1 collar at fold factor 1.036). One that reaches a
3920                // RAIL is not: the ball pokes out through the face it rides,
3921                // there is no lens to carve, and every cutter sweeps the same
3922                // envelope. Until 2026-10-21 the group fell through on that too:
3923                // the rounded-outline report's end face at r 1.7 around an r 1 round on its
3924                // outline ran the composition and its subset search for over 20
3925                // minutes. A lens fold the composition cannot rescue either is
3926                // answered by the fold (`fillet_edges_group_unchecked`).
3927                //
3928                // A blend stopping within a sliver of its face's width that
3929                // cannot be snapped onto the far edge without opening the shell
3930                // is terminal for the same reason: the SIZE is the question
3931                // (`blend::CONSUMED_SNAP_UNSOUND`), and the composition's tool
3932                // cut a sliver short of an edge leaves the sliver no lane keeps.
3933                //
3934                // And a FULL-WIDTH corner the network cannot collapse soundly
3935                // (`blend::RAIL_COLLAPSE_UNSUPPORTED`,
3936                // `blend::FULL_WIDTH_COLLAPSE_UNSOUND`): the composition's answer
3937                // to a full-width corner was measured wrong — a 5F/8E/5V miter
3938                // 8.0e-4 off its closed form at 1e-5 short of the width, and the
3939                // picture-frame corner at a full-width chamfer star.
3940                //
3941                // And a trim that left its planar carrier's chart
3942                // (`blend::PLANAR_CHART_EDGE_OFF_PLANE`,
3943                // `blend::PLANAR_CHART_WIDEN_UNSOUND`): the clamped body the
3944                // composition would answer with is the defect being refused.
3945                // A tangential end whose taper could not be planned also has
3946                // no supported closure for cutter composition to recover.
3947                if crate::blend::is_rail_fold(&refusal)
3948                    || crate::blend::is_marched_fit_off_carriers(&refusal)
3949                    || crate::blend::is_consumed_snap(&refusal)
3950                    || crate::blend::is_rail_collapse(&refusal)
3951                    || crate::blend::is_full_width_collapse(&refusal)
3952                    || crate::blend::is_planar_chart_refusal(&refusal)
3953                    || crate::blend::is_miter_support_overrun(&refusal)
3954                    || crate::blend::is_tangential_transverse_end(&refusal)
3955                {
3956                    return Err(refusal);
3957                }
3958            }
3959        }
3960    }
3961
3962    // An edge whose ball reaches its support only by rolling over a tangent
3963    // neighbour (`analyze::rollover_only_refusal`): the composition's tool
3964    // rides the mates' own carriers past the tangent edge and fills over air
3965    // (lCount_409 at r 2: +1.096 against the quadrature's 1103.315046), so
3966    // the reach refusal the unsigned check gave stands.
3967    if let Some(refusal) = super::analyze::rollover_only_refusal(&selected_edge_ids) {
3968        return Err(refusal);
3969    }
3970    CUTTER_COMPOSITIONS.with(|count| count.set(count.get() + 1));
3971    crate::blend::record_count("count.cutter_fallback", 1);
3972    let _cutter = crate::blend::BlendTimer::start("timing.cutter_ms");
3973    // 2. Build the blends.
3974    //
3975    //    CHAIN corners (§6.9.6 — exactly TWO selected edges share a vertex):
3976    //    the sequential build truncates the later blend where it runs into the
3977    //    earlier one and closes it with a flat bulkhead across the fillet
3978    //    channel — a hard step, not a transition.  For selections containing
3979    //    chain corners, blend each edge FULL-LENGTH on the ORIGINAL solid and
3980    //    INTERSECT the per-edge results instead: the removal volumes union, so
3981    //    adjacent blends run through the shared corner and trim each other
3982    //    along their intersection curve — the standard MITER corner, tangent
3983    //    to the shared face at the seam's tangency end.  Non-adjacent edges
3984    //    are unaffected (their removals are disjoint, intersection ≡
3985    //    sequential).
3986    //
3987    //    Selections without chain corners keep the sequential build unchanged
3988    //    (star corners are rounded in step 3 against exactly the sequential
3989    //    geometry round_convex_corner was built for).
3990    //    CONVEXITY GUARD: a convex blend REMOVES material (fillet = orig −
3991    //    cut), a concave blend ADDS it (orig + pad).  Full-length blends
3992    //    combine as orig − ∪cuts + ∪pads, so the per-edge results compose by
3993    //    INTERSECTION when every edge is convex and by UNION when every edge
3994    //    is concave; a mixed selection has no single composition and falls
3995    //    back to the sequential build.
3996    // Fillet stars keep the sequential topology required by their sphere
3997    // patches. Chamfer stars have no subsequent corner patch: compose their
3998    // full-length removals too, so all bevel planes meet at the corner.
3999    let miter_operation = if (chain_corner_count > 0 || !corners.is_empty())
4000        && (chamfer || corners.is_empty())
4001    {
4002        let mut any_convex = false;
4003        let mut any_concave = false;
4004        for point in edge_points {
4005            // Convexity is a DIHEDRAL property, so it is read from the general
4006            // scan (`scan_dihedral`) — the same one `check_mixed_concavity`
4007            // has already run over every selected edge.  `analyze_edge` used
4008            // to answer here and it ALSO refuses an edge the EXACT CUTTER
4009            // cannot build: a straight edge whose mates are not both planes,
4010            // a circular one whose mates do not share its axis.  Reading that
4011            // refusal as "unknown convexity" dropped the §6.9.6 miter for
4012            // every selection touching a curved carrier — the groove rim of a
4013            // bored box, say — and the sequential build then left a bulkhead
4014            // face standing in the shared corner (the 2026-09-10 "chamfer
4015            // produced a spurious face" report).
4016            match resolve_edge_by_point(solid, *point)
4017                .and_then(|edge_id| super::analyze::scan_dihedral(solid, edge_id))
4018            {
4019                // A mixed edge has no single composition either; it takes the
4020                // `_ => None` arm below through both flags.
4021                Ok(profile) if profile.samples > 0 && !profile.is_mixed() => {
4022                    any_convex |= profile.any_convex;
4023                    any_concave |= profile.any_concave;
4024                }
4025                // Unknown edge class: let the sequential path produce its own
4026                // (more specific) error or result.
4027                _ => {
4028                    any_convex = true;
4029                    any_concave = true;
4030                    break;
4031                }
4032            }
4033        }
4034        match (any_convex, any_concave) {
4035            (true, false) => Some(crate::BooleanOperation::Intersect),
4036            (false, true) => Some(crate::BooleanOperation::Union),
4037            _ => None,
4038        }
4039    } else {
4040        None
4041    };
4042
4043    // Fillet/chamfer each edge in turn, resolving its point on the evolving
4044    // solid (ids shift as earlier fillets rewrite topology; the midpoint of an
4045    // edge is untouched by the corner surgery of the others).  This is the
4046    // baseline build used directly for non-miter selections AND as the
4047    // fallback when the miter composition below cannot reassemble.
4048    // The composition's per-edge lane: cutter-first ONLY when a corner
4049    // closure will run afterwards and read cutter-shaped topology (a star or
4050    // a chain corner).  A selection with no shared vertex — a lone closed
4051    // rim, a lone chamfer, disconnected edges — has no such closure, so each
4052    // edge gets the march first there too.
4053    let composition_lane = if corners.is_empty() && chain_corner_count == 0 {
4054        Lane::GeneralFirst
4055    } else {
4056        Lane::CutterFirst
4057    };
4058    // The order the sequential build blends the selection in: the input
4059    // order, except that a CONCAVE edge ending at a star corner goes before
4060    // every convex edge (`sequential_build_order`). The §6.9.7 torus-sector
4061    // closure of a re-entrant vertex whose concave edge is selected too
4062    // (`round_mixed_concave_corner`) reads the concave blend's tangency
4063    // vertices off the convex cap cutters, so it exists only when the concave
4064    // edge was cut FIRST; a user who picks the keyway's rim and then its
4065    // inner corners (the 2026-10-13 sprocket report) got flat caps at both
4066    // corners from the input order, and the closure's own closed form from
4067    // this one. Every other selection keeps its input order, byte for byte.
4068    let concave_at_star = concave_star_edges(solid, &selected_edge_ids, &corner_edges, radius, chamfer);
4069    // And at a star corner whose edges the ladder answers with DIFFERENT
4070    // cutters, the marched edges go before the exact ones and the revolved
4071    // cutters last (`mixed_star_class_ranks`): the 2026-10-13 sprocket
4072    // report whose slit walls were selected as faces.
4073    let class_ranks = mixed_star_class_ranks(solid, &selected_edge_ids, &corner_edges, radius, chamfer);
4074    let sequential_order = sequential_build_order(edge_points.len(), &concave_at_star, &class_ranks);
4075    // And the corners close in the same precedence: a star with a concave
4076    // edge (the torus sector) before the convex stars, which on the report's
4077    // keyway share a 3.8-long rim edge with it — the convex star's surgery
4078    // read an open edge when it ran first (measured 2026-10-13), and closes
4079    // cleanly after the sector has trimmed that rim.
4080    let (corners, corner_edges) = corners_concave_first(corners, corner_edges, &concave_at_star);
4081    let mut build_sequential = || -> Result<BrepSolid, KernelRefusal> {
4082        let mut sequential = solid.clone();
4083        // The prefix chain of this build, for the subset search's memo (see
4084        // `ComponentMemo::sequential`); unused without one.
4085        let mut chain: Vec<SequentialKey> = Vec::with_capacity(sequential_order.len());
4086        for &index in &sequential_order {
4087            let point = &edge_points[index];
4088            let edge_id = resolve_edge_by_point(&sequential, *point)?;
4089            // Earlier cutters in this loop TRIM the edges that share a corner
4090            // with them; extend this cutter back over what they took so the
4091            // two removal volumes union through the corner (§6.9.6 miter)
4092            // instead of leaving a wedge of material standing behind a flush
4093            // end cap.  Untouched edges get a zero pad and the historical
4094            // flush cutter.
4095            let ends = tool_ends_to_original_extent(
4096                &sequential,
4097                edge_id,
4098                radius,
4099                original_extents[index],
4100                if chamfer { &[] } else { &corners },
4101            );
4102            // This edge's blend wall carries the name of THIS input edge
4103            // (`edge_names[index]`); a smooth chain that engulfs several edges
4104            // is named after the FIRST such input edge processed here (input
4105            // order), the chain's representative.
4106            let edge_name = per_edge_name(edge_names, name, index);
4107            if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4108                eprintln!(
4109                    "sequential build: selection #{index} {} is edge {edge_id} on the evolving body (ends {ends:?}, {composition_lane:?})",
4110                    selection_label(index, edge_points, edge_names, name)
4111                );
4112            }
4113            // Every step is a deterministic function of the body it starts
4114            // from and these four inputs, and the body is itself the chain of
4115            // the steps before it: a chain the search already composed on
4116            // this solid is answered from the memo, refusals included.
4117            chain.push((
4118                [point.x.to_bits(), point.y.to_bits(), point.z.to_bits()],
4119                edge_name.map(str::to_string),
4120                ends.key_bits(),
4121                u8::from(composition_lane == Lane::CutterFirst),
4122            ));
4123            if let Some(memo) = memo.as_deref_mut() {
4124                let key = (memo.prefix.clone(), chain.clone());
4125                let hit = memo.sequential.get(&key);
4126                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4127                    eprintln!(
4128                        "sequential memo: {} components before, step {} {} ({} chains stored)",
4129                        memo.prefix.len(),
4130                        chain.len(),
4131                        if hit.is_some() { "HIT" } else { "miss" },
4132                        memo.sequential.len(),
4133                    );
4134                }
4135                if let Some(built) = hit {
4136                    crate::blend::record_count("count.sequential.memo_hits", 1);
4137                    sequential = built.clone()?;
4138                    continue;
4139                }
4140            }
4141            crate::blend::record_count("count.sequential.steps_built", 1);
4142            let built = fillet_or_chamfer(
4143                &sequential,
4144                edge_id,
4145                radius,
4146                chamfer,
4147                edge_name,
4148                ends,
4149                composition_lane,
4150            );
4151            if let Some(memo) = memo.as_deref_mut() {
4152                memo.sequential.insert((memo.prefix.clone(), chain.clone()), built.clone());
4153            }
4154            sequential = built?;
4155        }
4156        Ok(sequential)
4157    };
4158
4159    let mut result = if let Some(operation) = miter_operation {
4160        // The per-edge results still carry their cutters' standing scaffold,
4161        // which the group settles once its corners are closed. A scaffold face
4162        // merged here would hand its tag to whatever it merged with.
4163        let options = crate::BooleanOptions {
4164            keep_unmerged_name_substrs: vec![CUTTER_SCAFFOLD_NAME.to_string()],
4165            ..crate::BooleanOptions::default()
4166        };
4167        let mut combined: Result<Option<BrepSolid>, KernelRefusal> = Ok(None);
4168        // The units the miter composes: one per selected edge, except that
4169        // edges joined at a TANGENT chain corner blend as one unit through
4170        // this same group build (see `miter_tangent_units`).
4171        let units = miter_tangent_units(solid, &selected_edge_ids, &chain_corners, edge_points.len());
4172        for unit in &units {
4173            let index = unit[0];
4174            let point = &edge_points[index];
4175            let blended = if unit.len() > 1 {
4176                let points = unit.iter().map(|&member| edge_points[member]).collect::<Vec<_>>();
4177                let names = edge_names.map(|all| unit.iter().map(|&member| all[member].clone()).collect::<Vec<_>>());
4178                fillet_edges_group_with_corner_policy(
4179                    solid,
4180                    &points,
4181                    names.as_deref(),
4182                    radius,
4183                    chamfer,
4184                    name,
4185                    None,
4186                    wrap_concave,
4187                    false,
4188                )?
4189            } else {
4190                let edge_id = resolve_edge_by_point(solid, *point)?;
4191                let edge_name = per_edge_name(edge_names, name, index);
4192                let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
4193                check_mixed_concavity(solid, edge_id, entry)?;
4194                check_support_extent(solid, edge_id, radius, entry)?;
4195                fillet_or_chamfer(
4196                    solid,
4197                    edge_id,
4198                    radius,
4199                    chamfer,
4200                    edge_name,
4201                    ToolEnds::default(),
4202                    Lane::CutterFirst,
4203                )?
4204            };
4205            combined = match combined {
4206                Err(e) => Err(e),
4207                Ok(None) => Ok(Some(blended)),
4208                Ok(Some(previous)) => {
4209                    crate::boolean_operation(&previous, &blended, operation, &options)
4210                        .map(Some)
4211                        .map_err(|error| {
4212                            // The boolean's own class survives the wrap.
4213                            error.with_message(|error| {
4214                                format!("fillet_edges: chain-corner miter composition failed: {error}")
4215                            })
4216                        })
4217                }
4218            };
4219            if combined.is_err() {
4220                break;
4221            }
4222        }
4223        // A §6.9.6 miter (per-edge blends intersected/unioned through the
4224        // shared chain corners) can fail to reassemble on faces whose
4225        // fragmented boundary does not close — e.g. a planar cap whose ENTIRE
4226        // perimeter is selected, where fragment_face reports an "incomplete
4227        // run".  Rather than let `fillet_edges` silently DROP a selected edge
4228        // to recover a valid subset (the reported defect: not every edge of
4229        // the face gets a fillet), fall back to the sequential build, which
4230        // blends EVERY selected edge (chain corners get a flat bulkhead
4231        // instead of a miter).  Only if that also fails to produce a valid
4232        // solid do we surface the miter error so the caller's
4233        // maximal-valid-subset search can still run.
4234        match combined {
4235            Ok(Some(mut mitered)) => {
4236                drop_slit_shells(&mut mitered);
4237                mitered
4238            }
4239            Ok(None) => {
4240                return Err(KernelRefusal::input(
4241                    KernelStage::Collect,
4242                    "miter_selection",
4243                    "fillet_edges: no edges selected",
4244                ))
4245            }
4246            Err(miter_err) => match build_sequential() {
4247                Ok(seq) if seq.validate().is_empty() => seq,
4248                _ => return Err(miter_err),
4249            },
4250        }
4251    } else {
4252        build_sequential()?
4253    };
4254
4255    // A re-entrant vertex of a selected face perimeter has two selected,
4256    // convex cap-wall edges and one UNSELECTED concave wall-wall edge.  The
4257    // two cutter volumes only touch there, so the boolean miter leaves a
4258    // triangular planar end-cap instead of carrying the rolling ball around
4259    // the corner.  Close that exact orthogonal class with its horn-torus
4260    // sector (major radius = minor radius = fillet radius).
4261    // BREP lane L: begin keyway_floor_open_mixed_corner_20261014
4262    let mut open_mixed_corners: Vec<(Vec3, [u64; 2], Option<String>)> = Vec::new();
4263    // BREP lane L: end keyway_floor_open_mixed_corner_20261014
4264    if !chamfer {
4265        for (corner, adjacent) in &chain_corners {
4266            let has_concave_unselected_edge = solid.edges.iter().any(|edge| {
4267                if selected_edge_ids.contains(&edge.id) {
4268                    return false;
4269                }
4270                let Ok(a) = edge.curve.evaluate(edge.t0) else {
4271                    return false;
4272                };
4273                let Ok(b) = edge.curve.evaluate(edge.t1) else {
4274                    return false;
4275                };
4276                (a.sub(*corner).length() < 1e-6 || b.sub(*corner).length() < 1e-6)
4277                    && analyze_edge(solid, edge.id, radius)
4278                        .map(|cross| !cross.convex)
4279                        .unwrap_or(false)
4280            });
4281            // BREP lane L: begin keyway_floor_open_mixed_corner_20261014
4282            // The OPEN mixed corner (the 2026-10-13 sprocket's keyway floor):
4283            // one selected convex rim, one selected concave vertical and an
4284            // UNSELECTED convex third edge. The rim's cutter ran through the
4285            // concave pad and left a scaffold square and a misplaced
4286            // bulkhead there; the closure is the one-ended runout's body —
4287            // the §6.9.7 torus sector to C5's stop, ended by its cliff
4288            // (`blend/corner/mixed_open.rs`). It reads the SETTLED body (the
4289            // pad's flush end merged into the cap), so the corner is noted
4290            // here and closed after `settle_cutter_scaffold` below.
4291            if !has_concave_unselected_edge {
4292                let convexity = |edge_id: u64| analyze_edge(solid, edge_id, radius).map(|cross| cross.convex).ok();
4293                let selected_pair = [convexity(selected_edge_ids[adjacent[0]]), convexity(selected_edge_ids[adjacent[1]])];
4294                let one_concave = matches!(selected_pair, [Some(true), Some(false)] | [Some(false), Some(true)]);
4295                let has_convex_unselected_edge = solid.edges.iter().any(|edge| {
4296                    if selected_edge_ids.contains(&edge.id) {
4297                        return false;
4298                    }
4299                    let (Ok(a), Ok(b)) = (edge.curve.evaluate(edge.t0), edge.curve.evaluate(edge.t1)) else {
4300                        return false;
4301                    };
4302                    (a.sub(*corner).length() < 1e-6 || b.sub(*corner).length() < 1e-6)
4303                        && analyze_edge(solid, edge.id, radius).map(|cross| cross.convex).unwrap_or(false)
4304                });
4305                if one_concave && has_convex_unselected_edge {
4306                    open_mixed_corners.push((
4307                        *corner,
4308                        [selected_edge_ids[adjacent[0]], selected_edge_ids[adjacent[1]]],
4309                        corner_face_name(edge_names, name, adjacent),
4310                    ));
4311                }
4312                continue;
4313            }
4314            // BREP lane L: end keyway_floor_open_mixed_corner_20261014
4315            let corner_name = corner_face_name(edge_names, name, adjacent);
4316            if let Ok(rounded) = crate::blend::round_concave_chain_corner(
4317                &result,
4318                solid,
4319                *corner,
4320                [
4321                    selected_edge_ids[adjacent[0]],
4322                    selected_edge_ids[adjacent[1]],
4323                ],
4324                radius,
4325                corner_name.as_deref(),
4326            ) {
4327                result = rounded;
4328            }
4329        }
4330    }
4331
4332    // 3. Round the convex corners (fillets only — chamfers keep sharp
4333    //    vertices).  A corner that cannot be rounded is left as the edge
4334    //    fillets so the group still succeeds.  Each corner patch is named after
4335    //    the selected edges meeting there (`{fid}:BLEND:CORNER:{e_a}+…`) so no
4336    //    two corners collide and the patch stays under the `{fid}:BLEND` prefix.
4337    if !chamfer {
4338        for (ci, corner) in corners.iter().enumerate() {
4339            let corner_name = corner_face_name(edge_names, name, &corner_edges[ci]);
4340            match crate::blend::round_convex_corner(&result, *corner, radius, corner_name.as_deref()) {
4341                Ok(rounded) => result = rounded,
4342                Err(error) => {
4343                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4344                        eprintln!("corner at {corner:?} left as the edge fillets: {error}");
4345                    }
4346                }
4347            }
4348        }
4349    }
4350
4351    // Heal any residual vertex/edge gaps introduced by the corner-rounding
4352    // surgery (the per-edge results are already healed inside fillet_or_chamfer).
4353    heal_edge_vertex_gaps(&mut result, radius)?;
4354    crate::blend::fit_planar_charts_to_trims(solid, &mut result)?;
4355    // BREP lane L: begin keyway_floor_open_mixed_corner_20261014
4356    let mut body = settle_cutter_scaffold(result);
4357    for (corner, pair, corner_name) in &open_mixed_corners {
4358        match crate::blend::round_mixed_concave_open_corner(&body, solid, *corner, *pair, radius, corner_name.as_deref()) {
4359            Ok(rounded) => body = rounded,
4360            Err(error) => {
4361                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4362                    eprintln!("open mixed corner at {corner:?} left as the composition built it: {error}");
4363                }
4364            }
4365        }
4366    }
4367    Ok(GroupBody { body, bowtie_clean: false })
4368    // BREP lane L: end keyway_floor_open_mixed_corner_20261014
4369}
4370
4371/// The selected edges (indices into the selection) that are CONCAVE and end
4372/// at a star corner (`corner_edges`: three or more selected edges at one
4373/// vertex), in input order. Empty for a chamfer, a selection with no star
4374/// corner, one whose star corners carry no concave edge, and one whose
4375/// convexity cannot be read — the cases the composition builds in input
4376/// order, exactly as before.
4377/// Whether the miter composition drops a stray SLIT shell: on unless
4378/// `BREP_FILLET_MITER_DROP_SLIT_SHELLS=0`/`off`.
4379fn drop_slit_shells_on() -> bool {
4380    switch!(live "BREP_FILLET_MITER_DROP_SLIT_SHELLS", true)
4381}
4382
4383/// Remove from a composed miter body every shell beyond the first whose faces
4384/// are all SLITS — each loop runs along each of its edges once forward and
4385/// once back — over edges no other shell uses, then the edges and vertices
4386/// nothing references any more. Returns how many shells went.
4387///
4388/// Such a shell bounds no area and no volume. The 2026-11-07 "fillet fails"
4389/// report's five-edge selection composed to the right body (the volume of
4390/// the same composition on the serialised input, which has one shell) plus
4391/// one face of the hole's floor plane, `Box_NZ_Offset_1_1`, whose single loop
4392/// ran 1.25 out along one edge and straight back; `validate()` accepts it.
4393fn drop_slit_shells(body: &mut BrepSolid) -> usize {
4394    if !drop_slit_shells_on() || body.shells.len() < 2 {
4395        return 0;
4396    }
4397    let mut users: std::collections::HashMap<u64, std::collections::HashSet<usize>> = std::collections::HashMap::new();
4398    for (index, shell) in body.shells.iter().enumerate() {
4399        for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
4400            users.entry(coedge.edge_id).or_default().insert(index);
4401        }
4402    }
4403    let slit_face = |face: &crate::topology::FaceRecord| {
4404        face.loops.iter().all(|lp| {
4405            let mut runs: std::collections::HashMap<u64, (usize, usize)> = std::collections::HashMap::new();
4406            for coedge in &lp.coedges {
4407                let entry = runs.entry(coedge.edge_id).or_default();
4408                if coedge.forward {
4409                    entry.0 += 1;
4410                } else {
4411                    entry.1 += 1;
4412                }
4413            }
4414            !runs.is_empty() && runs.values().all(|&(forward, back)| forward == 1 && back == 1)
4415        })
4416    };
4417    let mut index = 0usize;
4418    let mut dropped = 0usize;
4419    body.shells.retain(|shell| {
4420        let this = index;
4421        index += 1;
4422        let slit = this > 0
4423            && !shell.faces.is_empty()
4424            && shell.faces.iter().all(|face| slit_face(face))
4425            && shell
4426                .faces
4427                .iter()
4428                .flat_map(|face| &face.loops)
4429                .flat_map(|lp| &lp.coedges)
4430                .all(|coedge| users.get(&coedge.edge_id).is_some_and(|set| set.len() == 1));
4431        dropped += usize::from(slit);
4432        !slit
4433    });
4434    if dropped == 0 {
4435        return 0;
4436    }
4437    let used_edges: std::collections::HashSet<u64> = body
4438        .shells
4439        .iter()
4440        .flat_map(|shell| &shell.faces)
4441        .flat_map(|face| &face.loops)
4442        .flat_map(|lp| &lp.coedges)
4443        .map(|coedge| coedge.edge_id)
4444        .collect();
4445    body.edges.retain(|edge| used_edges.contains(&edge.id));
4446    let used_vertices: std::collections::HashSet<u64> =
4447        body.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
4448    body.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
4449    dropped
4450}
4451
4452/// Whether the miter composition blends a TANGENT run of the selection as
4453/// one unit: on unless `BREP_FILLET_MITER_TANGENT_UNITS=0`/`off`.
4454fn miter_tangent_units_on() -> bool {
4455    switch!(live "BREP_FILLET_MITER_TANGENT_UNITS", true)
4456}
4457
4458/// The units the §6.9.6 miter composition blends and then intersects (or
4459/// unions), in input order of each unit's first edge: every selected edge on
4460/// its own, except that edges meeting at a chain corner where their tangents
4461/// CONTINUE each other (a G1 joint, the 1e-6 bar of the tangent-chain walk)
4462/// form one unit.
4463///
4464/// The miter exists for SHARP chain corners: two full-length blends run
4465/// through the corner and trim each other. At a tangent joint there is
4466/// nothing to trim — the two walls meet flush — and two full-length
4467/// per-edge blends of the edges either side of it, each capped where its
4468/// tangent neighbour was left sharp, overlap along that joint in a sliver
4469/// the boolean cannot conform (2026-11-07 "fillet fails" report: a revolve
4470/// end cap's hole loop, one cylinder edge meeting a ceiling plane edge that
4471/// runs on tangentially through an offset blend into a wall; "one-use edge
4472/// conformance did not converge after 8 passes" on the plane-edge result
4473/// intersected with the blend-edge result). The network lane builds such a
4474/// tangent run whole with flush joins; it refused the selection only for
4475/// its sharp re-entrant corners, so a unit that is a STRICT part of the
4476/// selection goes back through the group build, which reaches it there.
4477/// A selection that is one tangent run keeps per-edge units, so the
4478/// recursion always shrinks the selection.
4479fn miter_tangent_units(
4480    solid: &BrepSolid,
4481    selected_edge_ids: &[u64],
4482    chain_corners: &[(Vec3, [usize; 2])],
4483    count: usize,
4484) -> Vec<Vec<usize>> {
4485    let singles = || (0..count).map(|index| vec![index]).collect::<Vec<_>>();
4486    if !miter_tangent_units_on() || selected_edge_ids.len() != count {
4487        return singles();
4488    }
4489    // The tangent along `edge` pointing AWAY from its end at `corner`.
4490    let leaving = |edge_id: u64, corner: Vec3| -> Option<Vec3> {
4491        let edge = solid.edges.iter().find(|edge| edge.id == edge_id)?;
4492        if edge.degenerate {
4493            return None;
4494        }
4495        let start = edge.curve.evaluate(edge.t0).ok()?;
4496        let end = edge.curve.evaluate(edge.t1).ok()?;
4497        let at_start = start.sub(corner).length() <= end.sub(corner).length();
4498        let t = if at_start { edge.t0 } else { edge.t1 };
4499        let tangent = edge.curve.unit_tangent(t, edge.t0, edge.t1).ok()?;
4500        Some(if at_start { tangent } else { tangent.scale(-1.0) })
4501    };
4502    let mut parent: Vec<usize> = (0..count).collect();
4503    fn root(parent: &mut [usize], mut index: usize) -> usize {
4504        while parent[index] != index {
4505            parent[index] = parent[parent[index]];
4506            index = parent[index];
4507        }
4508        index
4509    }
4510    for (corner, [a, b]) in chain_corners {
4511        let (Some(ta), Some(tb)) = (leaving(selected_edge_ids[*a], *corner), leaving(selected_edge_ids[*b], *corner)) else {
4512            continue;
4513        };
4514        // Leaving the corner, a tangent continuation points the opposite way.
4515        if ta.dot(tb) <= -(1.0 - 1e-6) {
4516            let (ra, rb) = (root(&mut parent, *a), root(&mut parent, *b));
4517            if ra != rb {
4518                parent[ra.max(rb)] = ra.min(rb);
4519            }
4520        }
4521    }
4522    let mut units: Vec<Vec<usize>> = Vec::new();
4523    let mut unit_of_root: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
4524    for index in 0..count {
4525        let r = root(&mut parent, index);
4526        let slot = *unit_of_root.entry(r).or_insert_with(|| {
4527            units.push(Vec::new());
4528            units.len() - 1
4529        });
4530        units[slot].push(index);
4531    }
4532    if units.len() <= 1 || units.iter().all(|unit| unit.len() == 1) {
4533        return singles();
4534    }
4535    units
4536}
4537
4538fn concave_star_edges(
4539    solid: &BrepSolid,
4540    selected_edge_ids: &[u64],
4541    corner_edges: &[Vec<usize>],
4542    radius: f64,
4543    chamfer: bool,
4544) -> Vec<usize> {
4545    if chamfer || corner_edges.is_empty() || !concave_first_on() {
4546        return Vec::new();
4547    }
4548    let Some(convexity) = crate::blend::selection_convexity(solid, selected_edge_ids, radius) else {
4549        return Vec::new();
4550    };
4551    (0..selected_edge_ids.len())
4552        .filter(|&index| !convexity[index] && corner_edges.iter().any(|adjacent| adjacent.contains(&index)))
4553        .collect()
4554}
4555
4556/// The cutter the sequential build's single-edge ladder answers a selected
4557/// edge with, read on the ORIGINAL solid: an exact extrusion (a straight
4558/// edge between planes), an exact revolution (a circular edge on
4559/// straight-meridian carriers about its own axis) or, for every other edge,
4560/// the general march (`fillet_or_chamfer_exact` refuses it, so the march
4561/// builds it with direct surgery on the evolving body).
4562#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4563enum CutterClass {
4564    Marched,
4565    Straight,
4566    Circular,
4567}
4568
4569fn cutter_class(solid: &BrepSolid, edge_id: u64, radius: f64) -> CutterClass {
4570    match super::analyze::analyze_edge(solid, edge_id, radius) {
4571        Ok(cross) => match cross.path {
4572            super::analyze::EdgePath::Straight { .. } => CutterClass::Straight,
4573            super::analyze::EdgePath::Circular { .. } => CutterClass::Circular,
4574        },
4575        Err(_) => CutterClass::Marched,
4576    }
4577}
4578
4579/// The sequential build's rank of every selected edge, from the cutter
4580/// classes meeting at the selection's star corners: `1` for a marched edge
4581/// and `3` for a revolved cutter at a star whose edges MIX classes, `2` for
4582/// everything else (a star of one class, a chain corner, a lone edge).
4583/// Within a rank the input order holds ([`sequential_build_order`]).
4584///
4585/// At such a corner the input order fails in two ways, both measured on the
4586/// 2026-10-13 sprocket report whose slit walls were selected as faces
4587/// (`inbox_20261013_sprocket_keyway_slit_fillet`): a revolved cutter leaves
4588/// a TORUS tangent to the hub's top plane along its rail, and the next
4589/// straight cutter's scaffold face lies in that very plane and ends on that
4590/// rail, so the boolean meets a tangent plane/torus contact along a 0.148
4591/// arc that the imprint traces but the assembly cannot close (`unsupported
4592/// tangent-curve surface intersection`, open edges, a 0.067 curve/vertex
4593/// gap); and the slit's vertical, a straight edge on the hub CYLINDER that
4594/// only the march builds, finds "no single end face across the corner" once
4595/// its star mates have been cut. The marched edge cut first sees the pristine
4596/// corner, and a straight cutter cut before the revolved one meets the
4597/// scaffold plane of a CYLINDER tangent along a line — the ordinary planar
4598/// star's own geometry, which the arrangement has always closed. Every
4599/// selection without a mixed-class star keeps its order, byte for byte.
4600fn mixed_star_class_ranks(
4601    solid: &BrepSolid,
4602    selected_edge_ids: &[u64],
4603    corner_edges: &[Vec<usize>],
4604    radius: f64,
4605    chamfer: bool,
4606) -> Vec<u8> {
4607    let mut ranks = vec![2u8; selected_edge_ids.len()];
4608    if chamfer || corner_edges.is_empty() || !class_order_on() {
4609        return ranks;
4610    }
4611    let classes: Vec<CutterClass> = selected_edge_ids
4612        .iter()
4613        .map(|&edge_id| cutter_class(solid, edge_id, radius))
4614        .collect();
4615    for adjacent in corner_edges {
4616        let Some(&head) = adjacent.first() else {
4617            continue;
4618        };
4619        if adjacent.iter().all(|&index| classes[index] == classes[head]) {
4620            continue;
4621        }
4622        for &index in adjacent {
4623            match classes[index] {
4624                CutterClass::Marched => ranks[index] = 1,
4625                CutterClass::Circular => ranks[index] = 3,
4626                CutterClass::Straight => {}
4627            }
4628        }
4629    }
4630    ranks
4631}
4632
4633/// The order the cutter composition's sequential build blends a selection
4634/// in: the input order, except that the edges in `first` (a star corner's
4635/// concave edges, [`concave_star_edges`]) are moved ahead of every other
4636/// edge and the rest follow by `ranks` ([`mixed_star_class_ranks`], lower
4637/// first), keeping the input order among the moved edges and within each
4638/// rank. With `first` empty and every rank equal this is the input order.
4639pub fn sequential_build_order(count: usize, first: &[usize], ranks: &[u8]) -> Vec<usize> {
4640    let mut order: Vec<usize> = (0..count).collect();
4641    // A stable sort: ties keep the input order.
4642    order.sort_by_key(|&index| if first.contains(&index) { 0 } else { ranks.get(index).copied().unwrap_or(2).max(1) });
4643    order
4644}
4645
4646/// Whether the sequential build ranks a mixed-class star's edges by cutter
4647/// class ([`mixed_star_class_ranks`]); always, outside a test that forces it
4648/// off.
4649fn class_order_on() -> bool {
4650    true
4651}
4652
4653
4654/// `corners` and their `corner_edges` (parallel), with every corner that one
4655/// of the `first` edges ends at moved ahead of the rest, both runs in their
4656/// detection order. With `first` empty both come back as they were.
4657fn corners_concave_first(
4658    corners: Vec<Vec3>,
4659    corner_edges: Vec<Vec<usize>>,
4660    first: &[usize],
4661) -> (Vec<Vec3>, Vec<Vec<usize>>) {
4662    if first.is_empty() {
4663        return (corners, corner_edges);
4664    }
4665    let mut ordered: Vec<(Vec3, Vec<usize>)> = Vec::with_capacity(corners.len());
4666    let pairs: Vec<(Vec3, Vec<usize>)> = corners.into_iter().zip(corner_edges).collect();
4667    let with_concave = |adjacent: &Vec<usize>| adjacent.iter().any(|index| first.contains(index));
4668    ordered.extend(pairs.iter().filter(|(_, adjacent)| with_concave(adjacent)).cloned());
4669    ordered.extend(pairs.iter().filter(|(_, adjacent)| !with_concave(adjacent)).cloned());
4670    ordered.into_iter().unzip()
4671}
4672
4673/// Whether the sequential build moves a star corner's concave edge first
4674/// ([`sequential_build_order`]); always, outside a test that forces it off.
4675fn concave_first_on() -> bool {
4676    true
4677}
4678
4679
4680/// Variable-radius fillet/chamfer of a GROUP of edges (§4.9.5), the app entry
4681/// for tapered blends: each selected edge (resolved by a point on it) is
4682/// blended with the SAME radius profile `radii` — a list of (edge-fraction,
4683/// radius) stops in `[0,1]` — applied along that edge's own parameterization.
4684/// Edges are blended independently (no shared-vertex corner rounding; a
4685/// variable-radius star has no single tangent ball), so this is the tapered
4686/// counterpart of `fillet_edges` for the constant case.
4687pub fn fillet_edges_variable(
4688    solid: &BrepSolid,
4689    edge_points: &[Vec3],
4690    edge_names: Option<&[String]>,
4691    radii: &[(f64, f64)],
4692    chamfer: bool,
4693    name: Option<&str>,
4694) -> Result<BrepSolid, KernelRefusal> {
4695    // One blend operation: the reports of an earlier one, never consumed, are
4696    // dropped as it starts (nested calls keep this operation's).
4697    let _operation = crate::blend::BlendOperation::enter();
4698    if edge_points.is_empty() {
4699        return Err(KernelRefusal::input(
4700            KernelStage::Collect,
4701            "variable_selection",
4702            "fillet_edges_variable: no edges selected",
4703        ));
4704    }
4705    let per_edge_stops: Vec<Vec<(f64, f64)>> = vec![radii.to_vec(); edge_points.len()];
4706    fillet_edges_variable_impl(
4707        solid,
4708        edge_points,
4709        edge_names,
4710        &per_edge_stops,
4711        chamfer,
4712        name,
4713        "fillet_edges_variable",
4714        true,
4715    )
4716}
4717
4718/// The shared variable-radius group core: each selected edge `i` is blended
4719/// with ITS OWN stop list `per_edge_stops[i]` (the legacy entry replicates one
4720/// list; the law entries sample a chain-abscissa [`crate::law::RadiusLaw`] per
4721/// edge).  `allow_tapered_sequential` keeps the legacy entry's sequential
4722/// fallback for tapered chains (whose end state is the honest
4723/// "mismatched radii" validation gate); the law entries pass `false` because
4724/// their stop fractions are computed against the ORIGINAL edges — the
4725/// sequential build re-resolves edges on the evolving solid whose shared
4726/// corners are already TRIMMED by earlier blends, which would silently distort
4727/// the law's abscissa mapping (constant stops are immune, so they may still
4728/// fall back).
4729#[allow(clippy::too_many_arguments)]
4730fn fillet_edges_variable_impl(
4731    solid: &BrepSolid,
4732    edge_points: &[Vec3],
4733    edge_names: Option<&[String]>,
4734    per_edge_stops: &[Vec<(f64, f64)>],
4735    chamfer: bool,
4736    name: Option<&str>,
4737    entry: &str,
4738    allow_tapered_sequential: bool,
4739) -> Result<BrepSolid, KernelRefusal> {
4740    // The translation control (`BREP_TRANSLATION_CONTROL`, `brep/recentre.rs`)
4741    // and the recentre guard, as `fillet_edges_reported` applies them.
4742    let bounds = crate::recentre::solid_bounds(solid);
4743    let translated = match crate::recentre::control_offset_at_entry() {
4744        Some(offset) => Some((offset, crate::recentre::EntryKind::Control)),
4745        None => crate::recentre::guard_offset(bounds).map(|offset| {
4746            crate::recentre::profile_fired(entry, offset, bounds);
4747            (offset, crate::recentre::EntryKind::Guard)
4748        }),
4749    };
4750    if let Some((offset, kind)) = translated {
4751        let _entry = crate::recentre::TranslatedEntry::open(kind);
4752        let translate = |solid: &BrepSolid, offset: Vec3| {
4753            crate::recentre::translate_solid(solid, offset).map_err(|message| {
4754                KernelRefusal::internal(
4755                    KernelStage::Collect,
4756                    "translation_control",
4757                    format!("{entry}: the translation control could not move the solid: {message}"),
4758                )
4759            })
4760        };
4761        let moved = translate(solid, offset)?;
4762        let points: Vec<Vec3> = edge_points.iter().map(|point| point.add(offset)).collect();
4763        let result = fillet_edges_variable_impl(
4764            &moved,
4765            &points,
4766            edge_names,
4767            per_edge_stops,
4768            chamfer,
4769            name,
4770            entry,
4771            allow_tapered_sequential,
4772        )?;
4773        return translate(&result, offset.scale(-1.0));
4774    }
4775    debug_assert_eq!(per_edge_stops.len(), edge_points.len());
4776    // A law that is one constant everywhere IS the constant-radius fillet:
4777    // hand it to the constant group, whose corners are constructed (the
4778    // stripe network) rather than composed by boolean.
4779    if let Some(constant) = per_edge_stops
4780        .first()
4781        .and_then(|stops| stops.first())
4782        .map(|(_, radius)| *radius)
4783    {
4784        let uniform = per_edge_stops.iter().all(|stops| {
4785            stops
4786                .iter()
4787                .all(|(_, radius)| (radius - constant).abs() <= 1e-12 * (1.0 + constant.abs()))
4788        });
4789        if uniform && constant > 0.0 {
4790            return fillet_edges(solid, edge_points, edge_names, constant, chamfer, name);
4791        }
4792    }
4793    let max_radius = per_edge_stops
4794        .iter()
4795        .flat_map(|stops| stops.iter())
4796        .map(|(_, r)| r.abs())
4797        .fold(0.0_f64, f64::max);
4798
4799    // Tried first; whatever the network does not build (an unequal-radius
4800    // corner, a flush join or re-entrant vertex at a varying radius, a
4801    // result its acceptance rejects) falls through to the composition below
4802    // exactly as before.
4803    if edge_points.len() >= 2 {
4804        match fillet_variable_network(
4805            solid, edge_points, edge_names, per_edge_stops, chamfer, name, entry, max_radius,
4806        )? {
4807            Ok(built) => return Ok(built),
4808            // A radius relief's law is the network's to build: the
4809            // composition below took 75 s a plan on the rounded-outline report at r 1.0
4810            // and built none, so the relief's next plan is asked instead.
4811            Err(refusal) if crate::blend::relief::relieving() => return Err(refusal),
4812            // A star whose corner stands outside a neighbouring blend has no
4813            // smooth corner fill on any lane: its named reason is the answer.
4814            Err(refusal) if crate::blend::is_n_sided_undercut_refusal(&refusal) => return Err(refusal),
4815            Err(_) => {}
4816        }
4817    }
4818
4819    // Chain corners miter exactly like the constant-radius group (§6.9.6):
4820    // per-edge blends on the ORIGINAL solid composed by boolean — Intersect
4821    // when every edge is convex, Union when every edge is concave.  Mixed or
4822    // unclassifiable selections keep the sequential build.  Variable blends
4823    // never round star vertices, so unlike the constant group there is no
4824    // sequential-only star path to protect.
4825    let mut chain_corner = false;
4826    {
4827        use rustc_hash::FxHashSet as HashSet;
4828        let mut endpoints: Vec<(Vec3, usize)> = Vec::with_capacity(edge_points.len() * 2);
4829        for (i, point) in edge_points.iter().enumerate() {
4830            if let Ok(edge_id) = resolve_edge_by_point(solid, *point) {
4831                if let Some(edge) = solid.edges.iter().find(|e| e.id == edge_id) {
4832                    if let (Ok(a), Ok(b)) =
4833                        (edge.curve.evaluate(edge.t0), edge.curve.evaluate(edge.t1))
4834                    {
4835                        endpoints.push((a, i));
4836                        endpoints.push((b, i));
4837                    }
4838                }
4839            }
4840        }
4841        let mut used = vec![false; endpoints.len()];
4842        for i in 0..endpoints.len() {
4843            if used[i] {
4844                continue;
4845            }
4846            used[i] = true;
4847            let mut edges_here: HashSet<usize> = HashSet::default();
4848            edges_here.insert(endpoints[i].1);
4849            for j in (i + 1)..endpoints.len() {
4850                if used[j] {
4851                    continue;
4852                }
4853                if endpoints[i].0.sub(endpoints[j].0).length() < 1e-6 {
4854                    used[j] = true;
4855                    edges_here.insert(endpoints[j].1);
4856                }
4857            }
4858            if edges_here.len() == 2 {
4859                chain_corner = true;
4860            }
4861        }
4862    }
4863    let miter_operation = if chain_corner {
4864        let probe_radius = if max_radius > 0.0 { max_radius } else { 1.0 };
4865        let mut any_convex = false;
4866        let mut any_concave = false;
4867        for point in edge_points {
4868            match resolve_edge_by_point(solid, *point)
4869                .and_then(|edge_id| analyze_edge(solid, edge_id, probe_radius))
4870            {
4871                Ok(cross) if cross.convex => any_convex = true,
4872                Ok(_) => any_concave = true,
4873                Err(_) => {
4874                    any_convex = true;
4875                    any_concave = true;
4876                    break;
4877                }
4878            }
4879        }
4880        match (any_convex, any_concave) {
4881            (true, false) => Some(crate::BooleanOperation::Intersect),
4882            (false, true) => Some(crate::BooleanOperation::Union),
4883            _ => None,
4884        }
4885    } else {
4886        None
4887    };
4888
4889    // Try the miter first; the variable blend's FITTED boundary curves are
4890    // only ~1e-3 accurate at blend-blend tangencies (unlike the exact
4891    // constant-radius cylinders), so the composition can fail — fall back to
4892    // the sequential build then, which is never worse than the pre-miter
4893    // behavior.  Tightening the taper surface's endpoint fitting is the
4894    // documented follow-up that would make the miter stick.
4895    let miter_attempt: Option<BrepSolid> = if let Some(operation) = miter_operation {
4896        let options = crate::BooleanOptions::default();
4897        let mut combined: Option<BrepSolid> = None;
4898        let mut failed = false;
4899        for (index, point) in edge_points.iter().enumerate() {
4900            let Ok(edge_id) = resolve_edge_by_point(solid, *point) else {
4901                failed = true;
4902                break;
4903            };
4904            let edge_name = per_edge_name(edge_names, name, index);
4905            let Ok(blended) = crate::blend::blend_edge_variable(
4906                solid,
4907                edge_id,
4908                &per_edge_stops[index],
4909                chamfer,
4910                edge_name,
4911            ) else {
4912                failed = true;
4913                break;
4914            };
4915            let next = match combined.take() {
4916                None => blended,
4917                Some(previous) => {
4918                    match crate::boolean_operation(&previous, &blended, operation, &options) {
4919                        Ok(next) => next,
4920                        Err(_) => {
4921                            failed = true;
4922                            break;
4923                        }
4924                    }
4925                }
4926            };
4927            combined = Some(next);
4928        }
4929        if failed {
4930            None
4931        } else {
4932            combined.filter(|s| s.validate().is_empty())
4933        }
4934    } else {
4935        None
4936    };
4937    let mut result = match miter_attempt {
4938        Some(mitered) => mitered,
4939        None => {
4940            // Any stop list that is NOT radius-uniform (the same 1e-12
4941            // relative criterion `blend_edge_variable` uses for its exact
4942            // constant-radius degeneration) makes the sequential build
4943            // abscissa-distorting on trimmed chain edges; law entries refuse
4944            // instead of silently shifting the law.
4945            let tapered = per_edge_stops.iter().any(|stops| {
4946                stops.first().is_some_and(|(_, first)| {
4947                    stops
4948                        .iter()
4949                        .any(|(_, r)| (r - first).abs() > 1e-12 * (1.0 + first.abs()))
4950                })
4951            });
4952            if chain_corner && tapered && !allow_tapered_sequential {
4953                // The transition patch that would carry a taper through the
4954                // corner is not built: a named deferral.
4955                return Err(KernelRefusal::unsupported(
4956                    KernelStage::Sew,
4957                    "tapered_chain_miter",
4958                    format!(
4959                        "{entry}: the tapered blends across the selected chain's shared corners \
4960                         did not compose to a valid solid (the fitted blend boundaries could not \
4961                         be mitered); fillet fewer edges per operation or reduce the taper"
4962                    ),
4963                ));
4964            }
4965            let mut sequential = solid.clone();
4966            for (index, point) in edge_points.iter().enumerate() {
4967                let edge_id = resolve_edge_by_point(&sequential, *point)?;
4968                let edge_name = per_edge_name(edge_names, name, index);
4969                sequential = crate::blend::blend_edge_variable(
4970                    &sequential,
4971                    edge_id,
4972                    &per_edge_stops[index],
4973                    chamfer,
4974                    edge_name,
4975                )?;
4976            }
4977            sequential
4978        }
4979    };
4980    // Heal §6.9 surgery so re-trimmed edges meet their vertices exactly; scale
4981    // the heal bound by the largest radius stop in the taper profile.
4982    heal_edge_vertex_gaps(&mut result, max_radius)?;
4983    crate::blend::fit_planar_charts_to_trims(solid, &mut result)?;
4984    // Final honesty gate: a genuinely TAPERED chain (different radii at the
4985    // shared corner) has mismatched trim stations there — the blends cannot
4986    // meet without a transition patch (not implemented), and the sequential
4987    // surgery silently left broken topology before this gate existed.
4988    let issues = result.validate();
4989    if !issues.is_empty() {
4990        // Two verdicts share the text's shape: the legacy entry names the
4991        // transition patch it does not build (a deferral); the law entries,
4992        // whose taper is continuous through the corner, report the
4993        // composition failing its own validation (a check that tripped).
4994        let (detail, class) = if allow_tapered_sequential {
4995            (
4996                "tapered blends meet at a shared chain vertex with \
4997                 mismatched radii — the radius-transition corner patch is not implemented; \
4998                 fillet the edges in separate operations or use matching stop radii",
4999                RefusalClass::UnsupportedGeometry {
5000                    what: "taper_transition_patch".into(),
5001                },
5002            )
5003        } else {
5004            (
5005                "the composed radius-law blend produced invalid topology — the blends \
5006                 across a shared chain corner failed to reassemble",
5007                RefusalClass::Internal {
5008                    what: "law_chain_topology".into(),
5009                },
5010            )
5011        };
5012        return Err(KernelRefusal::new(
5013            class,
5014            KernelStage::Validate,
5015            format!(
5016                "{entry}: {detail} ({} validation issues, first: {})",
5017                issues.len(),
5018                issues
5019                    .first()
5020                    .map(|issue| issue.message.clone())
5021                    .unwrap_or_default()
5022            ),
5023        ));
5024    }
5025    // The variable-radius lane's own soundness acceptance, the same one the
5026    // constant-radius group exit takes. `validate()` above is an INCIDENCE
5027    // test: a tapered wall that passes through a neighbour, or through itself,
5028    // satisfies every check it makes and still measures a volume.
5029    crate::soundness::census::profile_operation(&result, &[solid], None, entry);
5030    crate::accept_sound(result, entry)
5031}
5032
5033/// `Ok(None)` is "not this lane" — the network refused, or its result
5034/// failed the same acceptance the constant group holds the network to —
5035/// and the caller composes as before; `Err` is a refusal nothing below
5036/// can answer.
5037#[allow(clippy::too_many_arguments)]
5038fn fillet_variable_network(
5039    solid: &BrepSolid,
5040    edge_points: &[Vec3],
5041    edge_names: Option<&[String]>,
5042    per_edge_stops: &[Vec<(f64, f64)>],
5043    chamfer: bool,
5044    name: Option<&str>,
5045    entry: &str,
5046    max_radius: f64,
5047) -> Result<Result<BrepSolid, KernelRefusal>, KernelRefusal> {
5048    let mut edge_ids = Vec::with_capacity(edge_points.len());
5049    for point in edge_points {
5050        edge_ids.push(resolve_edge_by_point(solid, *point)?);
5051    }
5052    let laws: Vec<crate::blend::StripeRadius> =
5053        per_edge_stops.iter().map(|stops| crate::blend::StripeRadius::from_stops(stops)).collect();
5054    let network_names: Vec<Option<String>> = (0..edge_points.len())
5055        .map(|index| per_edge_name(edge_names, name, index).map(str::to_string))
5056        .collect();
5057    let network_corner_name = |adjacent: &[usize]| corner_face_name(edge_names, name, adjacent);
5058    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
5059    // A support pcurve off the floor is re-run ONCE with the knot-aware
5060    // support fit, as the constant group's network is; a re-run that also
5061    // fails keeps the first refusal. A radius relief's law crowds the
5062    // march's stations into its ramp, and the rail's knot spans there are
5063    // finer than the uniform track can follow (a reported model: r 1.4 on
5064    // the outline of a cut through a sub-D body, its relieved rail spans
5065    // 7.7e-5 against a track spacing of 2.4e-4, 1.5e-6 off at 4097
5066    // samples).
5067    let law_network = || {
5068        crate::blend::blend_star_network_laws(solid, &edge_ids, &laws, chamfer, &network_names, &network_corner_name, true)
5069    };
5070    let network_result = law_network().or_else(|first| {
5071        if crate::blend::is_pcurve_floor_refusal(&first) {
5072            crate::blend::with_pcurve_knot_retry(law_network).map_err(|_| first)
5073        } else {
5074            Err(first)
5075        }
5076    });
5077    let mut network = match network_result {
5078        Ok(network) => network,
5079        Err(refusal) => {
5080            if debug {
5081                eprintln!("law network refused: {refusal}");
5082            }
5083            return Ok(Err(refusal));
5084        }
5085    };
5086    // The constant group's acceptance of a network result, in its order:
5087    // the vertex-gap heal, the planar charts, validation, the interference
5088    // classifier and the bowtie scan; then the soundness acceptance the
5089    // variable lane's exit takes.
5090    let healed = heal_edge_vertex_gaps(&mut network, max_radius);
5091    crate::blend::fit_planar_charts_to_trims(solid, &mut network)?;
5092    let issues = network.validate();
5093    let interference = check_blend_interference(solid, &network, &edge_ids, entry);
5094    let bowtie = check_loop_self_crossings(&network, entry).and_then(|()| check_blend_wall_loops(&network, entry));
5095    if healed.is_ok() && issues.is_empty() && interference.is_ok() && bowtie.is_ok() {
5096        crate::soundness::census::profile_operation(&network, &[solid], None, entry);
5097        match crate::accept_sound(network, entry) {
5098            Ok(sound) => return Ok(Ok(sound)),
5099            Err(refusal) => {
5100                if debug {
5101                    eprintln!("law network result unsound: {refusal}");
5102                }
5103                return Ok(Err(refusal));
5104            }
5105        }
5106    }
5107    if debug {
5108        eprintln!(
5109            "law network result rejected: heal={healed:?} issues={issues:?} \
5110             interference={interference:?} bowtie={bowtie:?}"
5111        );
5112    }
5113    Ok(Err(KernelRefusal::unsupported(
5114        KernelStage::Validate,
5115        "law_network_rejected",
5116        format!(
5117            "{entry}: the tapered network's result was rejected (heal {}, {} validation issues, interference {}, loops {})",
5118            if healed.is_ok() { "ok" } else { "failed" },
5119            issues.len(),
5120            if interference.is_ok() { "ok" } else { "found" },
5121            if bowtie.is_ok() { "ok" } else { "found" },
5122        ),
5123    )))
5124}
5125
5126
5127/// One selected edge placed on the ordered chain, with its arc-length
5128/// parameterization (the caller-side mapping from chain abscissa to the
5129/// `blend_edge_variable` per-edge parameter-fraction stop seam).
5130struct ChainLink {
5131    /// Position of this edge in the caller's `edge_points` selection.
5132    input_index: usize,
5133    /// True when the edge's own t0→t1 parameter direction runs WITH the chain.
5134    forward: bool,
5135    /// Cumulative chord-length table from the edge's t0 end:
5136    /// `(parameter fraction, arc length)`, uniformly spaced in fraction.
5137    arc: Vec<(f64, f64)>,
5138    /// Total arc length of the edge.
5139    length: f64,
5140    /// Chain abscissa at the link's ENTRY vertex (the end reached first when
5141    /// walking the chain from its start).
5142    abscissa: f64,
5143}
5144
5145/// Cumulative chord-length table of one edge, `(parameter fraction, arc
5146/// length)` at uniform fractions.  The sample count doubles until two
5147/// successive total-length estimates agree within `tol` (chord length
5148/// converges O(N⁻²) for smooth curves, so the agreement of the N and 2N
5149/// estimates bounds the remaining error at the same order); straight edges
5150/// converge on the first doubling.  The 16-sample start resolves any
5151/// single-span arc of up to half a turn to sub-percent before refinement; the
5152/// 4096 cap (8 doublings) guards adversarial curves — beyond it the table is
5153/// two orders denser than the blend march's station grid, so finer chords
5154/// cannot move any station's sampled radius meaningfully.
5155fn edge_arc_table(
5156    curve: &NurbsCurve,
5157    t0: f64,
5158    t1: f64,
5159    tol: f64,
5160) -> Result<(Vec<(f64, f64)>, f64), KernelRefusal> {
5161    let evaluate = |t: f64| curve.evaluate(t).or_refuse(KernelStage::Collect, "arc_table");
5162    let build = |n: usize| -> Result<(Vec<(f64, f64)>, f64), KernelRefusal> {
5163        let mut table = Vec::with_capacity(n + 1);
5164        let mut cumulative = 0.0;
5165        let mut previous = evaluate(t0)?;
5166        table.push((0.0, 0.0));
5167        for j in 1..=n {
5168            let fraction = j as f64 / n as f64;
5169            let point = evaluate(t0 + (t1 - t0) * fraction)?;
5170            cumulative += point.sub(previous).length();
5171            previous = point;
5172            table.push((fraction, cumulative));
5173        }
5174        Ok((table, cumulative))
5175    };
5176    let mut n = 16usize;
5177    let (mut table, mut length) = build(n)?;
5178    while n < 4096 {
5179        n *= 2;
5180        let (next_table, next_length) = build(n)?;
5181        let converged = (next_length - length).abs() <= tol;
5182        table = next_table;
5183        length = next_length;
5184        if converged {
5185            break;
5186        }
5187    }
5188    Ok((table, length))
5189}
5190
5191/// Arc length from the edge's t0 end at `fraction` of its parameter span,
5192/// linearly interpolated in the uniform chord table.
5193fn arc_length_at_fraction(table: &[(f64, f64)], fraction: f64) -> f64 {
5194    let fraction = fraction.clamp(0.0, 1.0);
5195    let intervals = table.len() - 1;
5196    let scaled = fraction * intervals as f64;
5197    let index = (scaled.floor() as usize).min(intervals - 1);
5198    let local = scaled - index as f64;
5199    let (_, a) = table[index];
5200    let (_, b) = table[index + 1];
5201    a + (b - a) * local
5202}
5203
5204/// Resolve the selected edges and order them into ONE OPEN CHAIN with
5205/// cumulative arc-length abscissas.  The chain starts at the free endpoint
5206/// belonging to the EARLIEST-selected end edge (so users get the natural
5207/// "first pick carries the law start" orientation); a single selected edge is
5208/// its own chain oriented t0→t1 (which also admits a closed edge — the law's
5209/// end radii must then match, enforced downstream by `blend_edge_variable`).
5210/// Branching (a vertex shared by 3+ selected edges), closed rings of several
5211/// edges, and disconnected selections refuse with named errors.
5212fn resolve_selected_chain(
5213    solid: &BrepSolid,
5214    edge_points: &[Vec3],
5215    entry: &str,
5216    tol: f64,
5217) -> Result<Vec<ChainLink>, KernelRefusal> {
5218    // Endpoint identity uses the kernel-wide COINCIDENCE_DISTANCE_FLOOR — the
5219    // same band the constant-radius group's corner detector applies.
5220    let band = crate::tolerance::COINCIDENCE_DISTANCE_FLOOR;
5221
5222    struct Resolved {
5223        edge_id: u64,
5224        start: Vec3,
5225        end: Vec3,
5226        arc: Vec<(f64, f64)>,
5227        length: f64,
5228    }
5229    let mut resolved: Vec<Resolved> = Vec::with_capacity(edge_points.len());
5230    for point in edge_points {
5231        let edge_id = resolve_edge_by_point(solid, *point)?;
5232        if resolved.iter().any(|r| r.edge_id == edge_id) {
5233            return Err(KernelRefusal::input(
5234                KernelStage::Collect,
5235                "duplicate_edge",
5236                format!("{entry}: the same edge was selected more than once"),
5237            ));
5238        }
5239        let edge = solid
5240            .edges
5241            .iter()
5242            .find(|e| e.id == edge_id)
5243            .ok_or_else(|| {
5244                KernelRefusal::internal(
5245                    KernelStage::Collect,
5246                    "chain_resolved_edge",
5247                    format!("{entry}: resolved edge vanished"),
5248                )
5249            })?;
5250        let (arc, length) = edge_arc_table(&edge.curve, edge.t0, edge.t1, tol)?;
5251        if !(length > 0.0) {
5252            return Err(KernelRefusal::input(
5253                KernelStage::Collect,
5254                "zero_length_edge",
5255                format!("{entry}: selected edge has zero length"),
5256            ));
5257        }
5258        resolved.push(Resolved {
5259            edge_id,
5260            start: edge
5261                .curve
5262                .evaluate(edge.t0)
5263                .or_refuse(KernelStage::Collect, "chain_edge_start")?,
5264            end: edge
5265                .curve
5266                .evaluate(edge.t1)
5267                .or_refuse(KernelStage::Collect, "chain_edge_end")?,
5268            arc,
5269            length,
5270        });
5271    }
5272    let n = resolved.len();
5273    if n == 1 {
5274        let only = resolved.remove(0);
5275        return Ok(vec![ChainLink {
5276            input_index: 0,
5277            forward: true,
5278            arc: only.arc,
5279            length: only.length,
5280            abscissa: 0.0,
5281        }]);
5282    }
5283
5284    // Cluster the 2n endpoints; each entry is (edge index, is_start_end).
5285    let mut clusters: Vec<(Vec3, Vec<(usize, bool)>)> = Vec::new();
5286    for (i, r) in resolved.iter().enumerate() {
5287        for (point, is_start) in [(r.start, true), (r.end, false)] {
5288            match clusters
5289                .iter_mut()
5290                .find(|(anchor, _)| anchor.sub(point).length() < band)
5291            {
5292                Some((_, members)) => members.push((i, is_start)),
5293                None => clusters.push((point, vec![(i, is_start)])),
5294            }
5295        }
5296    }
5297    if clusters.iter().any(|(_, members)| members.len() > 2) {
5298        return Err(KernelRefusal::input(
5299            KernelStage::Collect,
5300            "chain_branching",
5301            format!(
5302                "{entry}: selected edges must form one open chain \
5303                 (a vertex is shared by three or more selected edges)"
5304            ),
5305        ));
5306    }
5307    let free: Vec<usize> = clusters
5308        .iter()
5309        .enumerate()
5310        .filter(|(_, (_, members))| members.len() == 1)
5311        .map(|(c, _)| c)
5312        .collect();
5313    if free.len() != 2 {
5314        return Err(KernelRefusal::input(
5315            KernelStage::Collect,
5316            "chain_open",
5317            format!(
5318                "{entry}: selected edges must form one OPEN chain \
5319                 (closed rings and disconnected selections are not supported)"
5320            ),
5321        ));
5322    }
5323    // Start at the free end whose edge appears EARLIEST in the selection.
5324    let start_cluster = *free
5325        .iter()
5326        .min_by_key(|&&c| clusters[c].1[0].0)
5327        .expect("two free ends");
5328
5329    // Walk the chain.
5330    let mut links: Vec<ChainLink> = Vec::with_capacity(n);
5331    let mut visited = vec![false; n];
5332    let mut abscissa = 0.0_f64;
5333    let mut cluster = start_cluster;
5334    for _ in 0..n {
5335        let Some(&(edge_index, entered_at_start)) = clusters[cluster]
5336            .1
5337            .iter()
5338            .find(|(edge_index, _)| !visited[*edge_index])
5339        else {
5340            return Err(KernelRefusal::input(
5341                KernelStage::Collect,
5342                "chain_walk",
5343                format!(
5344                    "{entry}: selected edges are not connected into one chain"
5345                ),
5346            ));
5347        };
5348        visited[edge_index] = true;
5349        let r = &resolved[edge_index];
5350        links.push(ChainLink {
5351            input_index: edge_index,
5352            forward: entered_at_start,
5353            arc: r.arc.clone(),
5354            length: r.length,
5355            abscissa,
5356        });
5357        abscissa += r.length;
5358        let exit_point = if entered_at_start { r.end } else { r.start };
5359        cluster = clusters
5360            .iter()
5361            .position(|(anchor, _)| anchor.sub(exit_point).length() < band)
5362            .ok_or_else(|| {
5363                KernelRefusal::internal(
5364                    KernelStage::Collect,
5365                    "chain_cluster",
5366                    format!("{entry}: chain walk lost an endpoint cluster"),
5367                )
5368            })?;
5369    }
5370    if visited.iter().any(|v| !v) {
5371        return Err(KernelRefusal::input(
5372            KernelStage::Collect,
5373            "chain_connected",
5374            format!(
5375                "{entry}: selected edges are not connected into one chain"
5376            ),
5377        ));
5378    }
5379    Ok(links)
5380}
5381
5382/// Sample the law into one edge's `(parameter fraction, radius)` stop list —
5383/// the caller-side bridge from chain abscissa into the `radius_at` closure
5384/// seam that `blend_edge_variable` builds over its stops.
5385///
5386/// `scale` maps chain abscissa into the law's own abscissa units
5387/// (`law.total_length() / chain_length` — proportional, so a law built from
5388/// the measured chain lengths maps 1:1).  The base stop count derives from
5389/// the law's curvature: piecewise-linear sampling of a C1, piecewise-C2
5390/// function over step `h` errs at most `h²·max|r''|/8`, so
5391/// `h = sqrt(8·tol/max|r''|)` holds the sampling error under the SSI fit
5392/// tolerance the variable lane is built to.  That bound is exact for
5393/// arc-length-linear (straight) edges; curved edges bend the
5394/// parameter→abscissa map, so each interval is additionally midpoint-checked
5395/// against the law and bisected on violation (up to 8 halvings — a 4⁸ ≈ 6·10⁴
5396/// error reduction, decisive for any C1 law).  The base count is capped at
5397/// 256 intervals: 4× the blend march's 64-station density
5398/// (blend/stations.rs), beyond which denser stops cannot move any station's
5399/// sampled radius by more than the fit tolerance.
5400fn law_stops_for_link(
5401    link: &ChainLink,
5402    law: &crate::law::RadiusLaw,
5403    scale: f64,
5404    tol: f64,
5405) -> Vec<(f64, f64)> {
5406    let radius_at_fraction = |fraction: f64| -> f64 {
5407        let arc = arc_length_at_fraction(&link.arc, fraction);
5408        let chain_s = if link.forward {
5409            link.abscissa + arc
5410        } else {
5411            link.abscissa + (link.length - arc)
5412        };
5413        law.radius_at(chain_s * scale)
5414    };
5415    // Curvature of the law in edge-fraction units: d²r/df² ≤
5416    // max|r''|·(scale·length)² for the arc-length-linear map.
5417    let curvature = law
5418        .max_second_derivative(link.abscissa * scale, (link.abscissa + link.length) * scale)
5419        * (scale * link.length).powi(2);
5420    let base = if curvature * 0.125 <= tol {
5421        1usize
5422    } else {
5423        ((curvature / (8.0 * tol)).sqrt().ceil() as usize).clamp(1, 256)
5424    };
5425    let mut stops: Vec<(f64, f64)> = (0..=base)
5426        .map(|j| {
5427            let fraction = j as f64 / base as f64;
5428            (fraction, radius_at_fraction(fraction))
5429        })
5430        .collect();
5431    // Midpoint refinement for curved parameter→abscissa maps.
5432    let mut depth = 0usize;
5433    while depth < 8 {
5434        let mut refined: Vec<(f64, f64)> = Vec::with_capacity(stops.len());
5435        let mut inserted = false;
5436        for pair in stops.windows(2) {
5437            refined.push(pair[0]);
5438            let mid_fraction = 0.5 * (pair[0].0 + pair[1].0);
5439            let law_mid = radius_at_fraction(mid_fraction);
5440            let linear_mid = 0.5 * (pair[0].1 + pair[1].1);
5441            if (law_mid - linear_mid).abs() > tol {
5442                refined.push((mid_fraction, law_mid));
5443                inserted = true;
5444            }
5445        }
5446        refined.push(*stops.last().expect("at least two stops"));
5447        stops = refined;
5448        if !inserted {
5449            break;
5450        }
5451        depth += 1;
5452    }
5453    stops
5454}
5455
5456/// Fillet (or chamfer) a chain of edges under a composable radius law
5457/// evaluated on the chain's cumulative arc-length abscissa (the OCCT
5458/// `Law_Composite` model; see [`crate::law::RadiusLaw`]).  The selected edges
5459/// must form ONE OPEN CHAIN (or be a single edge); the chain starts at the
5460/// free end of the earliest-selected end edge, and the law's abscissa maps
5461/// proportionally onto the chain's measured arc length (a law built with the
5462/// chain's own lengths — e.g. [`crate::law::RadiusLaw::from_vertex_radii`] —
5463/// maps 1:1).  Endpoint radii are met exactly; radii at shared chain vertices
5464/// match by the law's continuity, so the per-edge blends miter through the
5465/// corners; a chain whose blends cannot be mitered REFUSES rather than
5466/// distorting the law through the sequential rebuild.
5467pub fn fillet_edges_variable_law(
5468    solid: &BrepSolid,
5469    edge_points: &[Vec3],
5470    edge_names: Option<&[String]>,
5471    law: &crate::law::RadiusLaw,
5472    chamfer: bool,
5473    name: Option<&str>,
5474) -> Result<BrepSolid, KernelRefusal> {
5475    // One blend operation: the reports of an earlier one, never consumed, are
5476    // dropped as it starts (nested calls keep this operation's).
5477    let _operation = crate::blend::BlendOperation::enter();
5478    const ENTRY: &str = "fillet_edges_variable_law";
5479    if edge_points.is_empty() {
5480        return Err(KernelRefusal::input(
5481            KernelStage::Collect,
5482            "law_selection",
5483            format!("{ENTRY}: no edges selected"),
5484        ));
5485    }
5486    let tolerances = crate::KernelTolerances::for_solid(solid, 1e-7);
5487    let chain = resolve_selected_chain(solid, edge_points, ENTRY, tolerances.intersection_fit)?;
5488    fillet_variable_law_on_chain(
5489        solid,
5490        edge_points,
5491        edge_names,
5492        &chain,
5493        law,
5494        chamfer,
5495        name,
5496        ENTRY,
5497        tolerances.intersection_fit,
5498    )
5499}
5500
5501/// The natural per-vertex user model: radius `vertex_radii[i]` at chain
5502/// vertex `i` (in CHAIN order, starting at the free end of the
5503/// earliest-selected edge), smoothly interpolated along the chain
5504/// (monotone C1 — every vertex radius met exactly, no overshoot).  Requires
5505/// exactly one radius per chain vertex (`edges + 1`).
5506pub fn fillet_edges_variable_vertex_radii(
5507    solid: &BrepSolid,
5508    edge_points: &[Vec3],
5509    edge_names: Option<&[String]>,
5510    vertex_radii: &[f64],
5511    chamfer: bool,
5512    name: Option<&str>,
5513) -> Result<BrepSolid, KernelRefusal> {
5514    // One blend operation: the reports of an earlier one, never consumed, are
5515    // dropped as it starts (nested calls keep this operation's).
5516    let _operation = crate::blend::BlendOperation::enter();
5517    const ENTRY: &str = "fillet_edges_variable_vertex_radii";
5518    if edge_points.is_empty() {
5519        return Err(KernelRefusal::input(
5520            KernelStage::Collect,
5521            "vertex_radii_selection",
5522            format!("{ENTRY}: no edges selected"),
5523        ));
5524    }
5525    let tolerances = crate::KernelTolerances::for_solid(solid, 1e-7);
5526    let chain = resolve_selected_chain(solid, edge_points, ENTRY, tolerances.intersection_fit)?;
5527    let lengths: Vec<f64> = chain.iter().map(|link| link.length).collect();
5528    let law = crate::law::RadiusLaw::from_vertex_radii(&lengths, vertex_radii)
5529        .map_err(|error| error.with_message(|error| format!("{ENTRY}: {error}")))?;
5530    fillet_variable_law_on_chain(
5531        solid,
5532        edge_points,
5533        edge_names,
5534        &chain,
5535        &law,
5536        chamfer,
5537        name,
5538        ENTRY,
5539        tolerances.intersection_fit,
5540    )
5541}
5542
5543/// Shared law-entry tail: sample per-edge stop lists from the law over the
5544/// resolved chain and run the variable group core (miter-or-refuse: no
5545/// sequential fallback for tapered chains — see `fillet_edges_variable_impl`).
5546#[allow(clippy::too_many_arguments)]
5547fn fillet_variable_law_on_chain(
5548    solid: &BrepSolid,
5549    edge_points: &[Vec3],
5550    edge_names: Option<&[String]>,
5551    chain: &[ChainLink],
5552    law: &crate::law::RadiusLaw,
5553    chamfer: bool,
5554    name: Option<&str>,
5555    entry: &str,
5556    tol: f64,
5557) -> Result<BrepSolid, KernelRefusal> {
5558    let chain_length: f64 = chain.iter().map(|link| link.length).sum();
5559    let scale = law.total_length() / chain_length;
5560    let mut per_edge_stops: Vec<Vec<(f64, f64)>> = vec![Vec::new(); edge_points.len()];
5561    for link in chain {
5562        per_edge_stops[link.input_index] = law_stops_for_link(link, law, scale, tol);
5563    }
5564    fillet_edges_variable_impl(
5565        solid,
5566        edge_points,
5567        edge_names,
5568        &per_edge_stops,
5569        chamfer,
5570        name,
5571        entry,
5572        false,
5573    )
5574}
5575
5576/// Asymmetric (two-distance) chamfer of a GROUP of edges, the app entry: each
5577/// selected edge (resolved by a point on it) gets a `d1 × d2` bevel (§6.11).
5578/// Edges are chamfered independently — asymmetric chamfers keep sharp vertices,
5579/// so there is no shared-corner blending.
5580pub fn chamfer_edges_asymmetric(
5581    solid: &BrepSolid,
5582    edge_points: &[Vec3],
5583    edge_names: Option<&[String]>,
5584    d1: f64,
5585    d2: f64,
5586    name: Option<&str>,
5587) -> Result<BrepSolid, KernelRefusal> {
5588    // One blend operation: the reports of an earlier one, never consumed, are
5589    // dropped as it starts (nested calls keep this operation's).
5590    let _operation = crate::blend::BlendOperation::enter();
5591    if edge_points.is_empty() {
5592        return Err(KernelRefusal::input(
5593            KernelStage::Collect,
5594            "asymmetric_selection",
5595            "chamfer_edges_asymmetric: no edges selected",
5596        ));
5597    }
5598    let mut result = solid.clone();
5599    let mut done = vec![false; edge_points.len()];
5600    // `edge_names[index]` is keyed by INPUT position; the loop resolves each
5601    // point on the EVOLVING `result`, but enumerates the input points in order,
5602    // so the index alignment holds.
5603    for (index, point) in edge_points.iter().enumerate() {
5604        if done[index] {
5605            continue;
5606        }
5607        let edge_id = resolve_edge_by_point(&result, *point)?;
5608        let edge_name = per_edge_name(edge_names, name, index);
5609        // A smooth chain the selection covers whole is chamfered as one unit
5610        // (its setbacks run on through the tangent joins).
5611        if chamfer_asym_curved_on() {
5612            if let Some(members) = selected_chain(&result, edge_id, edge_points, &done)? {
5613                let faces = setback_faces(&result, edge_id)?;
5614                let law = crate::blend::setback::SetbackLaw::Distances { faces, distances: [d1, d2] };
5615                result = chamfer_by_setback_law(&result, edge_id, law, edge_name, "chamfer_edges_asymmetric", true)?;
5616                for member in members {
5617                    done[member] = true;
5618                }
5619                continue;
5620            }
5621        }
5622        result = chamfer_edge_asymmetric(&result, edge_id, d1, d2, edge_name)?;
5623        done[index] = true;
5624    }
5625    refuse_invalid_result(&result, "chamfer_edges_asymmetric")?;
5626    Ok(result)
5627}
5628
5629/// Distance-angle chamfer of a GROUP of edges, the app entry: each selected
5630/// edge (resolved by a point on it) gets a setback `d1` on face 1 and a chamfer
5631/// face at `angle_rad` from face 1 (§6.11); `d2` is constructed per edge.
5632pub fn chamfer_edges_angle(
5633    solid: &BrepSolid,
5634    edge_points: &[Vec3],
5635    edge_names: Option<&[String]>,
5636    d1: f64,
5637    angle_rad: f64,
5638    name: Option<&str>,
5639) -> Result<BrepSolid, KernelRefusal> {
5640    // One blend operation: the reports of an earlier one, never consumed, are
5641    // dropped as it starts (nested calls keep this operation's).
5642    let _operation = crate::blend::BlendOperation::enter();
5643    if edge_points.is_empty() {
5644        return Err(KernelRefusal::input(
5645            KernelStage::Collect,
5646            "angle_selection",
5647            "chamfer_edges_angle: no edges selected",
5648        ));
5649    }
5650    let mut result = solid.clone();
5651    let mut done = vec![false; edge_points.len()];
5652    for (index, point) in edge_points.iter().enumerate() {
5653        if done[index] {
5654            continue;
5655        }
5656        let edge_id = resolve_edge_by_point(&result, *point)?;
5657        let edge_name = per_edge_name(edge_names, name, index);
5658        // A smooth chain the selection covers whole is chamfered as one unit,
5659        // as `chamfer_edges_asymmetric` does.
5660        if chamfer_asym_curved_on() && d1 > 0.0 && d1.is_finite() && angle_rad > 1e-9 && angle_rad < std::f64::consts::PI {
5661            if let Some(members) = selected_chain(&result, edge_id, edge_points, &done)? {
5662                let [first, _] = setback_faces(&result, edge_id)?;
5663                let law = crate::blend::setback::SetbackLaw::Angle { first, distance: d1, angle: angle_rad };
5664                result = chamfer_by_setback_law(&result, edge_id, law, edge_name, "chamfer_edges_angle", true)?;
5665                for member in members {
5666                    done[member] = true;
5667                }
5668                continue;
5669            }
5670        }
5671        result = chamfer_edge_angle(&result, edge_id, d1, angle_rad, edge_name)?;
5672        done[index] = true;
5673    }
5674    refuse_invalid_result(&result, "chamfer_edges_angle")?;
5675    Ok(result)
5676}
5677
5678/// Debug aid (`BREP_DEBUG_NETWORK`): every face loop as its coedge walk, with
5679/// each edge's stored vertices, so a loop the surgery left open can be read
5680/// against the input it was built from.
5681fn dump_loops_debug(label: &str, solid: &BrepSolid) {
5682    for shell in &solid.shells {
5683        for face in &shell.faces {
5684            for (index, loop_record) in face.loops.iter().enumerate() {
5685                let walk: Vec<String> = loop_record
5686                    .coedges
5687                    .iter()
5688                    .map(|coedge| {
5689                        // The pcurve's walk endpoints in the face's (u, v), so a
5690                        // loop that closes in space but not in parameter space
5691                        // (a periodic carrier's seam) is visible in the dump.
5692                        let uv = coedge
5693                            .pcurve
5694                            .domain()
5695                            .ok()
5696                            .and_then(|[q0, q1]| {
5697                                let a = coedge.pcurve.evaluate(q0).ok()?;
5698                                let b = coedge.pcurve.evaluate(q1).ok()?;
5699                                Some(format!("uv[({:.4},{:.4})->({:.4},{:.4})]", a.x, a.y, b.x, b.y))
5700                            })
5701                            .unwrap_or_default();
5702                        match solid.edges.iter().find(|e| e.id == coedge.edge_id) {
5703                            Some(edge) => format!(
5704                                "c{}:e{}{}({}->{}){uv}",
5705                                coedge.id,
5706                                edge.id,
5707                                if coedge.forward { "+" } else { "-" },
5708                                edge.start_vertex_id,
5709                                edge.end_vertex_id
5710                            ),
5711                            None => format!("c{}:e{}?MISSING", coedge.id, coedge.edge_id),
5712                        }
5713                    })
5714                    .collect();
5715                eprintln!(
5716                    "{label} face {} ({:?}) loop {index}: {}",
5717                    face.id,
5718                    face.name,
5719                    walk.join(" ")
5720                );
5721            }
5722        }
5723    }
5724}
5725
5726