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