Skip to main content

brep_blend/blending/fillet/
edges.rs

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