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