Skip to main content

brep_kernel/blending/blend/
mod.rs

1//! General rolling-ball blends (Golovanov §4.9 + §6.9 surgery).
2//!
3//! The blend surface is the rational surface (4.9.1) built from three
4//! curves: the two support curves cr(t) ⊂ F1 and cs(t) ⊂ F2 where a
5//! sphere of radius ρ touches both faces, and the middle curve at the
6//! intersection of the two tangent planes, weighted w(t) = cos(α/2)
7//! (4.9.3).  The tangency system (4.9.2) + the section-plane constraint
8//! (4.9.5) — the sphere center pinned to the normal plane of the edge —
9//! is solved per station by Newton with a finite-difference Jacobian.
10//!
11//! Topology is rebuilt the §6.9 way, with NO tool solid and NO boolean:
12//! each mating face's loop swaps the blended edge's coedge for a coedge
13//! on its support curve (trimming the adjacent seam edge when the face
14//! is a closed carrier with seam-in-one-loop topology), and the blend
15//! face is inserted with its own seam.  Open edges take the same route
16//! (`edge/open.rs`), and a whole SELECTION goes through `network.rs`, which
17//! marches every stripe against the original solid and solves each shared
18//! corner from its ball before anything is cut.
19
20mod carve;
21mod chain;
22mod collapse;
23pub(crate) mod convex_parallel;
24mod corner;
25pub(crate) mod creased_rim;
26mod edge;
27mod fold;
28mod miter;
29mod network;
30pub(crate) use network::STRIPE_PINCH_TAPER_WHAT;
31mod planar_chart;
32mod restrict;
33pub(super) mod rollover;
34mod rollover_surgery;
35pub(crate) mod setback;
36pub(crate) mod runout;
37pub(crate) mod split_rim;
38pub(crate) mod sheet_ends;
39mod stations;
40mod rows;
41mod track_fit;
42
43/// A transverse end with parallel normals needs a tapered runout, not cutter
44/// composition. The network tries that runout before propagating this refusal.
45pub(crate) const TANGENTIAL_TRANSVERSE_END: &str = "tangential_transverse_end";
46
47pub(crate) fn is_tangential_transverse_end(refusal: &crate::KernelRefusal) -> bool {
48    matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what }
49        if what == TANGENTIAL_TRANSVERSE_END)
50}
51
52/// Whether the open march's local station refinement runs. Escape hatch
53/// `BREP_BLEND_REFINE=0` restores the uniform ladder exactly; a test turns it
54/// off for its own thread with `set_refinement_off_for_test`.
55pub(crate) fn station_refinement_on() -> bool {
56    switch!(live "BREP_BLEND_REFINE", true)
57}
58
59thread_local! {
60    static BLEND_NOTES: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
61}
62
63thread_local! {
64    /// Set only while the open-pad composition (`fillet/edges.rs`, the
65    /// 2026-10-17 face-ring report) builds its two stages on this thread.
66    static OPEN_PAD_NETWORK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
67}
68
69/// Runs `build` as the open-pad composition's network: the open march takes
70/// a station where a contact crosses its carrier's domain boundary and the
71/// row fit breaks there (`march_open_stations_core`), and the march extends
72/// past a section end that lies outside the overshoot
73/// (`open_station_parameters`). Both are what the composition's walls need
74/// (the F6 blend rail of the reported ring stood 7.1e-5 off its carrier at
75/// the boundary; the pads' stripes start before their trims) and both move
76/// a body the plain network already built (2026-10-18: the reported model's
77/// F6 moved by a refinement rung and a broken row), so outside the
78/// composition every network is built exactly as before. Restores the flag
79/// after.
80pub(crate) fn with_open_pad_network<T>(build: impl FnOnce() -> T) -> T {
81    /// Restores the previous flag on every exit path, an unwinding panic
82    /// included, so a later network on this thread never inherits it.
83    struct Reset(bool);
84    impl Drop for Reset {
85        fn drop(&mut self) {
86            OPEN_PAD_NETWORK.with(|flag| flag.set(self.0));
87        }
88    }
89    let _reset = Reset(OPEN_PAD_NETWORK.with(|flag| flag.replace(true)));
90    build()
91}
92
93/// Whether the march runs as the open-pad composition's network (see
94/// [`with_open_pad_network`]).
95pub(in crate::blend) fn open_pad_network_on() -> bool {
96    OPEN_PAD_NETWORK.with(|flag| flag.get())
97}
98
99/// An equal-radius convex star on four planar faces with no common ball closes
100/// as the rolling ball does: a ridge cylinder between two sphere triangles.
101/// `BREP_BLEND_RIDGE_STAR=0` restores the ribbon fill.
102const RIDGE_STAR_DEFAULT: bool = true;
103
104pub(crate) fn ridge_star_on() -> bool {
105    switch!(live "BREP_BLEND_RIDGE_STAR", RIDGE_STAR_DEFAULT)
106}
107
108/// The STOPPED-END rollover of an open stripe (user bug F10, 2026-11-02):
109/// a track that leaves its mate across a tangent edge before the stripe's
110/// own vertex and never comes back — the F10 fillet's rails run 1.1e-2 past
111/// faces 13/23's boundaries onto the F8 blend faces 19/26 — has its tail
112/// re-marched on the neighbour from the crossing station and the cap's
113/// legs drawn on the neighbours. Default OFF: `BREP_BLEND_STOPPED_END_ROLLOVER=1`
114/// turns it on. Promotion owes the blend/fillet filters and both censuses
115/// with the switch on.
116const STOPPED_END_ROLLOVER_DEFAULT: bool = false;
117
118pub(crate) fn stopped_end_rollover_on() -> bool {
119    switch!(live "BREP_BLEND_STOPPED_END_ROLLOVER", STOPPED_END_ROLLOVER_DEFAULT)
120}
121
122/// Equal-length chains are unchanged either way; unequal ones move their
123/// stations, so it lands behind this switch until its census:
124/// `BREP_BLEND_CHAIN_ARC_STATIONS=1` turns it on, `=0` off;
125/// `set_chain_arc_stations_for_test` forces it on a test's own thread.
126const CHAIN_ARC_STATIONS_DEFAULT: bool = false;
127
128pub(crate) fn chain_arc_stations_on() -> bool {
129    switch!(live "BREP_BLEND_CHAIN_ARC_STATIONS", CHAIN_ARC_STATIONS_DEFAULT)
130}
131
132#[derive(Clone, Debug, PartialEq)]
133pub(crate) enum StripeRadius {
134    Constant(f64),
135    /// `(edge fraction, radius)` stops sorted by fraction, interpolated
136    /// linearly between and held flat past the ends: `blend_edge_variable`'s
137    /// convention, which the law entries sample into.
138    Stops(Vec<(f64, f64)>),
139}
140
141impl StripeRadius {
142    /// From a stop list: one constant when every stop carries the same
143    /// radius (to 1e-12 relative, the single-edge lane's own test).
144    pub(crate) fn from_stops(stops: &[(f64, f64)]) -> Self {
145        let mut sorted = stops.to_vec();
146        sorted.sort_by(|a, b| a.0.total_cmp(&b.0));
147        match sorted.first() {
148            Some(&(_, first)) if sorted.iter().all(|(_, r)| (r - first).abs() <= 1e-12 * (1.0 + first.abs())) => {
149                StripeRadius::Constant(first)
150            }
151            _ => StripeRadius::Stops(sorted),
152        }
153    }
154
155    /// The radius at an edge fraction in `[0, 1]` (clamped).
156    pub(crate) fn at_fraction(&self, fraction: f64) -> f64 {
157        match self {
158            StripeRadius::Constant(radius) => *radius,
159            StripeRadius::Stops(stops) => {
160                let fraction = fraction.clamp(0.0, 1.0);
161                if fraction <= stops[0].0 {
162                    return stops[0].1;
163                }
164                for pair in stops.windows(2) {
165                    if fraction <= pair[1].0 {
166                        let width = (pair[1].0 - pair[0].0).max(1e-12);
167                        return pair[0].1 + (pair[1].1 - pair[0].1) * (fraction - pair[0].0) / width;
168                    }
169                }
170                stops[stops.len() - 1].1
171            }
172        }
173    }
174
175    /// The constant, for a constant law.
176    pub(crate) fn constant(&self) -> Option<f64> {
177        match self {
178            StripeRadius::Constant(radius) => Some(*radius),
179            StripeRadius::Stops(_) => None,
180        }
181    }
182
183    /// The largest radius the law takes.
184    pub(crate) fn largest(&self) -> f64 {
185        match self {
186            StripeRadius::Constant(radius) => *radius,
187            StripeRadius::Stops(stops) => stops.iter().map(|(_, r)| *r).fold(0.0, f64::max),
188        }
189    }
190
191    /// The law's END value at the edge's start (`at_start`) or finish: what
192    /// the user asked for at that vertex, and the constant every corner solve
193    /// there uses (C2).
194    pub(crate) fn end(&self, at_start: bool) -> f64 {
195        self.at_fraction(if at_start { 0.0 } else { 1.0 })
196    }
197
198    /// Whether every radius is positive and finite.
199    pub(crate) fn is_positive(&self) -> bool {
200        match self {
201            StripeRadius::Constant(radius) => radius.is_finite() && *radius > 0.0,
202            StripeRadius::Stops(stops) => !stops.is_empty() && stops.iter().all(|(_, r)| r.is_finite() && *r > 0.0),
203        }
204    }
205}
206
207
208/// Record what a blend that SHIPS needs its feature to say about it — today,
209/// a march whose rails still stand off their carriers after its station
210/// ladder and local refinement ran out. Drained per feature by the history
211/// loop ([`take_blend_notes`]), beside the soundness acceptance's repairs.
212pub(crate) fn record_blend_note(note: String) {
213    BLEND_NOTES.with(|notes| notes.borrow_mut().push(note));
214}
215
216/// Take every blend note recorded on this thread since the last call.
217/// Blending runs on the feature's own thread (no parallel march), so the
218/// history loop's drain sees every note its feature recorded.
219pub fn take_blend_notes() -> Vec<String> {
220    BLEND_NOTES.with(|notes| std::mem::take(&mut *notes.borrow_mut()))
221}
222
223/// The ledger's length, and a way back to it: a lane that refuses takes back
224/// the notes it recorded, so a note never describes a wall that did not ship.
225pub(crate) fn blend_notes_mark() -> usize {
226    BLEND_NOTES.with(|notes| notes.borrow().len())
227}
228
229pub(crate) fn blend_notes_truncate(mark: usize) {
230    BLEND_NOTES.with(|notes| notes.borrow_mut().truncate(mark));
231}
232
233/// A fillet chain wall that SHIPPED short of the construction request its
234/// accepted rung made (`KernelTolerances::model` on the wall between its
235/// rails): which wall — the blend face's name and its exact surface — what
236/// was asked, what the wall reads, and the typed budget that ran out.
237#[derive(Clone, Debug)]
238pub(crate) struct WallModelReport {
239    pub(crate) name: Option<String>,
240    pub(crate) surface: crate::NurbsSurface,
241    pub(crate) request: f64,
242    pub(crate) residual: f64,
243    /// What else the lane measured that the message must say (an unaccepted
244    /// rung's deficit, a ladder rung's local refinement), verbatim.
245    pub(crate) detail: Option<String>,
246    pub(crate) budget: crate::ApproximationBudget,
247}
248
249thread_local! {
250    static BLEND_APPROXIMATIONS: std::cell::RefCell<Vec<WallModelReport>> = const { std::cell::RefCell::new(Vec::new()) };
251}
252
253thread_local! {
254    static BLEND_OPERATION_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
255}
256
257/// One blend OPERATION's scope on this thread: every public blend entry point
258/// (and the history loop, around each feature) holds one. The OUTERMOST
259/// entry drops whatever an earlier operation recorded and nobody consumed —
260/// a direct API caller consumes ([`take_blend_approximations`]) after the
261/// operation whose reports it wants, before starting the next — while a
262/// nested entry (a fillet's per-edge chain blend) clears nothing, so every
263/// report of the operation in flight is kept, however many there are.
264pub(crate) struct BlendOperation;
265
266impl BlendOperation {
267    pub(crate) fn enter() -> BlendOperation {
268        BLEND_OPERATION_DEPTH.with(|depth| {
269            if depth.get() == 0 {
270                BLEND_APPROXIMATIONS.with(|reports| reports.borrow_mut().clear());
271                timing::begin_operation();
272            }
273            depth.set(depth.get() + 1);
274        });
275        BlendOperation
276    }
277}
278
279/// Whether the innermost open blend operation is the outermost one (no
280/// nested operation inside another).
281pub(crate) fn blend_operation_outermost() -> bool {
282    BLEND_OPERATION_DEPTH.with(|depth| depth.get() <= 1)
283}
284
285impl Drop for BlendOperation {
286    fn drop(&mut self) {
287        BLEND_OPERATION_DEPTH.with(|depth| {
288            depth.set(depth.get().saturating_sub(1));
289            if depth.get() == 0 {
290                timing::end_operation();
291            }
292        });
293    }
294}
295
296/// Phase timing of the blend lanes, on the same switch as the boolean's
297/// `boolean.<stage>_ms` lines: set `BREP_PROFILE` and the outermost blend
298/// operation prints one `blend.<measure>=<ms>` line per measure to stderr when
299/// it ends. Off (one `Cell` read per hook), nothing is recorded.
300///
301/// Measures ACCUMULATE: a stage that runs per stripe, per rung or per
302/// component adds to one entry and bumps its count, so the ledger reads as a
303/// split of the operation, not as the worst instance. `timing.*` entries are
304/// milliseconds, `count.*` entries are plain counters.
305pub(crate) mod timing {
306    use std::cell::{Cell, RefCell};
307    use web_time::Instant;
308
309    /// One ledger entry: the measure's name, its accumulated milliseconds
310    /// (zero for a `count.*` entry) and how many times it was recorded.
311    #[derive(Clone, Debug, PartialEq)]
312    pub struct BlendTiming {
313        pub measure: String,
314        pub ms: f64,
315        pub count: u64,
316    }
317
318    thread_local! {
319        static CAPTURE: Cell<bool> = const { Cell::new(false) };
320        static ENABLED: Cell<bool> = const { Cell::new(false) };
321        static TO_STDERR: Cell<bool> = const { Cell::new(false) };
322        static LEDGER: RefCell<Vec<BlendTiming>> = const { RefCell::new(Vec::new()) };
323    }
324
325    /// Turn the ledger on (or off) for the blend operations that FOLLOW on
326    /// this thread; `BREP_PROFILE` turns it on for every operation.
327    pub fn blend_timing_capture(on: bool) {
328        CAPTURE.with(|capture| capture.set(on));
329    }
330
331    /// Take every entry recorded on this thread since the last call (or the
332    /// last outermost operation's start), sorted by measure name.
333    pub fn take_blend_timings() -> Vec<BlendTiming> {
334        let mut entries = LEDGER.with(|ledger| std::mem::take(&mut *ledger.borrow_mut()));
335        entries.sort_by(|a, b| a.measure.cmp(&b.measure));
336        entries
337    }
338
339    /// Whether the hooks record anything right now.
340    pub(crate) fn enabled() -> bool {
341        ENABLED.with(|enabled| enabled.get())
342    }
343
344    pub(super) fn begin_operation() {
345        let profile = crate::profile::profile_enabled();
346        TO_STDERR.with(|to_stderr| to_stderr.set(profile));
347        let on = profile || CAPTURE.with(|capture| capture.get());
348        ENABLED.with(|enabled| enabled.set(on));
349        if on {
350            LEDGER.with(|ledger| ledger.borrow_mut().clear());
351        }
352    }
353
354    pub(super) fn end_operation() {
355        if TO_STDERR.with(|to_stderr| to_stderr.get()) {
356            let mut entries = LEDGER.with(|ledger| ledger.borrow().clone());
357            entries.sort_by(|a, b| a.measure.cmp(&b.measure));
358            for entry in entries {
359                if entry.measure.starts_with("timing.") {
360                    eprintln!("blend.{}={:.3} n={}", entry.measure, entry.ms, entry.count);
361                } else {
362                    eprintln!("blend.{}={}", entry.measure, entry.count);
363                }
364            }
365        }
366        ENABLED.with(|enabled| enabled.set(false));
367    }
368
369    fn add(measure: &str, ms: f64, count: u64) {
370        LEDGER.with(|ledger| {
371            let mut ledger = ledger.borrow_mut();
372            match ledger.iter_mut().find(|entry| entry.measure == measure) {
373                Some(entry) => {
374                    entry.ms += ms;
375                    entry.count += count;
376                }
377                None => ledger.push(BlendTiming { measure: measure.to_string(), ms, count }),
378            }
379        });
380    }
381
382    /// Add `ms` to a `timing.*` measure (one more occurrence).
383    pub(crate) fn record_ms(measure: &str, ms: f64) {
384        if enabled() {
385            add(measure, ms, 1);
386        }
387    }
388
389    /// Add `n` to a `count.*` measure.
390    pub(crate) fn record_count(measure: &str, n: u64) {
391        if enabled() {
392            add(measure, 0.0, n);
393        }
394    }
395
396    /// A stage timer: records its measure when stopped or dropped. Costs one
397    /// flag read when the ledger is off.
398    pub(crate) struct BlendTimer {
399        measure: &'static str,
400        started: Option<Instant>,
401    }
402
403    impl BlendTimer {
404        pub(crate) fn start(measure: &'static str) -> BlendTimer {
405            BlendTimer { measure, started: enabled().then(Instant::now) }
406        }
407
408        /// Milliseconds since the start (zero when the ledger is off).
409        pub(crate) fn elapsed_ms(&self) -> f64 {
410            self.started.map_or(0.0, |started| started.elapsed().as_secs_f64() * 1_000.0)
411        }
412
413        /// Record now and return the reading.
414        pub(crate) fn stop(mut self) -> f64 {
415            let ms = self.elapsed_ms();
416            if self.started.take().is_some() {
417                add(self.measure, ms, 1);
418            }
419            ms
420        }
421    }
422
423    impl Drop for BlendTimer {
424        fn drop(&mut self) {
425            if let Some(started) = self.started.take() {
426                add(self.measure, started.elapsed().as_secs_f64() * 1_000.0, 1);
427            }
428        }
429    }
430}
431pub use timing::{blend_timing_capture, take_blend_timings, BlendTiming};
432pub(crate) use timing::{record_count, BlendTimer};
433
434/// Record a wall that ships with its request unmet. Written by the rung that
435/// keeps its body; whether the body reaches a caller is decided at
436/// consumption ([`take_blend_approximations`]), not here. Every report of
437/// the operation in flight is kept (see [`BlendOperation`]).
438pub(crate) fn record_wall_model_report(report: WallModelReport) {
439    BLEND_APPROXIMATIONS.with(|reports| reports.borrow_mut().push(report));
440}
441
442
443/// Whether any wall-model report is waiting (the history loop reads the
444/// returned bodies only then).
445pub(crate) fn blend_approximations_pending() -> bool {
446    BLEND_APPROXIMATIONS.with(|reports| !reports.borrow().is_empty())
447}
448
449/// Bit-identical surfaces: the same degrees, knots and homogeneous control
450/// points, compared by their bits.
451pub(crate) fn same_surface(a: &crate::NurbsSurface, b: &crate::NurbsSurface) -> bool {
452    let bits = |values: &[f64]| values.iter().map(|value| value.to_bits()).collect::<Vec<_>>();
453    a.degree_u == b.degree_u
454        && a.degree_v == b.degree_v
455        && bits(&a.knots_u) == bits(&b.knots_u)
456        && bits(&a.knots_v) == bits(&b.knots_v)
457        && a.control_points.len() == b.control_points.len()
458        && a.control_points.iter().zip(&b.control_points).all(|(row_a, row_b)| {
459            row_a.len() == row_b.len()
460                && row_a.iter().zip(row_b).all(|(p, q)| {
461                    [p.x, p.y, p.z, p.w].map(f64::to_bits) == [q.x, q.y, q.z, q.w].map(f64::to_bits)
462                })
463        })
464}
465
466/// Whether `face_name` names the report's wall: its exact name, or that
467/// name with the `[k]` (decimal) suffix `ensure_unique_face_names` gives a
468/// colliding name at registration. Nothing else: no prefix, no other suffix.
469fn names_the_wall(face_name: &Option<String>, report_name: &Option<String>) -> bool {
470    match (face_name, report_name) {
471        (Some(face), Some(report)) => {
472            face == report
473                || face.strip_prefix(report.as_str()).and_then(|rest| rest.strip_prefix('[')).and_then(|rest| rest.strip_suffix(']')).is_some_and(
474                    |index| !index.is_empty() && index.bytes().all(|byte| byte.is_ascii_digit()),
475                )
476        }
477        (None, None) => true,
478        _ => false,
479    }
480}
481
482/// Consume EVERY wall-model report recorded on this thread since the last
483/// call, in ONE snapshot, against ALL the bodies a call returned
484/// (`(body name, solid)`): a report becomes a typed `blend.wall_model`
485/// [`crate::Approximation`] on each body carrying its wall — a face with a
486/// bit-identical surface AND the report's name, exactly or as registration
487/// renamed it (`NAME[k]`) — and is dropped when no returned body carries it
488/// (a lane that refused, a body a later step discarded). A wall carried by
489/// two returned bodies (one surface, bit for bit, in both) is reported on
490/// both: the reading is a property of that surface. Reports for one wall
491/// collapse to the last. Never a match by name alone.
492/// `take_blend_approximations(&[])` discards everything recorded (the
493/// history loop's stale drain before a feature runs).
494pub fn take_blend_approximations(bodies: &[(&str, &crate::BrepSolid)]) -> Vec<crate::Approximation> {
495    let snapshot = BLEND_APPROXIMATIONS.with(|reports| std::mem::take(&mut *reports.borrow_mut()));
496    let mut unique: Vec<WallModelReport> = Vec::new();
497    for report in snapshot {
498        unique.retain(|kept| !(kept.name == report.name && same_surface(&kept.surface, &report.surface)));
499        unique.push(report);
500    }
501    let mut approximations = Vec::new();
502    for (body, solid) in bodies {
503        for report in &unique {
504            let carried = solid.shells.iter().flat_map(|shell| &shell.faces).any(|face| {
505                names_the_wall(&face.name, &report.name) && same_surface(&face.surface, &report.surface)
506            });
507            if carried {
508                let wall = report.name.as_deref().unwrap_or("(unnamed)");
509                let unaccepted = matches!(report.budget.reason, crate::BudgetReason::Unaccepted | crate::BudgetReason::Unread);
510                let budget = match report.budget.mechanism {
511                    crate::BudgetMechanism::LocalRounds => format!(
512                        "local refinement stopped: {:?} after {} of {} rounds, {} of {} stations per segment",
513                        report.budget.reason, report.budget.rounds_used, report.budget.rounds_limit,
514                        report.budget.stations, report.budget.station_limit,
515                    ),
516                    crate::BudgetMechanism::StationRungs => format!(
517                        "the open march's station ladder stopped: {:?} after {} of {} global station rungs, {} of {} stations",
518                        report.budget.reason, report.budget.rounds_used, report.budget.rounds_limit,
519                        report.budget.stations, report.budget.station_limit,
520                    ),
521                };
522                let unknown = report.budget.unread > 0;
523                let rails = report.budget.measured_component == crate::MeasuredComponent::Rails;
524                let mut message = if !unaccepted && (rails || unknown) {
525                    // A request that covers the rails and the wall says WHICH
526                    // it measured, and never offers a partial reading as the
527                    // worst: with unread intervals the worst is unknown.
528                    let what = if rails {
529                        format!("the fillet wall {wall}'s support rails stand")
530                    } else {
531                        format!("the fillet wall {wall} stands")
532                    };
533                    let against = if rails {
534                        "off their exact construction (their carriers / the exact ball contacts)"
535                    } else {
536                        "from the rolling ball between its rails"
537                    };
538                    let reading = if unknown {
539                        format!(
540                            "an UNKNOWN distance {against}: {} interval(s) could not be read (the largest READABLE reading is {:.3e} mm, not the worst)",
541                            report.budget.unread, report.residual
542                        )
543                    } else {
544                        format!("{:.3e} mm {against}", report.residual)
545                    };
546                    format!(
547                        "{what} {reading}, against a construction request of {:.3e} mm (accepted at the intersection-fit bar); {budget}",
548                        report.request,
549                    )
550                } else if unaccepted {
551                    format!(
552                        "the blend wall {wall} ships from a rung that never met acceptance: its worst reading \
553                         {:.3e} mm against its acceptance bar {:.3e} mm; {budget}",
554                        report.residual, report.request,
555                    )
556                } else {
557                    format!(
558                        "the fillet wall {wall} stands {:.3e} mm from the rolling ball between its rails, against a \
559                         construction request of {:.3e} mm (accepted at the intersection-fit bar); {budget}",
560                        report.residual, report.request,
561                    )
562                };
563                if let Some(detail) = &report.detail {
564                    message = format!("{message} ({detail})");
565                }
566                approximations.push(crate::Approximation {
567                    code: if unaccepted { "blend.wall_acceptance" } else { "blend.wall_model" }.to_string(),
568                    body: body.to_string(),
569                    measured: report.residual,
570                    bar: report.request,
571                    volume_bound: None,
572                    edges: Vec::new(),
573                    budget: Some(report.budget.clone()),
574                    message,
575                });
576            }
577        }
578    }
579    approximations
580}
581
582
583pub use chain::{blend_smooth_chain, blend_smooth_chain_if_closed};
584pub(crate) use chain::smooth_chain_members;
585pub(crate) use corner::round_concave_chain_corner;
586pub use corner::round_convex_corner;
587pub use edge::{blend_closed_edge, blend_closed_edge_knot_aware, blend_edge_variable, blend_open_edge, is_pcurve_floor_refusal, with_pcurve_knot_retry};
588pub(crate) use collapse::is_full_width_collapse;
589pub(crate) use planar_chart::{
590    fit_planar_charts_to_trims, is_planar_chart_refusal, planar_chart_overrun,
591};
592pub(crate) use track_fit::PCURVE_OFF_FLOOR;
593pub(crate) use edge::{consumed_band, is_consumed_snap, is_rail_collapse};
594pub(crate) use network::{
595    blend_star_network, blend_star_network_laws, blend_star_network_with_corner_policy, degenerate_corner_setbacks, mixed_convexity_corner, mixed_convexity_corners, selection_convexity, MixedCorner,
596};
597pub(crate) use miter::{is_marched_fit_off_carriers, is_miter_support_overrun};
598/// The two faces each selected edge lies on, in the network's mate order
599/// (the open-pad composition reads which is planar and which is the boss).
600pub(crate) fn selection_mates<'a>(
601    solid: &'a crate::topology::BrepSolid,
602    edge_ids: &[u64],
603    radius: f64,
604) -> Result<Vec<(&'a crate::topology::EdgeRecord, [&'a crate::topology::FaceRecord; 2])>, crate::KernelRefusal> {
605    Ok(network::stripe_mates(solid, edge_ids, radius)?
606        .into_iter()
607        .map(|(edge, first, second)| (edge, [first.face, second.face]))
608        .collect())
609}
610
611pub(crate) use runout::{build_runout_walls, plan_runout, RunoutPlan};
612pub(crate) use fold::{is_rail_fold, is_wall_fold, wall_loop_refusal, WALL_FOLDS};
613pub(crate) use stations::is_ball_off_carrier;
614pub(crate) use network::is_ball_does_not_fit;
615
616/// Off the switch every closed rim's two support pcurves are refitted to their
617/// rail's projected track (`edge/closed.rs::refit_closed_support_pcurve`, the
618/// closed chain's support-piece fitter: a dense track of analytic feet, a
619/// verified fit ladder and the shipped read), 96 of the half torus's 98 ms of
620/// rows. On the switch each trim is first READ as shipped at the same floor
621/// (`track_fit::read_shipped_pcurve`, `PCURVE_REFINEMENT_TOLERANCE`): a plane
622/// mate's trim is the rail's own control points through the plane's affine
623/// chart (exact by construction, the exact revolution lane's rule); any other
624/// mate's trim, or an image that misses, takes the refit as before (the
625/// march's own interpolated pcurve was measured as a candidate and dropped:
626/// 8.5e-5 off on the half torus's torus mate). The shipped contract is
627/// unchanged (every trim read within the floor); the bytes are not, so it
628/// landed OFF and was promoted by its census (the kernel battery, the case
629/// manifest and hlr_tests with the switch on). ON by default;
630/// `BREP_BLEND_CLOSED_TRIM_READ_FIRST=0` is the escape hatch back to the refit
631/// road, `=1` forces it on; `set_closed_trim_read_first_for_test` forces
632/// either way on a test's thread.
633const CLOSED_TRIM_READ_FIRST_DEFAULT: bool = true;
634
635pub(crate) fn closed_trim_read_first_on() -> bool {
636    switch!(live "BREP_BLEND_CLOSED_TRIM_READ_FIRST", CLOSED_TRIM_READ_FIRST_DEFAULT)
637}
638
639
640/// The check solves 31 centres per interval by continuation from the
641/// neighbour, each a full station Newton with a finite-difference Jacobian
642/// rebuilt at every iteration (eleven evaluations of the tangency system a
643/// centre, 89 of the half torus's 169 ms of march). On the switch each centre
644/// is seeded by a quadratic extrapolation through the last three and solved
645/// by the chord method with the Jacobian carried from centre to centre
646/// (`stations::solve_station_state_chord`), to the plain solver's own stop;
647/// the plain solver from the neighbour is the fall-back for anything the
648/// chord cannot finish. The centres are the same roots to the same tolerance,
649/// not the same bits: the declared wall reading moves in its last digits, its
650/// verdict and the body do not, which is why it landed OFF and was promoted
651/// by its census. ON by default; `BREP_BLEND_CLOSED_WALL_PREDICT=0` is the
652/// escape hatch back to the plain continuation solves, `=1` forces it on;
653/// `set_closed_wall_predict_for_test` forces either way on a test's thread.
654const CLOSED_WALL_PREDICT_DEFAULT: bool = true;
655
656pub(crate) fn closed_wall_predict_on() -> bool {
657    switch!(live "BREP_BLEND_CLOSED_WALL_PREDICT", CLOSED_WALL_PREDICT_DEFAULT)
658}
659
660
661// BREP lane L: begin keyway_floor_open_mixed_corner_20261014
662pub(crate) use corner::round_mixed_concave_open_corner;
663// BREP lane L: end keyway_floor_open_mixed_corner_20261014
664
665
666// Lane R7 (2026-10-19): the tapered cusp runout; `BREP_BLEND_TAPER_RUNOUT`.
667pub(crate) mod taper_runout;
668
669// 2026-10-21: the local radius relief of a folding constant fillet;
670// `BREP_BLEND_RADIUS_RELIEF`.
671pub(crate) mod relief;