brep_boolean/csg/imprint/driver.rs
1use crate::{KernelRefusal, KernelStage, OrRefuse, RefusalClass, MAX_FIT_STATIONS};
2
3// Fit-split instrumentation (2026-11-02): where the section
4// fit's time goes, read only under BREP_PROFILE and printed once per
5// `build_imprints` as `imprint.fit_split`. Zero behaviour: timers only.
6#[derive(Clone, Copy)]
7pub(super) enum FitSplitLane { InitialFit, EvenSliverTotal, RefineTotal, Consistency, Midspan, MidspanRefine, CarrierUpper, Representatives, Seeded, FullRefit, CarrierReadings }
8const FIT_SPLIT_LANES: usize = 11;
9const FIT_SPLIT_NAMES: [&str; FIT_SPLIT_LANES] = ["initial_fit", "even_sliver_total", "refine_total", "consistency", "midspan", "midspan_refine", "carrier_upper", "representatives", "seeded", "full_refit", "carrier_readings"];
10thread_local! {
11 static FIT_SPLIT: std::cell::RefCell<([f64; FIT_SPLIT_LANES], [u64; FIT_SPLIT_LANES])> = const { std::cell::RefCell::new(([0.0; FIT_SPLIT_LANES], [0; FIT_SPLIT_LANES])) };
12}
13pub(super) fn fit_split_started() -> Option<Instant> { crate::profile::profile_enabled().then(Instant::now) }
14pub(super) fn fit_split_add(lane: FitSplitLane, started: Option<Instant>, calls: u64) {
15 if let Some(started) = started {
16 FIT_SPLIT.with(|cell| { let mut cell = cell.borrow_mut(); cell.0[lane as usize] += started.elapsed().as_secs_f64() * 1e3; cell.1[lane as usize] += calls; });
17 }
18}
19pub(super) fn fit_split_timed<T>(lane: FitSplitLane, run: impl FnOnce() -> T) -> T {
20 let started = fit_split_started();
21 let out = run();
22 fit_split_add(lane, started, 1);
23 out
24}
25pub(super) fn fit_split_report() {
26 let (ms, calls) = FIT_SPLIT.with(|cell| std::mem::take(&mut *cell.borrow_mut()));
27 let line = FIT_SPLIT_NAMES.iter().enumerate().map(|(i, name)| format!("{name}={:.2}/{}", ms[i], calls[i])).collect::<Vec<_>>().join(" ");
28 profile_line!("imprint.fit_split {line}");
29 let (calls, stations, points, params_ms, interpolate_ms, measure_ms) = crate::fit::station_set_split_take();
30 profile_line!("imprint.station_set calls={calls} stations={stations} points={points} params_ms={params_ms:.2} interpolate_ms={interpolate_ms:.2} measure_ms={measure_ms:.2}");
31}
32
33/// The degree a marched section is interpolated at (2026-09-27). The march
34/// puts every station on both carriers; the fit decides how far the curve
35/// strays BETWEEN them, and a cubic's O(h^4) there left `BadBoolean`'s
36/// sphere×bore rim 2.5e-7 off the bore with a mean bias of −1.2e-8 that both
37/// trims inherited (+1.14e-6 on the solid). A quintic through the same
38/// stations reads 8.5e-9 and +6e-11 with the same knots and control-point
39/// count. More stations bought the same accuracy on 2026-09-26 and were
40/// reverted for their cost: the watertight tessellator samples every interior
41/// knot, so every scan downstream scales with station count, and a degree does
42/// not add knots. `BREP_SECTION_FIT_DEGREE=3` restores the cubic. The gate on
43/// the mid-span refinement, as a multiple of the fit tolerance (2026-09-27): a
44/// marched section whose unrefined fit misses a carrier between stations by
45/// more than this is UNDERSAMPLED — the 20° cylinder crossing of
46/// `fillet-skew-cylinder-seam-split-20deg` sits 4e-5..8e-5 off, 470 times the
47/// tolerance, at any degree — and only such a section is given true
48/// intersection points until its mid-spans hold. Refining every section cost
49/// more downstream than it returned (the tessellator samples every knot).
50/// `BREP_SECTION_REFINE_GATE` sets the multiple (`on` for
51/// [`SECTION_REFINE_GATE`]). OFF BY DEFAULT: at k = 100 the sequential
52/// blend/direct_edit/imprint/boolean lib set costs +64 % and
53/// `oblique_multi_rim_cone_cap_tearing_push_refuses` goes red; k = 1000 costs
54/// +32 % and leaves the skew union +5.3e-4 off. This global switch stays off.
55/// Independently, a pair of grazing crossings on one trim edge requests a
56/// fit-floor check for that face pair below: those two nearby junctions and
57/// the intervening cap must survive the fit.
58fn section_refine_gate() -> Option<f64> {
59 static GATE: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
60 *GATE.get_or_init(|| match std::env::var("BREP_SECTION_REFINE_GATE") {
61 Ok(value) if value == "on" => Some(SECTION_REFINE_GATE),
62 Ok(value) => value.parse::<f64>().ok().filter(|gate| *gate >= 0.0),
63 Err(_) => None,
64 })
65}
66
67/// Why a section goes to `refine_section_against_carriers`.
68#[derive(Clone, Copy, Debug, PartialEq)]
69pub enum SectionRefineRoute {
70 /// `BREP_SECTION_REFINE_GATE`: every section, at the variable's multiple.
71 Global,
72 /// A recovered fit reproduces its march points; check it between them.
73 Recovered,
74 /// A pair of grazing crossings on one trim edge.
75 Grazing,
76 /// The standing fit missed the tolerance it was asked for. The polyline
77 /// deviation can overstate the carrier miss (a band-raised floor reads the
78 /// input's noise), so the refiner's own carrier measure decides: a section
79 /// whose mid-spans already hold the gate leaves at round 0 as `BelowGate`,
80 /// unchanged. Measured 2026-10-04: the StationCeiling fits it reaches ship
81 /// 4.7e-5 to 2.1e-4 off the true section; the refiner brings them to
82 /// 1e-8..3e-8.
83 UnmetRequest,
84 /// A standing fit that MET its request on no other route, whose kept
85 /// stations all lie on both carriers within the fit tolerance, but whose
86 /// curve stands further off the carriers BETWEEN them than the local gate
87 /// ([`carrier_miss_route`]). The polyline it met is the march's chords; an
88 /// interpolant through consistent stations can still ring between them.
89 /// Measured 2026-10-04 (94 cases): 23 of 285 fast-path sections,
90 /// 13 distinct pairs, read their mid-spans up to 6.03e-6 off while every
91 /// kept station read within 1e-7; fixture 28 t217 pair 118x474 read 1.59e-6
92 /// between stations 1.8e-9 off.
93 CarrierMiss,
94}
95
96/// The carrier-miss route for a fit that met its request on no other route:
97/// refine at the local gate when its mid-spans miss the carriers by more than
98/// the fit tolerance WHILE every kept station is within it. Stations off a
99/// carrier are the input's (moving them is the reserved relocation ruling),
100/// so such a section keeps the fast path and is not reported as refined. An
101/// unreadable reading (NaN) never routes.
102pub fn carrier_miss_route(station_upper: f64, midspan_upper: f64, fit_tolerance: f64) -> Option<(f64, SectionRefineRoute)> {
103 (station_upper.is_finite() && midspan_upper.is_finite() && station_upper <= fit_tolerance && midspan_upper > fit_tolerance)
104 .then_some((1.0, SectionRefineRoute::CarrierMiss))
105}
106
107/// The carrier readings [`carrier_miss_route`] decides on: the worst of both
108/// carriers over EVERY point of the section's run (the march's original
109/// stations, kept or dropped by the fit, so a fit through consistent kept
110/// stations cannot hide an inconsistent dropped one), and at the fit's
111/// mid-spans. Projector distances, so upper readings; NaN as soon as any is
112/// unreadable. The mid-span read is the route's TRIGGER, not a bound on the
113/// curve's maximum; [`knot_interior_carrier_upper`] is the finer read.
114pub fn fast_path_carrier_readings(fit: &PolylineFit, run: &[Vec3], first: &NurbsSurface, second: &NurbsSurface) -> (f64, f64) {
115 let read = |surface: &NurbsSurface, point: Vec3| project_point_to_surface(surface, point).map_or(f64::NAN, |projection| projection.distance);
116 let mut station = 0.0f64;
117 for point in run {
118 let (a, b) = (read(first, *point), read(second, *point));
119 station = if a.is_nan() || b.is_nan() || station.is_nan() { f64::NAN } else { station.max(a).max(b) };
120 }
121 (station, midspan_carrier_upper(fit, first, second))
122}
123
124/// SECTION-REFINE READ MEMO (`BREP_SECTION_REFINE_READ_MEMO`, default on, =0 restores;
125/// 2026-11-03). One section refine reads the carrier distance of
126/// the SAME points several times: a representative round reads every mid-span
127/// in [`midspan_misses`], again in [`midspan_carrier_upper`], and, once a
128/// representative has run, the mid-spans and knot interiors a second time on
129/// the unchanged fit. In wasm the planter's carrier upper reads were 103 ms of
130/// its 395 ms section fit. This keeps each `(carrier, point bits)` reading for
131/// one `refine_section_against_carriers_inner` call, error included, so every
132/// caller sees exactly the value (or error) the first read returned. Off, it
133/// is the projector itself.
134pub struct CarrierReads {
135 memo: Option<HashMap<(usize, [u64; 3]), Result<f64, String>>>,
136}
137impl CarrierReads {
138 pub fn off() -> Self {
139 Self { memo: None }
140 }
141 pub fn open() -> Self {
142 Self { memo: switch!(live "BREP_SECTION_REFINE_READ_MEMO", true).then(HashMap::default) }
143 }
144 /// The carrier distance at `point` on carrier `side` (0 first, 1 second).
145 pub fn distance(&mut self, side: usize, surface: &NurbsSurface, point: Vec3) -> Result<f64, String> {
146 let Some(memo) = self.memo.as_mut() else {
147 return project_point_to_surface(surface, point).map(|projection| projection.distance);
148 };
149 memo.entry((side, [point.x.to_bits(), point.y.to_bits(), point.z.to_bits()]))
150 .or_insert_with(|| project_point_to_surface(surface, point).map(|projection| projection.distance))
151 .clone()
152 }
153}
154
155/// The worst of BOTH carriers at the fit's mid-spans, each carrier read on its
156/// own and checked finite BEFORE any max (`f64::max` would drop a NaN from one
157/// carrier and pass the other's reading): NaN as soon as either is unreadable.
158pub(super) fn midspan_carrier_upper(fit: &PolylineFit, first: &NurbsSurface, second: &NurbsSurface) -> f64 {
159 midspan_carrier_upper_read(fit, first, second, &mut CarrierReads::off())
160}
161
162/// [`midspan_carrier_upper`] through a section-refine round's [`CarrierReads`].
163fn midspan_carrier_upper_read(fit: &PolylineFit, first: &NurbsSurface, second: &NurbsSurface, reads: &mut CarrierReads) -> f64 {
164 let mut read = |side: usize, surface: &NurbsSurface, point: Vec3| reads.distance(side, surface, point).unwrap_or(f64::NAN);
165 let mut worst = 0.0f64;
166 for span in 0..fit.parameters.len().saturating_sub(1) {
167 let mid = 0.5 * (fit.parameters[span] + fit.parameters[span + 1]);
168 let (a, b) = match fit.curve.evaluate(mid) {
169 Ok(point) => (read(0, first, point), read(1, second, point)),
170 Err(_) => (f64::NAN, f64::NAN),
171 };
172 if !(a.is_finite() && b.is_finite()) || worst.is_nan() {
173 return f64::NAN;
174 }
175 worst = worst.max(a).max(b);
176 }
177 worst
178}
179
180/// The curve's worst distance from both carriers at the quarter points of
181/// every one of its own knot spans (its native pieces, where an interpolant
182/// is extremal between knots), NaN as soon as any read is unreadable. Sampled
183/// and projector-based: an upper reading at its points, not a certified
184/// maximum of the curve.
185pub fn knot_interior_carrier_upper(curve: &NurbsCurve, first: &NurbsSurface, second: &NurbsSurface) -> f64 {
186 knot_interior_carrier_upper_read(curve, first, second, &mut CarrierReads::off())
187}
188
189/// [`knot_interior_carrier_upper`] through a section-refine round's [`CarrierReads`].
190fn knot_interior_carrier_upper_read(curve: &NurbsCurve, first: &NurbsSurface, second: &NurbsSurface, reads: &mut CarrierReads) -> f64 {
191 let mut read = |side: usize, surface: &NurbsSurface, point: Vec3| reads.distance(side, surface, point).unwrap_or(f64::NAN);
192 let Ok([t0, t1]) = curve.domain() else { return f64::NAN };
193 let mut knots: Vec<f64> = curve.knots.iter().copied().filter(|knot| *knot >= t0 && *knot <= t1).collect();
194 knots.dedup();
195 let mut worst = 0.0f64;
196 for pair in knots.windows(2) {
197 if pair[1] <= pair[0] {
198 continue;
199 }
200 for fraction in [0.25, 0.5, 0.75] {
201 let value = match curve.evaluate(pair[0] + (pair[1] - pair[0]) * fraction) {
202 Ok(point) => {
203 let (a, b) = (read(0, first, point), read(1, second, point));
204 if a.is_finite() && b.is_finite() { a.max(b) } else { f64::NAN }
205 }
206 Err(_) => f64::NAN,
207 };
208 worst = if worst.is_nan() || !value.is_finite() { f64::NAN } else { worst.max(value) };
209 }
210 }
211 worst
212}
213
214/// The refine route and its gate (a multiple of the fit tolerance) for one
215/// section, or `None` for the fast path.
216///
217/// A standing fit that MET its request takes exactly the routes that existed
218/// before: the global gate alone when set, else a recovered fit, else a grazing
219/// pair (read lazily, only when the first two do not apply), else nothing — it
220/// goes straight to `process_curve`, untouched.
221///
222/// A fit that MISSED its request is always refined, at the local gate 1, or at
223/// a tighter global gate. A looser global gate does not mask the miss: seam 60
224/// was a recovered fit missing its 1e-7 request, and `BREP_SECTION_REFINE_GATE`
225/// above 1 used to let it through. Its route stays `UnmetRequest` under any
226/// global gate, so its cost reads apart from the global gate's.
227pub fn section_refine_route(
228 global: Option<f64>,
229 recovered: bool,
230 grazing: impl FnOnce() -> bool,
231 met_requested: bool,
232) -> Option<(f64, SectionRefineRoute)> {
233 if !met_requested {
234 return Some((global.map_or(1.0, |gate| gate.min(1.0)), SectionRefineRoute::UnmetRequest));
235 }
236 global
237 .map(|gate| (gate, SectionRefineRoute::Global))
238 .or_else(|| recovered.then_some((1.0, SectionRefineRoute::Recovered)))
239 .or_else(|| grazing().then_some((1.0, SectionRefineRoute::Grazing)))
240}
241
242/// The multiple `BREP_SECTION_REFINE_GATE=on` uses: the smallest measured
243/// that trips the skew union's undersampled sections and leaves fixture 22 as
244/// it was (k = 10 flips it).
245const SECTION_REFINE_GATE: f64 = 100.0;
246
247/// The axis-aligned box of a curve's control points (rational ones read at
248/// their Cartesian position), grown by `margin` on every side: a box the
249/// curve cannot leave, since a NURBS curve with positive weights lies in its
250/// control hull.
251pub fn control_hull_box(curve: &NurbsCurve, margin: f64) -> [Vec3; 2] {
252 let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
253 let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
254 for control in &curve.control_points {
255 let w = if control.w.abs() > 1e-300 { control.w } else { 1.0 };
256 let point = Vec3::new(control.x / w, control.y / w, control.z / w);
257 low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
258 high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
259 }
260 [
261 Vec3::new(low.x - margin, low.y - margin, low.z - margin),
262 Vec3::new(high.x + margin, high.y + margin, high.z + margin),
263 ]
264}
265
266/// Whether two closed boxes share a point.
267pub fn boxes_overlap(a: &[Vec3; 2], b: &[Vec3; 2]) -> bool {
268 a[0].x <= b[1].x && b[0].x <= a[1].x && a[0].y <= b[1].y && b[0].y <= a[1].y && a[0].z <= b[1].z && b[0].z <= a[1].z
269}
270
271/// A clipped run's END span can be a sliver: the clip endpoint lands beside a
272/// march station, a spacing ratio to the run's median of 0.011 on
273/// `anotherBooleanFail`, and a global interpolant rings next to such a jump —
274/// the mid-spans near the ends miss their carriers by 1e-3, and bisecting them
275/// only makes the spacing more uneven (2026-09-27). The reduced witness
276/// (`imprint/tests.rs` `sliver_end_evening`) says what makes the jump ring: a
277/// sliver end ON both carriers fits to 3e-8, while the same end 2.7e-4 off
278/// the torus — the vendor's edge curves sit that far off the tori they
279/// bound, and the run's end is solved on such an edge — rings at 2e-3 with
280/// the interior at 3e-13 (2026-09-30). Below
281/// `SLIVER_END_FRACTION` of the median spacing the station beside the
282/// endpoint is RE-SOLVED at the middle of the merged gap as a fresh
283/// intersection point (the default, `BREP_SECTION_SLIVER_END=resolve`) or
284/// dropped (`drop`); `off` restores the unevened fit for a before/after
285/// reading. Returns how many ends were evened.
286///
287/// ON BY DEFAULT since 2026-09-30 (lane K6), behind the measurement in
288/// [`even_sliver_ends_measured`]: only a section whose fit shows the ringing signature
289/// ([`ringing_signature`]) is evened, and the evened fit stands only where it reads closer to
290/// the carriers by [`SLIVER_END_GAIN`]. The ringing is what a marched section carries into the
291/// result: on `anotherBooleanFail` the sphere sections leave the analytic vendor torus by
292/// 3.1e-3 within 1% of their span (measured against the STEP file's own `TOROIDAL_SURFACE`,
293/// not the projector), the cut torus faces depart from their edges by 2.6e-4 and the result
294/// shell's vector-area closure reads 1.88e-4 against a 3.83e-5 bar. Evened, the sections sit
295/// 5e-8 off, the shell closes at 1.7e-6 and the boolean takes 2.3 s instead of 9.1 s. The
296/// 2026-09-27 shelving reason was three fixture-25 exact-value pins moving under a blanket
297/// `resolve`; a blanket default also refused fixture 28's reversed subtract and broke fixture
298/// 26's idempotence, which is why the signature gates it. Fixture 25's sections do not show
299/// the signature at the shipped contrast and its pins stand.
300fn even_sliver_ends(
301 section: &mut Vec<Vec3>,
302 first: &NurbsSurface,
303 second: &NurbsSurface,
304 tolerance: f64,
305) -> Result<usize, String> {
306 static MODE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
307 let mode = MODE.get_or_init(|| {
308 std::env::var("BREP_SECTION_SLIVER_END").unwrap_or_else(|_| "resolve".to_string())
309 });
310 if !(mode == "drop" || mode == "resolve") {
311 return Ok(0);
312 }
313 let mut evened = 0;
314 // One sliver at a time: each removal changes the spans it sits between.
315 for _ in 0..SLIVER_END_ROUNDS {
316 let count = section.len();
317 if count < 6 {
318 break;
319 }
320 let mut chords: Vec<f64> = section.windows(2).map(|pair| pair[1].sub(pair[0]).length()).collect();
321 let lengths = chords.clone();
322 chords.sort_by(f64::total_cmp);
323 let median = chords[chords.len() / 2];
324 let spans = lengths.len();
325 let near_ends = [0, 1, 2, spans - 3, spans - 2, spans - 1];
326 let Some(&sliver) = near_ends
327 .iter()
328 .filter(|&&span| lengths[span] < sliver_end_fraction() * median)
329 .min_by(|a, b| lengths[**a].total_cmp(&lengths[**b]))
330 else {
331 break;
332 };
333 // The sliver's bounding stations are `sliver` and `sliver + 1`; a run
334 // endpoint is never moved. Of the interior ones, remove the one whose
335 // removal leaves the shorter merged span.
336 let mut candidates = Vec::new();
337 for station in [sliver, sliver + 1] {
338 if station == 0 || station == count - 1 {
339 continue;
340 }
341 let merged = section[station + 1].sub(section[station - 1]).length();
342 candidates.push((station, merged));
343 }
344 let Some(&(station, _)) = candidates.iter().min_by(|a, b| a.1.total_cmp(&b.1)) else {
345 break;
346 };
347 if mode == "resolve" {
348 let (before, after) = (section[station - 1], section[station + 1]);
349 let seed = before.add(after).scale(0.5);
350 let reach = 0.5 * after.sub(before).length();
351 match crate::surface_surface_intersection::refine_to_intersection(first, second, seed, tolerance, reach)? {
352 Some(point) => section[station] = point,
353 None => {
354 section.remove(station);
355 }
356 }
357 } else {
358 section.remove(station);
359 }
360 evened += 1;
361 }
362 Ok(evened)
363}
364
365/// At 0.25 six of `anotherBooleanFail`'s eight sections stay NoProgress
366/// (worst miss 2.7e-4); at 0.5 all eight are evened and fall below the
367/// refinement gate (worst miss 2.8e-3 -> 5.4e-8).
368const SLIVER_END_FRACTION: f64 = 0.5;
369
370/// How many sliver spans one section may lose, at most, over both ends. Every
371/// `anotherBooleanFail` section reaches this cap (the march lands several
372/// closely spaced stations beside each clip end), and the evened fits read
373/// 2.2e-8..5.4e-8 against the carriers under it; whether a higher cap would
374/// read differently was not measured (lane K6, 2026-09-30).
375const SLIVER_END_ROUNDS: usize = 4;
376
377/// `BREP_SECTION_SLIVER_FRACTION` overrides [`SLIVER_END_FRACTION`] for the
378/// measurement that picks it.
379fn sliver_end_fraction() -> f64 {
380 static FRACTION: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
381 *FRACTION.get_or_init(|| {
382 std::env::var("BREP_SECTION_SLIVER_FRACTION")
383 .ok()
384 .and_then(|value| value.parse::<f64>().ok())
385 .filter(|fraction| *fraction > 0.0 && *fraction < 1.0)
386 .unwrap_or(SLIVER_END_FRACTION)
387 })
388}
389
390fn section_fit_degree() -> usize {
391 static DEGREE: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
392 *DEGREE.get_or_init(|| {
393 std::env::var("BREP_SECTION_FIT_DEGREE")
394 .ok()
395 .and_then(|value| value.parse::<usize>().ok())
396 .filter(|degree| (1..=7).contains(degree))
397 .unwrap_or(5)
398 })
399}
400
401/// `BREP_SPAN_BUDGET`, read once: unset leaves [`ImprintOptions::span_budget`]
402/// in charge; `off` forces none; `fit` is the pair's `intersection_fit` at the
403/// operands' scale; a number is an absolute budget.
404#[derive(Clone, Copy, Debug, PartialEq)]
405enum SpanBudgetSwitch {
406 Unset,
407 Off,
408 Fit,
409 Absolute(f64),
410}
411
412fn span_budget_switch() -> SpanBudgetSwitch {
413 static SWITCH: std::sync::OnceLock<SpanBudgetSwitch> = std::sync::OnceLock::new();
414 *SWITCH.get_or_init(|| match std::env::var("BREP_SPAN_BUDGET") {
415 Ok(value) if value == "fit" => SpanBudgetSwitch::Fit,
416 Ok(value) if value == "off" || value == "0" => SpanBudgetSwitch::Off,
417 Ok(value) => value
418 .parse::<f64>()
419 .ok()
420 .filter(|budget| *budget > 0.0)
421 .map_or(SpanBudgetSwitch::Unset, SpanBudgetSwitch::Absolute),
422 Err(_) => SpanBudgetSwitch::Unset,
423 })
424}
425
426/// The span budget every march of this imprint carries: the option under
427/// its environment override. `fit` is what the catalogue names as the
428/// budget a lane may carry, the imprint's `intersection_fit`
429/// (`KernelTolerances::for_scale`), never the corrector's `tolerance`.
430pub(super) fn span_budget(options: &ImprintOptions, scale: f64) -> Option<f64> {
431 match span_budget_switch() {
432 SpanBudgetSwitch::Unset => options.span_budget,
433 SpanBudgetSwitch::Off => None,
434 SpanBudgetSwitch::Fit => Some(crate::KernelTolerances::for_scale(scale, options.tolerance).intersection_fit),
435 SpanBudgetSwitch::Absolute(budget) => Some(budget),
436 }
437}
438
439/// [`ImprintOptions::hermite_sections`] under its environment override.
440fn hermite_sections(options: &ImprintOptions) -> bool {
441 match std::env::var("BREP_HERMITE_SECTIONS").as_deref() {
442 Ok("0") => false,
443 Ok(_) => true,
444 Err(_) => options.hermite_sections,
445 }
446}
447
448/// [`ImprintOptions::exact_iso_pcurves`] under its environment override
449/// (`BREP_EXACT_ISO_PCURVES`: `0`/`off`, `check`, anything else on).
450#[derive(Clone, Copy, Debug, PartialEq, Eq)]
451pub(super) enum ExactIsoPcurves {
452 Off,
453 On,
454 /// The fit lane runs; the exact pcurve is built beside it and compared
455 /// (`ImprintBuilder::exact_pcurve_check`).
456 Check,
457}
458
459fn exact_iso_pcurves(options: &ImprintOptions) -> ExactIsoPcurves {
460 match mode_switch!(live "BREP_EXACT_ISO_PCURVES", options.exact_iso_pcurves) {
461 crate::env_read::Mode::Off => ExactIsoPcurves::Off,
462 crate::env_read::Mode::Check => ExactIsoPcurves::Check,
463 crate::env_read::Mode::On => ExactIsoPcurves::On,
464 }
465}
466
467thread_local! {
468 /// Set by `build_imprints_impl` as it returns, read by the boolean
469 /// right after ([`take_rescue_firings`]) into
470 /// `intersect.march_swap_rescue` and `intersect.clip_swap_rescue`; a
471 /// thread-local rather than a field so the shared record's eight
472 /// literals stay as they are.
473 static RESCUE_FIRINGS: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) };
474}
475
476/// `(march-order swap rescues, clip-order swap rescues)` of the last imprint
477/// built on this thread, cleared by the read.
478pub fn take_rescue_firings() -> (u64, u64) {
479 RESCUE_FIRINGS.with(|cell| cell.replace((0, 0)))
480}
481
482/// [`ImprintOptions::march_starts`] under its environment override, as
483/// `(ordered_starts, consume_starts, tree_seeds)` for every march this
484/// imprint runs. `BREP_MARCH_STARTS`: `0`/`off`; `order` (A3's ordering
485/// alone); `snap` (the ordering with run-through starts consumed); `tree`
486/// (A4 alone); `order+tree`; anything else all three.
487fn march_starts(options: &ImprintOptions, carrier_tree_seeds: bool) -> (bool, bool, bool) {
488 match std::env::var("BREP_MARCH_STARTS").as_deref() {
489 Ok("0") | Ok("off") => (false, false, false),
490 Ok("order") => (true, false, false),
491 Ok("snap") => (true, true, false),
492 Ok("tree") => (false, false, true),
493 Ok("order+tree") => (true, false, true),
494 Ok(_) => (true, true, true),
495 Err(_) => (options.march_starts, options.march_starts, options.march_starts || carrier_tree_seeds),
496 }
497}
498
499/// `BREP_SPAN_CENSUS=<file>`: one line per clipped section, appended, so a
500/// corpus replay can be read for station growth and refine-route firings
501/// under a budget. `BREP_CENSUS_LABEL` names the run on every line.
502fn span_census(line: impl FnOnce() -> String) {
503 if let Ok(path) = std::env::var("BREP_SPAN_CENSUS") {
504 use std::io::Write;
505 if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
506 let label = std::env::var("BREP_CENSUS_LABEL").unwrap_or_default();
507 let _ = writeln!(file, "span-budget census: label {label} {}", line());
508 }
509 }
510}
511
512/// A marched section is held to the fit tolerance against the CARRIERS, not
513/// only against the polyline it was fitted through (2026-09-26). The march
514/// refines every station onto both surfaces to `tolerance * 0.01`, but the
515/// cubic interpolant between stations is measured by `fit_polyline` against the
516/// polyline's own chords, which are further from the true curve than the
517/// interpolant is — so a systematic bias of the interpolant (2.8e-8 mean,
518/// 4.7e-7 worst, inside the bore on `BadBoolean`'s sphere/bore rim at 135
519/// stations) passed every check the fit could make, and both trims inherited it
520/// (+1.14e-6 on the solid's volume, against two independent readings agreeing
521/// to 1e-8). The check below evaluates the fitted curve at every mid-span,
522/// measures it against both carriers, and where it misses `fit tolerance *
523/// SECTION_MIDSPAN_FRACTION` inserts a TRUE intersection point there and
524/// refits. The interpolant's bias falls as h^4, so one round usually suffices.
525/// A round that neither halves the worst miss nor lowers the count of spans
526/// missing is not in that regime — a carrier's C0 crease puts a corner in the
527/// section (fixture 25's pierce solid), where every round only doubles the
528/// stations — so that round is discarded and the loop stops. It is also capped
529/// in rounds and stations, and names how it left.
530/// `BREP_SECTION_REFINE_GATE=off` switches it off, for the before/after reading
531/// and nothing else.
532pub(super) const SECTION_MIDSPAN_FRACTION: f64 = 0.1;
533const SECTION_MIDSPAN_ROUNDS: usize = 4;
534/// A round earns another if it cuts the worst mid-span miss by this factor
535/// (h^4 promises 16 for a halved spacing) OR lowers the count of spans
536/// missing: near the floor a few isolated spans hold the worst while the count
537/// falls, and on a corner the count GROWS round on round.
538const SECTION_MIDSPAN_PROGRESS: f64 = 0.5;
539
540/// Squared distance from `point` to the segment `from`-`to`.
541fn distance_to_segment_sq(point: Vec3, from: Vec3, to: Vec3) -> f64 {
542 point.distance_to_segment_squared(from, to)
543}
544
545/// The carrier miss, in fit tolerances, past which a section the mid-span
546/// refiner left unconverged goes to the 3-D Hermite lane
547/// (`BREP_SECTION_HERMITE_3D`). Measured on the lane's cases: a section that
548/// stalls near its floor (crossing cylinders, a tangent cone: 1.2e-8 to
549/// 1.3e-7 at a 1e-7 tolerance) keeps its fit; the swept rim walls' hairpin
550/// sections miss by 0.1 to 4.4e2.
551const HERMITE_3D_GROSS_MISS: f64 = 1e3;
552
553/// How a mid-span refinement left (`SECTION_MIDSPAN_*`), for the pair trace.
554#[derive(Clone, Copy, Debug, PartialEq)]
555pub enum MidspanExit {
556 /// Every mid-span within the floor of both carriers.
557 Converged,
558 /// The unrefined fit's worst mid-span is within the gate: the section is
559 /// sampled well enough that its degree carries it, and stations would
560 /// cost more downstream than they return.
561 BelowGate,
562 /// Some mid-span still misses and no inserted point could improve it
563 /// (the Newton failed, wandered off the span, or landed on a station
564 /// already present).
565 Stalled,
566 /// A round neither halved the worst miss nor lowered the count of spans
567 /// missing: not the h^4 regime, so the section has a corner the
568 /// interpolant cannot follow. That round's fit is discarded.
569 NoProgress,
570 RoundBudget,
571 StationCeiling,
572}
573
574/// Measure `fit` at every mid-span against both carriers; return the worst
575/// distance, the count of spans that miss `floor` and, for each of them the
576/// Newton could place, the refined intersection point to insert (with the
577/// span's index).
578fn midspan_misses(
579 fit: &PolylineFit,
580 first: &NurbsSurface,
581 second: &NurbsSurface,
582 floor: f64,
583 tolerance: f64,
584 reads: &mut CarrierReads,
585) -> Result<(f64, usize, Vec<(usize, Vec3)>), String> {
586 let mut worst = 0.0f64;
587 let mut missing = 0usize;
588 let mut inserts = Vec::new();
589 for span in 0..fit.parameters.len().saturating_sub(1) {
590 let mid = 0.5 * (fit.parameters[span] + fit.parameters[span + 1]);
591 let point = fit.curve.evaluate(mid)?;
592 let off = reads.distance(0, first, point)?.max(reads.distance(1, second, point)?);
593 worst = worst.max(off);
594 if off <= floor {
595 continue;
596 }
597 missing += 1;
598 // The refined point must stay on THIS span: half its chord is the reach.
599 let reach = 0.5 * fit.kept[span + 1].sub(fit.kept[span]).length();
600 if let Some(refined) = fit_split_timed(FitSplitLane::MidspanRefine, || crate::surface_surface_intersection::refine_to_intersection(
601 first, second, point, tolerance, reach,
602 ))? {
603 inserts.push((span, refined));
604 }
605 }
606 Ok((worst, missing, inserts))
607}
608
609/// Every mid-span miss of `fit` against both carriers, measured and nothing
610/// else: what [`even_sliver_ends_measured`] reads before and after evening.
611/// It refines nothing, so a section without a sliver end pays only the
612/// projections.
613fn midspan_misses_only(fit: &PolylineFit, first: &NurbsSurface, second: &NurbsSurface) -> Result<Vec<f64>, String> {
614 let mut misses = Vec::with_capacity(fit.parameters.len());
615 for span in 0..fit.parameters.len().saturating_sub(1) {
616 let mid = 0.5 * (fit.parameters[span] + fit.parameters[span + 1]);
617 let point = fit.curve.evaluate(mid)?;
618 let off = project_point_to_surface(first, point)?
619 .distance
620 .max(project_point_to_surface(second, point)?.distance);
621 misses.push(off);
622 }
623 Ok(misses)
624}
625
626/// The signature of a global interpolant ringing on a sliver end span: the
627/// worst mid-span miss sits in one of the [`SLIVER_END_SPANS`] spans at either
628/// end, is over the fit `floor`, AND stands [`SLIVER_RING_CONTRAST`] times
629/// above the median of the interior spans. A section sampled too coarsely for the carriers misses
630/// everywhere at once and does not show this; a section with fewer than two
631/// interior spans offers no evidence either way. Returns the end-span worst
632/// and the interior median when the signature is present.
633fn ringing_signature(misses: &[f64], floor: f64) -> Option<(f64, f64)> {
634 let spans = misses.len();
635 if spans < 2 * SLIVER_END_SPANS + 2 {
636 return None;
637 }
638 let ends = misses[..SLIVER_END_SPANS]
639 .iter()
640 .chain(&misses[spans - SLIVER_END_SPANS..])
641 .copied()
642 .fold(0.0f64, f64::max);
643 let mut interior: Vec<f64> = misses[SLIVER_END_SPANS..spans - SLIVER_END_SPANS].to_vec();
644 interior.sort_by(f64::total_cmp);
645 let median = interior[interior.len() / 2];
646 let worst = misses.iter().copied().fold(0.0f64, f64::max);
647 // Below the fit floor there is nothing to even: a 1e-8 miss on a planar
648 // section passed the contrast on fixture 26 and flipped its idempotence
649 // reading while changing nothing a bar could see.
650 (ends > floor.max(sliver_min_miss()) && ends >= worst && ends > sliver_ring_contrast() * median.max(f64::MIN_POSITIVE))
651 .then_some((ends, median))
652}
653
654/// How many spans at each end of a section [`even_sliver_ends`] may even —
655/// the same three it inspects — and where [`ringing_signature`] looks.
656const SLIVER_END_SPANS: usize = 3;
657
658/// The ringing signature's contrast: the end spans' worst mid-span miss over
659/// the interior spans' median. A converged march leaves its interior at
660/// 1e-9 and a sliver end rings at 1e-4..1e-3, so the ratio is 1e5 and up:
661/// `anotherBooleanFail`'s eight sections read 1.3e5..2.2e6 (interior
662/// 6e-10..2.6e-9, ends 1.6e-4..2.8e-3). A section whose interior itself
663/// misses is under-sampled rather than ringing, and evening its end moves a
664/// junction the assembler then cannot repair: fixture 28's pair 822×118
665/// (interior 1.5e-6, ends 1.4e-3, contrast 930) refused the reversed
666/// subtract whenever it was evened, while its pairs 474×118 (1.7e4) and
667/// 842×118 (1.4e5) are evened and build. Fixture 25's two sections read
668/// 2.2e3 and 5.9e3 (interior 2e-8) and keep their stations and their pins.
669/// 3e4 sits at least 4× from the nearest reading on either side
670/// (2026-09-30).
671const SLIVER_RING_CONTRAST: f64 = 3.0e4;
672
673/// `BREP_SECTION_SLIVER_CONTRAST` overrides [`SLIVER_RING_CONTRAST`] for the
674/// measurement that picks it.
675fn sliver_ring_contrast() -> f64 {
676 static CONTRAST: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
677 *CONTRAST.get_or_init(|| {
678 std::env::var("BREP_SECTION_SLIVER_CONTRAST")
679 .ok()
680 .and_then(|value| value.parse::<f64>().ok())
681 .filter(|contrast| *contrast >= 1.0)
682 .unwrap_or(SLIVER_RING_CONTRAST)
683 })
684}
685
686/// `BREP_SECTION_SLIVER_MIN_MISS` raises the absolute floor under the end
687/// spans' worst miss, for measurement only (the shipped floor is the fit
688/// tolerance).
689fn sliver_min_miss() -> f64 {
690 static MIN: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
691 *MIN.get_or_init(|| {
692 std::env::var("BREP_SECTION_SLIVER_MIN_MISS")
693 .ok()
694 .and_then(|value| value.parse::<f64>().ok())
695 .filter(|miss| *miss >= 0.0)
696 .unwrap_or(0.0)
697 })
698}
699
700/// How a sliver-end evening left, for the census line.
701#[derive(Clone, Copy, Debug, PartialEq)]
702pub enum SliverEvening {
703 /// No end span was shorter than the fraction, or the hatch is `off`.
704 NoSliver,
705 /// A sliver end exists but the unevened fit does not show the ringing
706 /// signature ([`ringing_signature`]): its stations stand.
707 NotRinging { slivers: usize, worst: f64 },
708 /// The evened section's fit reads at least [`SLIVER_END_GAIN`] times
709 /// closer to the carriers at its worst mid-span: the evened fit stands.
710 Accepted { slivers: usize, before: f64, after: f64, interior: f64 },
711 /// Evening did not earn its keep: the unevened fit stands, the stations
712 /// untouched.
713 Rejected { slivers: usize, before: f64, after: f64, interior: f64 },
714}
715
716/// A sliver-end evening must earn its keep: the evened fit stands only when
717/// its worst mid-span miss against both carriers falls by at least this
718/// factor. Measured on 2026-09-30 against the blanket default: `resolve` on
719/// every section that HAS a sliver end refused the reversed subtract of
720/// fixture 28 (`march_swap_rescue_recovers_reversed_subtract_t217`, an open
721/// loop) and made fixture 26's union read differently before and after
722/// operand splitting, while on `anotherBooleanFail` (2.8e-3 → 5e-8) and
723/// fixture 25 (2.0e-5 / 3.4e-5 → 9.2e-7) it cut the miss by 20× to 5e4×. A
724/// section whose evened fit is not clearly better keeps its stations.
725const SLIVER_END_GAIN: f64 = 2.0;
726
727/// [`even_sliver_ends`] with the measurement that decides whether it stands:
728/// fit the section as marched; if its mid-spans show the ringing signature
729/// ([`ringing_signature`]), even its sliver ends, fit again, and keep the
730/// evened fit only when its worst mid-span wins by [`SLIVER_END_GAIN`].
731/// Returns the section, its fit, the recovery flag of the fit that stands and
732/// the outcome.
733pub fn even_sliver_ends_measured(
734 section: Vec<Vec3>,
735 first: &NurbsSurface,
736 second: &NurbsSurface,
737 tolerance: f64,
738 fit_tolerance: f64,
739 maximum_fit_points: usize,
740 local_fit: bool,
741) -> Result<(Vec<Vec3>, PolylineFit, bool, SliverEvening), String> {
742 fit_split_timed(FitSplitLane::EvenSliverTotal, || even_sliver_ends_measured_inner(section, first, second, tolerance, fit_tolerance, maximum_fit_points, local_fit))
743}
744
745fn even_sliver_ends_measured_inner(
746 section: Vec<Vec3>,
747 first: &NurbsSurface,
748 second: &NurbsSurface,
749 tolerance: f64,
750 fit_tolerance: f64,
751 maximum_fit_points: usize,
752 local_fit: bool,
753) -> Result<(Vec<Vec3>, PolylineFit, bool, SliverEvening), String> {
754 let (fit, recovered) = fit_split_timed(FitSplitLane::InitialFit, || crate::fit::fit_polyline_of_degree_with_recovery(
755 §ion,
756 fit_tolerance,
757 maximum_fit_points,
758 local_fit,
759 section_fit_degree(),
760 ))?;
761 let mut evened = section.clone();
762 let slivers = even_sliver_ends(&mut evened, first, second, tolerance)?;
763 if slivers == 0 {
764 return Ok((section, fit, recovered, SliverEvening::NoSliver));
765 }
766 let misses = midspan_misses_only(&fit, first, second)?;
767 let Some((before, interior)) = ringing_signature(&misses, fit_tolerance) else {
768 let worst = misses.iter().copied().fold(0.0f64, f64::max);
769 return Ok((section, fit, recovered, SliverEvening::NotRinging { slivers, worst }));
770 };
771 let (evened_fit, evened_recovered) = crate::fit::fit_polyline_of_degree_with_recovery(
772 &evened,
773 fit_tolerance,
774 maximum_fit_points,
775 local_fit,
776 section_fit_degree(),
777 )?;
778 let after_misses = midspan_misses_only(&evened_fit, first, second)?;
779 let after = after_misses.iter().copied().fold(0.0f64, f64::max);
780 if let Ok(path) = std::env::var("BREP_SECTION_SLIVER_CENSUS") {
781 use std::io::Write;
782 if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
783 let chords = |points: &[Vec3]| points.windows(2).map(|pair| format!("{:.4e}", pair[1].sub(pair[0]).length())).collect::<Vec<_>>().join(" ");
784 let fmt = |values: &[f64]| values.iter().map(|value| format!("{value:.2e}")).collect::<Vec<_>>().join(" ");
785 let _ = writeln!(file, "sliver-end detail: stations {} -> {} kept {} -> {}", section.len(), evened.len(), fit.kept.len(), evened_fit.kept.len());
786 let _ = writeln!(file, "sliver-end detail: chords before: {}", chords(§ion));
787 let _ = writeln!(file, "sliver-end detail: chords after: {}", chords(&evened));
788 let _ = writeln!(file, "sliver-end detail: misses before: {}", fmt(&misses));
789 let _ = writeln!(file, "sliver-end detail: misses after: {}", fmt(&after_misses));
790 let _ = writeln!(file, "sliver-end detail: ends before: {:?} {:?}", section[0], section[section.len() - 1]);
791 let _ = writeln!(file, "sliver-end detail: ends after: {:?} {:?}", evened[0], evened[evened.len() - 1]);
792 }
793 }
794 if after * SLIVER_END_GAIN <= before {
795 Ok((evened, evened_fit, evened_recovered, SliverEvening::Accepted { slivers, before, after, interior }))
796 } else {
797 Ok((section, fit, recovered, SliverEvening::Rejected { slivers, before, after, interior }))
798 }
799}
800
801/// Refit `section` until its mid-spans sit within `floor` of both carriers,
802/// inserting true intersection points where they do not. Returns the fit that
803/// stands, the worst mid-span miss it still carries, the unrefined fit's worst
804/// (what the gate read), the rounds spent and the exit.
805/// Keep the single best measured refiner state (root grant 2026-10-04,
806/// accepted-representative sections only): replaced when `worst` is finite and
807/// no larger than the kept one (ties go to the later state). An unreadable
808/// reading is never kept. At most one snapshot is held.
809pub fn keep_best_state<S>(best: &mut Option<(S, f64)>, state: impl FnOnce() -> S, worst: f64) {
810 if worst.is_finite() && best.as_ref().is_none_or(|(_, kept)| worst <= *kept) {
811 *best = Some((state(), worst));
812 }
813}
814
815/// The rollback a budget-type exit (RoundBudget, StationCeiling, Stalled)
816/// takes: on a section where an ACCEPTED representative round ran, the kept
817/// best state when its COMMON reading is strictly lower than the current
818/// state's common reading on the same instrument (both carriers, finite, at the
819/// fit's mid-spans and its own knot-span quarter points). Otherwise `None`:
820/// the exit returns the current state exactly as before, with nothing cloned.
821/// An unreadable current reading never rolls back (it is not hidden).
822pub fn take_rollback<S>(best: &mut Option<(S, f64)>, current_common: f64, representative_ran: bool) -> Option<(S, f64)> {
823 let lower = matches!(best, Some((_, kept)) if representative_ran && current_common.is_finite() && *kept < current_common);
824 if lower { best.take() } else { None }
825}
826
827/// Which fit a refinement RETURNED: a receipt for controls, deciding nothing.
828#[derive(Clone, Copy, Debug, PartialEq)]
829pub enum RefinedFitSource {
830 /// The standing fit the caller passed in.
831 Standing,
832 /// The original full refit of the run, made directly (`full-unmatched`,
833 /// or the retry after an unreadable representative or a seeded stall).
834 FullRefit,
835 /// The seeded (forced-station) call and its own path: a `Fallback` path
836 /// IS the original full refit.
837 Seeded(crate::fit::SeededPath),
838 /// The representative candidate call and its own path: a `Fallback` path
839 /// IS the original full refit.
840 Representatives(crate::fit::SeededPath),
841 /// The best measured state the budget-exit rollback restored.
842 Rollback,
843}
844
845/// The refiner's receipt: whether the run took the representative route at
846/// all, and which fit it returned (None on an error return). Production
847/// callers discard it; only controls read it.
848#[allow(dead_code)]
849#[derive(Clone, Copy, Debug, Default, PartialEq)]
850pub struct RefineReceipt {
851 pub original_consistent: bool,
852 pub returned: Option<RefinedFitSource>,
853}
854
855
856/// `refine_section_against_carriers` with the representative switch passed
857/// in (the env hatch's value, so a control can take the seeded route without
858/// touching the process environment) and a receipt of the fit returned.
859#[allow(clippy::too_many_arguments)]
860pub fn refine_section_against_carriers_with(
861 section: &mut Vec<Vec3>,
862 fit: PolylineFit,
863 first: &NurbsSurface,
864 second: &NurbsSurface,
865 fit_tolerance: f64,
866 tolerance: f64,
867 local_fit: bool,
868 gate: f64,
869 representatives: bool,
870 receipt: &mut RefineReceipt,
871) -> Result<(PolylineFit, f64, f64, usize, MidspanExit), String> {
872 let started = fit_split_started();
873 let out = refine_section_against_carriers_inner(section, fit, first, second, fit_tolerance, tolerance, local_fit, gate, representatives, receipt);
874 fit_split_add(FitSplitLane::RefineTotal, started, 1);
875 out
876}
877
878#[allow(clippy::too_many_arguments)]
879fn refine_section_against_carriers_inner(
880 section: &mut Vec<Vec3>,
881 fit: PolylineFit,
882 first: &NurbsSurface,
883 second: &NurbsSurface,
884 fit_tolerance: f64,
885 tolerance: f64,
886 local_fit: bool,
887 gate: f64,
888 representatives: bool,
889 receipt: &mut RefineReceipt,
890) -> Result<(PolylineFit, f64, f64, usize, MidspanExit), String> {
891 // A reused receipt starts clean, so an error return leaves `returned`
892 // None as documented, never a previous call's value.
893 *receipt = RefineReceipt::default();
894 // Which fit `fit` currently is, and which fit `previous` holds.
895 let mut fit_source = RefinedFitSource::Standing;
896 let mut previous_source = RefinedFitSource::Standing;
897 let floor = fit_tolerance * SECTION_MIDSPAN_FRACTION;
898 let mut unrefined = f64::NAN;
899 let mut fit = fit;
900 let mut rounds = 0usize;
901 let mut previous: Option<(PolylineFit, f64, usize)> = None;
902 // Every true intersection point inserted so far: the residual-driven bend
903 // witnesses, which the refit must keep as stations.
904 let mut inserted_points: Vec<Vec3> = Vec::new();
905 // `BREP_SECTION_REFINE_CENSUS`: one `section-refine round:` line per round,
906 // bound to its section by the run's head and tail, so a stall can be read
907 // round by round (debug only; nothing below reads it).
908 let round_census = std::env::var("BREP_SECTION_REFINE_CENSUS").ok();
909 let (head, tail) = (section[0], section[section.len() - 1]);
910 // Whether EVERY original point of the run lies on both carriers within the
911 // fit tolerance (projector upper readings, NaN = no): only such a run takes
912 // the refiner-specific representative candidate below. A run with any
913 // point off a carrier keeps the existing seeded path exactly (moving or
914 // discounting input points is the reserved relocation ruling).
915 // `representatives` false (the `BREP_SECTION_REPRESENTATIVES=0` hatch)
916 // restores the seeded path everywhere for an attribution A/B only.
917 let consistency_started = fit_split_started();
918 let original_consistent = representatives
919 && section.iter().all(|point| {
920 let a = project_point_to_surface(first, *point).map_or(f64::NAN, |projection| projection.distance);
921 let b = project_point_to_surface(second, *point).map_or(f64::NAN, |projection| projection.distance);
922 a.is_finite() && b.is_finite() && a <= fit_tolerance && b <= fit_tolerance
923 });
924 receipt.original_consistent = original_consistent;
925 fit_split_add(FitSplitLane::Consistency, consistency_started, 1);
926 let mut refit_path = String::from("standing");
927 let mut refit_seeds = 0usize;
928 let mut refit_seeds_kept = 0usize;
929 let mut refit_seeds_outside_pool = 0usize;
930 let mut refit_pool = 0usize;
931 let mut refit_pool_discarded = 0usize;
932 let mut refit_pool_floor = f64::NAN;
933 let mut refit_seed_min_chord = f64::NAN;
934 // Trace only: what the closest seed pair is made of (kept station or
935 // refiner insert at each end), to place the near pair upstream.
936 let mut refit_seed_min_pair = "n/a";
937 // Trace only: every seed the full refit's pool rejects, by ORIGIN (a march
938 // station of the run, or a refiner insert) and by REASON (dropped by
939 // `station_pool`'s simplification, or kept by it and then conditioned
940 // away as a near-duplicate): [march simplified, march conditioned,
941 // insert simplified, insert conditioned].
942 let mut refit_rejected = [0usize; 4];
943 // Fits made for the round being judged (2 when its seeded fit stalled and
944 // the full refit was tried as well), and that retry's own cost.
945 let mut refit_trials = 1usize;
946 let mut retry_ms = 0.0f64;
947 // Whether the fit judged this round is an ACCEPTED seeded fit (not merely
948 // a seeded call: a seeded call that fell back already IS the full refit).
949 let mut seeded_refit = false;
950 // Whether the fit judged this round is an ACCEPTED representative
951 // candidate, and what that candidate call spent (its own interpolations
952 // and whether it ended on the full refit), kept apart from the fit's
953 // report, which on a fallback must stay the full refit's to the bit.
954 let mut representative_fit = false;
955 let mut refit_cost = crate::fit::RepresentativeCost::default();
956 // Whether an ACCEPTED representative round ran on this section, and the one
957 // best measured (fit, section) state kept for its budget exits.
958 let mut representative_ran = false;
959 let mut best_state: Option<((PolylineFit, Vec<Vec3>), f64)> = None;
960 let mut reads = CarrierReads::open();
961 loop {
962 // On an accepted representative candidate a read or refinement ERROR is
963 // not a refusal: the section takes the original full refit of the same
964 // run instead, as an unreadable read does below.
965 let (mut worst, missing, inserts) = match fit_split_timed(FitSplitLane::Midspan, || midspan_misses(&fit, first, second, floor, tolerance, &mut reads)) {
966 Ok(reading) => reading,
967 Err(_) if representative_fit => {
968 representative_fit = false;
969 seeded_refit = false;
970 let maximum_points = section.len().min(MAX_FIT_STATIONS);
971 fit = fit_split_timed(FitSplitLane::FullRefit, || fit_polyline_of_degree(section, fit_tolerance, maximum_points, local_fit, section_fit_degree()))?;
972 fit_source = RefinedFitSource::FullRefit;
973 refit_path = String::from("full-after-unreadable-representative");
974 refit_trials += 1;
975 refit_cost.full_refit = true;
976 continue;
977 }
978 Err(error) => return Err(error),
979 };
980 // An ACCEPTED representative candidate is judged on more than its
981 // mid-spans: both carriers must read finite at every mid-span and at
982 // the quarter points of the curve's own knot spans, and its worst is
983 // the worse of the two reads (sampled, projector upper readings; the
984 // carrier target is unchanged). An unreadable read never passes: the
985 // section takes the original full refit of the same run instead.
986 if representative_fit {
987 let interior = fit_split_timed(FitSplitLane::CarrierUpper, || knot_interior_carrier_upper_read(&fit.curve, first, second, &mut reads));
988 let midspans = fit_split_timed(FitSplitLane::CarrierUpper, || midspan_carrier_upper_read(&fit, first, second, &mut reads));
989 if interior.is_finite() && midspans.is_finite() {
990 worst = worst.max(interior).max(midspans);
991 } else {
992 representative_fit = false;
993 seeded_refit = false;
994 let maximum_points = section.len().min(MAX_FIT_STATIONS);
995 fit = fit_split_timed(FitSplitLane::FullRefit, || fit_polyline_of_degree(section, fit_tolerance, maximum_points, local_fit, section_fit_degree()))?;
996 fit_source = RefinedFitSource::FullRefit;
997 refit_path = String::from("full-after-unreadable-representative");
998 refit_trials += 1;
999 refit_cost.full_refit = true;
1000 continue;
1001 }
1002 }
1003 if let Some(path) = &round_census {
1004 use std::io::Write;
1005 if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
1006 let _ = writeln!(
1007 file,
1008 "section-refine round: head ({:.9}, {:.9}, {:.9}) tail ({:.9}, {:.9}, {:.9}) round {rounds} fit {refit_path} trials {refit_trials} retry_ms {retry_ms:.3} kept {} seeds {refit_seeds} seeds_kept {refit_seeds_kept} seeds_outside_pool {refit_seeds_outside_pool} seed_min_chord {refit_seed_min_chord:.3e} seed_min_pair {refit_seed_min_pair} rejected_march_simplified {} rejected_march_conditioned {} rejected_insert_simplified {} rejected_insert_conditioned {} pool {refit_pool} pool_discarded {refit_pool_discarded} pool_floor {refit_pool_floor:.3e} exit {:?} deviation {:.3e} floor {:.3e} run {} worst {:.3e} missing {} inserts_offered {} representatives {} witnesses {} candidate_fits {} candidate_full_refit {} candidate_end_offsets {:.3e}/{:.3e} seed_role {}",
1009 head.x, head.y, head.z, tail.x, tail.y, tail.z,
1010 fit.kept.len(),
1011 refit_rejected[0], refit_rejected[1], refit_rejected[2], refit_rejected[3], fit.report.exit, fit.report.deviation, fit.report.floor, section.len(), worst, missing, inserts.len(),
1012 refit_cost.representatives, refit_cost.witnesses, refit_cost.candidate_fits, refit_cost.full_refit,
1013 refit_cost.start_offset, refit_cost.end_offset,
1014 // On the representative path the seeds counted above are
1015 // WITNESSES (not forced); on the seeded path they are forced.
1016 if original_consistent { "witness" } else { "forced" }
1017 );
1018 // Trace only: where the full refit's band-raised floor comes
1019 // from on THIS run, and whether the run's own points are on
1020 // the carriers (input-consistent) or not. The band is
1021 // `dropped_band`'s reading (largest distance of a point the
1022 // pool drops from the segment between its surviving
1023 // neighbours); its point is classified as simplified away or
1024 // conditioned away, with its carrier distance and its gap to
1025 // the nearest run neighbour. Projector distances are upper
1026 // readings.
1027 let pool = crate::fit::polyline_station_pool(section, fit_tolerance);
1028 let simplified = crate::fit::simplify_polyline_indices(section, fit_tolerance);
1029 let mut band = (0.0f64, usize::MAX);
1030 for pair in pool.windows(2) {
1031 for index in pair[0] + 1..pair[1] {
1032 let off = distance_to_segment_sq(section[index], section[pair[0]], section[pair[1]]).sqrt();
1033 if off > band.0 {
1034 band = (off, index);
1035 }
1036 }
1037 }
1038 let carrier = |point: Vec3| -> f64 {
1039 let a = project_point_to_surface(first, point).map_or(f64::NAN, |projection| projection.distance);
1040 let b = project_point_to_surface(second, point).map_or(f64::NAN, |projection| projection.distance);
1041 if a.is_nan() || b.is_nan() { f64::NAN } else { a.max(b) }
1042 };
1043 let mut run_carrier = 0.0f64;
1044 for point in section.iter() {
1045 let off = carrier(*point);
1046 run_carrier = if off.is_nan() || run_carrier.is_nan() { f64::NAN } else { run_carrier.max(off) };
1047 }
1048 let (kind, band_carrier, gap) = if band.1 == usize::MAX {
1049 ("none", f64::NAN, f64::NAN)
1050 } else {
1051 let index = band.1;
1052 let kind = if simplified.binary_search(&index).is_ok() { "conditioned" } else { "simplified" };
1053 let mut gap = f64::INFINITY;
1054 if index > 0 {
1055 gap = gap.min(section[index].sub(section[index - 1]).length());
1056 }
1057 if index + 1 < section.len() {
1058 gap = gap.min(section[index + 1].sub(section[index]).length());
1059 }
1060 (kind, carrier(section[index]), gap)
1061 };
1062 let _ = writeln!(
1063 file,
1064 "section-refine band: head ({:.9}, {:.9}, {:.9}) tail ({:.9}, {:.9}, {:.9}) round {rounds} run {} pool {} tolerance {:.3e} band {:.3e} band_index {} of {} band_kind {kind} band_point_carrier_upper {band_carrier:.3e} band_point_gap {gap:.3e} run_carrier_upper {run_carrier:.3e}",
1065 head.x, head.y, head.z, tail.x, tail.y, tail.z,
1066 section.len(), pool.len(), fit_tolerance, band.0,
1067 if band.1 == usize::MAX { -1 } else { band.1 as i64 }, section.len()
1068 );
1069 }
1070 }
1071 if rounds == 0 {
1072 unrefined = worst;
1073 }
1074 // The rollback path's COMMON reading, only once an accepted
1075 // representative round has run and only on a run the refit can hold
1076 // (<= MAX_FIT_STATIONS): both carriers, finite, at the fit's mid-spans
1077 // and its own knot-span quarter points, for EVERY state compared
1078 // (representative, standing or full alike). One snapshot, the fit and
1079 // the run it was measured on as one coherent pair: its payload is one
1080 // PolylineFit and at most MAX_FIT_STATIONS points. Off this path
1081 // nothing is read or cloned.
1082 let mut current_common = f64::NAN;
1083 if representative_ran && section.len() <= MAX_FIT_STATIONS {
1084 let interior = fit_split_timed(FitSplitLane::CarrierUpper, || knot_interior_carrier_upper_read(&fit.curve, first, second, &mut reads));
1085 let midspans = fit_split_timed(FitSplitLane::CarrierUpper, || midspan_carrier_upper_read(&fit, first, second, &mut reads));
1086 current_common = if interior.is_finite() && midspans.is_finite() { interior.max(midspans) } else { f64::NAN };
1087 keep_best_state(&mut best_state, || (fit.clone(), section.clone()), current_common);
1088 }
1089 if worst <= floor {
1090 receipt.returned = Some(fit_source);
1091 return Ok((fit, worst, unrefined, rounds, MidspanExit::Converged));
1092 }
1093 if rounds == 0 && worst <= gate {
1094 receipt.returned = Some(fit_source);
1095 return Ok((fit, worst, unrefined, rounds, MidspanExit::BelowGate));
1096 }
1097 if let Some((earlier, earlier_worst, earlier_missing)) = previous.take() {
1098 // A round that did not earn its keep is discarded whole: the fit
1099 // of the last round that did stands (on a corner, the unrefined
1100 // fit), not whichever of the two happens to read a smaller max.
1101 if worst > earlier_worst * SECTION_MIDSPAN_PROGRESS && missing >= earlier_missing {
1102 // A SEEDED round that did not earn its keep is refitted once
1103 // with the original full refit of the same denser run, and
1104 // that is judged against the same earlier round before the
1105 // section stops. The seeded fit keeps fewer stations; on the
1106 // helmet's 2036x3009 section that gave back the whole of the
1107 // full refit's gain (6.335e-6 stood where 5.596e-7 was
1108 // reached). The full refit is the round the refiner made
1109 // before the seeded entry existed; only a round that fails
1110 // both ends the section, exactly as before.
1111 if seeded_refit {
1112 seeded_refit = false;
1113 let maximum_points = section.len().min(MAX_FIT_STATIONS);
1114 let retry_started = round_census.is_some().then(Instant::now);
1115 fit = fit_split_timed(FitSplitLane::FullRefit, || fit_polyline_of_degree(section, fit_tolerance, maximum_points, local_fit, section_fit_degree()))?;
1116 fit_source = RefinedFitSource::FullRefit;
1117 // Trace: one more fit for the SAME round, its cost, and no
1118 // seed counters carried over from the rejected seeded fit.
1119 refit_path = String::from("full-after-seeded-stall");
1120 // Every fit this round made: the candidate's (or the seeded
1121 // call's one) plus this retry.
1122 refit_trials += 1;
1123 retry_ms = retry_started.map_or(0.0, |started| started.elapsed().as_secs_f64() * 1e3);
1124 refit_seeds = 0;
1125 refit_seeds_kept = 0;
1126 refit_seeds_outside_pool = 0;
1127 refit_seed_min_chord = f64::NAN;
1128 refit_seed_min_pair = "n/a";
1129 refit_rejected = [0; 4];
1130 representative_fit = false;
1131 // Keep the candidate's own counts; the retry is the full refit.
1132 refit_cost.full_refit = true;
1133 previous = Some((earlier, earlier_worst, earlier_missing));
1134 continue;
1135 }
1136 receipt.returned = Some(previous_source);
1137 return Ok((earlier, earlier_worst, unrefined, rounds, MidspanExit::NoProgress));
1138 }
1139 }
1140 if inserts.is_empty() {
1141 if let Some(((kept_fit, kept_run), kept_common)) = take_rollback(&mut best_state, current_common, representative_ran) {
1142 *section = kept_run;
1143 receipt.returned = Some(RefinedFitSource::Rollback);
1144 return Ok((kept_fit, kept_common, unrefined, rounds, MidspanExit::Stalled));
1145 }
1146 receipt.returned = Some(fit_source);
1147 return Ok((fit, worst, unrefined, rounds, MidspanExit::Stalled));
1148 }
1149 if rounds >= SECTION_MIDSPAN_ROUNDS {
1150 if let Some(((kept_fit, kept_run), kept_common)) = take_rollback(&mut best_state, current_common, representative_ran) {
1151 *section = kept_run;
1152 receipt.returned = Some(RefinedFitSource::Rollback);
1153 return Ok((kept_fit, kept_common, unrefined, rounds, MidspanExit::RoundBudget));
1154 }
1155 receipt.returned = Some(fit_source);
1156 return Ok((fit, worst, unrefined, rounds, MidspanExit::RoundBudget));
1157 }
1158 if section.len() + inserts.len() > MAX_FIT_STATIONS {
1159 if let Some(((kept_fit, kept_run), kept_common)) = take_rollback(&mut best_state, current_common, representative_ran) {
1160 *section = kept_run;
1161 receipt.returned = Some(RefinedFitSource::Rollback);
1162 return Ok((kept_fit, kept_common, unrefined, rounds, MidspanExit::StationCeiling));
1163 }
1164 receipt.returned = Some(fit_source);
1165 return Ok((fit, worst, unrefined, rounds, MidspanExit::StationCeiling));
1166 }
1167 // Insert each refined point into the run between its span's stations,
1168 // on the nearest segment of the run there. Positions are located
1169 // against the run BEFORE any insertion of this round, then applied
1170 // from the back so earlier indices stay valid. The kept stations are
1171 // found by a FORWARD search from the previous one: a closed section
1172 // ends on its first station, and a search from the start would put
1173 // the last span's far end at index 0 and skip that span forever.
1174 let station_index = |point: Vec3, from: usize| -> Option<usize> {
1175 section[from..]
1176 .iter()
1177 .position(|p| p.sub(point).length() <= 1e-15 * (1.0 + point.length()))
1178 .map(|offset| from + offset)
1179 };
1180 let mut placed: Vec<(usize, Vec3)> = Vec::new();
1181 for (span, point) in inserts {
1182 let Some(lo) = station_index(fit.kept[span], 0) else {
1183 continue;
1184 };
1185 let Some(hi) = station_index(fit.kept[span + 1], lo + 1) else {
1186 continue;
1187 };
1188 if hi <= lo {
1189 continue;
1190 }
1191 if section[lo..=hi].iter().any(|p| p.sub(point).length() <= floor) {
1192 continue; // already a station: inserting it again refines nothing
1193 }
1194 let mut best = (lo, f64::INFINITY);
1195 for index in lo..hi {
1196 let d2 = distance_to_segment_sq(point, section[index], section[index + 1]);
1197 if d2 < best.1 {
1198 best = (index, d2);
1199 }
1200 }
1201 placed.push((best.0 + 1, point));
1202 }
1203 if placed.is_empty() {
1204 if let Some(((kept_fit, kept_run), kept_common)) = take_rollback(&mut best_state, current_common, representative_ran) {
1205 *section = kept_run;
1206 receipt.returned = Some(RefinedFitSource::Rollback);
1207 return Ok((kept_fit, kept_common, unrefined, rounds, MidspanExit::Stalled));
1208 }
1209 receipt.returned = Some(fit_source);
1210 return Ok((fit, worst, unrefined, rounds, MidspanExit::Stalled));
1211 }
1212 placed.sort_by(|a, b| b.0.cmp(&a.0));
1213 for (at, point) in placed {
1214 section.insert(at, point);
1215 inserted_points.push(point);
1216 }
1217 // The refit keeps the stations the current fit kept and every point
1218 // inserted so far as SEEDS, and grows only where it is measured to
1219 // miss (`fit_polyline_seeded_with_path`). It is no longer the whole denser run
1220 // from the run's own count: that interpolated every march station the
1221 // standing fit had dropped as well, 3x the controls on the skew-cylinder
1222 // loop for the same carrier floor. The ceiling is the one the full refit
1223 // derives from the same `maximum_points`, and a seeded fit that cannot
1224 // meet the floor, or cannot be read, IS the full refit. The carrier
1225 // measure above still decides every round.
1226 let same = |a: &Vec3, b: &Vec3| a.x.to_bits() == b.x.to_bits() && a.y.to_bits() == b.y.to_bits() && a.z.to_bits() == b.z.to_bits();
1227 let mut seeds = Vec::with_capacity(fit.kept.len() + inserted_points.len());
1228 // The previous fit's kept stations alone: the representative candidate's
1229 // starting set (inserts are its witnesses, not forced stations).
1230 let mut kept_seeds = Vec::with_capacity(fit.kept.len());
1231 // The refiner's own inserted true-carrier points: the representative
1232 // candidate's TIGHT witnesses, held to this refiner's carrier floor.
1233 let mut insert_indices = Vec::with_capacity(inserted_points.len());
1234 let mut next_kept = 0usize;
1235 for (index, point) in section.iter().enumerate() {
1236 // The kept stations are a subsequence of the run, in run order
1237 // (insertion only adds points), so a closed run's two equal ends
1238 // each match their own station.
1239 // An inserted point is a tight witness whether or not the previous
1240 // fit also kept it as a station (membership is independent).
1241 let inserted = inserted_points.iter().any(|candidate| same(point, candidate));
1242 if inserted {
1243 insert_indices.push(index);
1244 }
1245 if next_kept < fit.kept.len() && same(point, &fit.kept[next_kept]) {
1246 seeds.push(index);
1247 kept_seeds.push(index);
1248 next_kept += 1;
1249 } else if inserted {
1250 seeds.push(index);
1251 }
1252 }
1253 let maximum_points = section.len().min(MAX_FIT_STATIONS);
1254 // Every standing station must be found as a seed; if the pass missed
1255 // one, the seeded refit would silently lose it, so the section takes the
1256 // original full refit instead.
1257 refit_trials = 1;
1258 retry_ms = 0.0;
1259 let refit_source;
1260 let refit = if next_kept == fit.kept.len() {
1261 let (refit, path) = if original_consistent {
1262 let (refit, path, cost) = fit_split_timed(FitSplitLane::Representatives, || crate::fit::fit_polyline_representatives_with_witnesses(
1263 section,
1264 &kept_seeds,
1265 &insert_indices,
1266 floor,
1267 fit_tolerance,
1268 maximum_points,
1269 local_fit,
1270 section_fit_degree(),
1271 ))?;
1272 // MIXED UNITS, named as such: the candidate's own
1273 // `fit_station_set` interpolations plus one per call of the
1274 // full refit `fit_polyline_of_degree`, which may itself run
1275 // several ladder and recovery interpolations that are NOT
1276 // counted here. Whole-job cost is the matched timing.
1277 refit_cost = cost;
1278 refit_trials = cost.candidate_fits + usize::from(cost.full_refit);
1279 (refit, path)
1280 } else {
1281 refit_cost = crate::fit::RepresentativeCost::default();
1282 fit_split_timed(FitSplitLane::Seeded, || crate::fit::fit_polyline_seeded_with_path(
1283 section,
1284 &seeds,
1285 fit_tolerance,
1286 maximum_points,
1287 local_fit,
1288 section_fit_degree(),
1289 ))?
1290 };
1291 // Only an ACCEPTED seeded fit can be retried in full: a fallback
1292 // already is the full refit, and retrying it would repeat it.
1293 seeded_refit = matches!(path, crate::fit::SeededPath::Accepted { .. });
1294 representative_fit = original_consistent && seeded_refit;
1295 refit_source = if original_consistent { RefinedFitSource::Representatives(path) } else { RefinedFitSource::Seeded(path) };
1296 representative_ran |= representative_fit;
1297 if round_census.is_some() {
1298 refit_path = if original_consistent { format!("representatives-call:{path:?}") } else { format!("seeded-call:{path:?}") };
1299 }
1300 refit
1301 } else {
1302 seeded_refit = false;
1303 representative_fit = false;
1304 refit_cost = crate::fit::RepresentativeCost::default();
1305 refit_path = String::from("full-unmatched");
1306 refit_source = RefinedFitSource::FullRefit;
1307 fit_split_timed(FitSplitLane::FullRefit, || fit_polyline_of_degree(section, fit_tolerance, maximum_points, local_fit, section_fit_degree()))?
1308 };
1309 if round_census.is_some() {
1310 // Trace only: how many seeds the refit kept. This does NOT tell an
1311 // accepted seeded fit from the fallback (a full refit can keep
1312 // every seed too); the returned `SeededPath`, traced as `fit`, does.
1313 refit_seeds = seeds.len();
1314 refit_seeds_kept = seeds.iter().filter(|&&index| refit.kept.iter().any(|kept| same(kept, §ion[index]))).count();
1315 // Seeds the full refit's pool would NOT interpolate (simplified
1316 // or conditioned away): forced stations only the seeded fit keeps.
1317 let pool = crate::fit::polyline_station_pool(section, fit_tolerance);
1318 refit_pool = pool.len();
1319 refit_pool_discarded = section.len() - pool.len();
1320 refit_pool_floor = crate::fit::polyline_station_pool_floor(section, fit_tolerance);
1321 refit_seeds_outside_pool = seeds.iter().filter(|index| !pool.contains(index)).count();
1322 // Seeds are in run order; the closest consecutive pair is what a
1323 // near-duplicate conditioning floor would act on.
1324 refit_seed_min_chord = seeds
1325 .windows(2)
1326 .map(|pair| section[pair[1]].sub(section[pair[0]]).length())
1327 .fold(f64::INFINITY, f64::min);
1328 let is_insert = |index: usize| inserted_points.iter().any(|inserted| same(inserted, §ion[index]));
1329 refit_seed_min_pair = seeds
1330 .windows(2)
1331 .min_by(|a, b| {
1332 section[a[1]].sub(section[a[0]]).length().total_cmp(§ion[b[1]].sub(section[b[0]]).length())
1333 })
1334 .map_or("n/a", |pair| match (is_insert(pair[0]), is_insert(pair[1])) {
1335 (false, false) => "station-station",
1336 (false, true) => "station-insert",
1337 (true, false) => "insert-station",
1338 (true, true) => "insert-insert",
1339 });
1340 // Every rejected seed, classified. `station_pool` starts from this
1341 // same simplification, so a non-member that is not in it was
1342 // simplified away, and one that is in it was conditioned away.
1343 let simplified = crate::fit::simplify_polyline_indices(section, fit_tolerance);
1344 refit_rejected = [0; 4];
1345 for &index in seeds.iter().filter(|index| !pool.contains(index)) {
1346 let conditioned = simplified.binary_search(&index).is_ok();
1347 refit_rejected[2 * usize::from(is_insert(index)) + usize::from(conditioned)] += 1;
1348 }
1349 }
1350 previous = Some((std::mem::replace(&mut fit, refit), worst, missing));
1351 previous_source = std::mem::replace(&mut fit_source, refit_source);
1352 rounds += 1;
1353 }
1354}
1355use super::*;
1356use super::gate_census::{census_pair, fit_census_enabled};
1357
1358pub fn build_imprints(
1359 solid_a: &BrepSolid,
1360 solid_b: &BrepSolid,
1361 options: &ImprintOptions,
1362) -> Result<ImprintResultRecord, KernelRefusal> {
1363 build_imprints_impl(solid_a, solid_b, options, false, super::pcurve_cache::enabled())
1364}
1365
1366/// Imprint temporary open offset sheets. A section riding one sheet's trim
1367/// still cuts the other sheet when no boundary copy supplied that section.
1368pub fn build_carrier_imprints(
1369 solid_a: &BrepSolid,
1370 solid_b: &BrepSolid,
1371 options: &ImprintOptions,
1372 tree_seeds: bool,
1373) -> Result<ImprintResultRecord, KernelRefusal> {
1374 build_imprints_with_carrier_seeds(
1375 solid_a, solid_b, options, true, super::pcurve_cache::enabled(), tree_seeds, None,
1376 )
1377}
1378
1379/// Lane P3b row 6 (2026-10-26): imprint the faces of ONE open sheet solid
1380/// against each other in a single call. `solid` is both operands (operand 0
1381/// and 1 tag the same faces); a face pair is processed once, as
1382/// (first index, second index) in the solid's face order with first < second,
1383/// and only when `admit(first, second)` says so. Every post-pass then runs
1384/// once over the whole piece set instead of once per pair.
1385pub fn build_carrier_imprints_within(
1386 solid: &BrepSolid,
1387 admit: &dyn Fn(usize, usize) -> bool,
1388 options: &ImprintOptions,
1389 tree_seeds: bool,
1390) -> Result<ImprintResultRecord, KernelRefusal> {
1391 build_imprints_with_carrier_seeds(
1392 solid, solid, options, true, super::pcurve_cache::enabled(), tree_seeds, Some(admit),
1393 )
1394}
1395
1396/// `BREP_IMPRINT_PLANE_POINT_SKIP` (lane X row 5): skip the march for two
1397/// exact parallelogram faces whose contact is one point
1398/// ([`super::support::planar_point_contact`]) once their seeds are accepted.
1399/// On by default; `0`/`off` disables it.
1400pub(super) fn plane_point_skip_enabled() -> bool {
1401 switch!(live "BREP_IMPRINT_PLANE_POINT_SKIP", true)
1402}
1403
1404thread_local! {
1405 static PLANE_POINT_SKIPS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
1406}
1407
1408
1409
1410pub(super) fn build_imprints_impl(
1411 solid_a: &BrepSolid,
1412 solid_b: &BrepSolid,
1413 options: &ImprintOptions,
1414 open_carriers: bool,
1415 pcurve_cache: bool,
1416) -> Result<ImprintResultRecord, KernelRefusal> {
1417 build_imprints_with_carrier_seeds(solid_a, solid_b, options, open_carriers, pcurve_cache, false, None)
1418}
1419
1420// A carved offset can have a narrow transverse section beside its fold.
1421// Seed its knot spans without enabling ordered/consumed starts on other paths.
1422fn build_imprints_with_carrier_seeds(
1423 solid_a: &BrepSolid,
1424 solid_b: &BrepSolid,
1425 options: &ImprintOptions,
1426 open_carriers: bool,
1427 pcurve_cache: bool,
1428 carrier_tree_seeds: bool,
1429 // `Some`: `solid_a` IS `solid_b` and only face pairs (first < second) the
1430 // predicate admits are processed ([`build_carrier_imprints_within`]).
1431 self_pairs: Option<&dyn Fn(usize, usize) -> bool>,
1432) -> Result<ImprintResultRecord, KernelRefusal> {
1433 let _wall = crate::wall_profile::Stage::open("imprint");
1434 let _profile_sink = ProfileSink::open();
1435 let _work = super::work_profile::Scope::open("imprint");
1436 let classify_before = crate::pair_classification::classify_reads();
1437 let setup_started = profile_enabled().then(Instant::now);
1438 let windows_before = window_reads();
1439 let _pcurve_cache = super::pcurve_cache::FitCacheScope::open(pcurve_cache);
1440 let _edge_hulls = super::support::EdgeHullScope::open(super::support::edge_hull_memo_enabled());
1441 let _intersection_cache = super::intersection_cache::Scope::open();
1442 let reuse_whole_miss = open_carriers &&
1443 std::env::var("BREP_OFFSET_IMPRINT_READINGS").map_or(true, |v| v != "0" && v != "off");
1444 let mut section_evidence = false;
1445 let edges = edge_map(solid_a, solid_b);
1446 // FEATURE SCALE (`BREP_FEATURE_SCALE_IMPRINT`, default on, `=0` off):
1447 // the slivers between almost parallel plane faces of the two operands,
1448 // measured before any section is processed so that every band the
1449 // imprint applies sees them. A sliver a quarter of which is under the
1450 // tolerance cannot be resolved by any band, so the boolean refuses
1451 // rather than merge it away.
1452 let feature_scale = if crate::feature_scale::imprint_enabled() {
1453 let scale = crate::feature_scale::FeatureScale::between(solid_a, solid_b, options.tolerance)
1454 .or_refuse(KernelStage::Intersect, "feature_scale")?;
1455 if let Some(thinnest) = scale.thinnest() {
1456 if crate::feature_scale::FRACTION * thinnest < options.tolerance {
1457 return Err(KernelRefusal::new(
1458 RefusalClass::IllPosed { what: "feature size".into() },
1459 KernelStage::Intersect,
1460 format!(
1461 "boolean: a sliver {thinnest:.3e} thick between almost parallel faces is smaller than the \
1462 section's resolution (tolerance {:.1e})",
1463 options.tolerance
1464 ),
1465 ));
1466 }
1467 }
1468 scale
1469 } else {
1470 Default::default()
1471 };
1472 // The tail passes (coincident-piece merge, junction canonicalisation)
1473 // run after the builder is consumed; they read the same scale.
1474 let tail_feature_scale = feature_scale.clone();
1475 let mut builder = ImprintBuilder {
1476 feature_scale,
1477 open_carriers,
1478 edges,
1479 tolerance: options.tolerance,
1480 barrier_edges: HashSet::default(),
1481 overlap_ridden_edges: HashSet::default(),
1482 scale: solid_scale(solid_a).max(solid_scale(solid_b)),
1483 vertices: Vec::new(),
1484 vertex_radii: HashMap::default(),
1485 vertex_sources: HashMap::default(),
1486 pieces: Vec::new(),
1487 by_face: HashMap::default(),
1488 edge_splits: HashMap::default(),
1489 marched_pieces: HashSet::default(),
1490 exact_section: false,
1491 emitted_pcurves: HashSet::default(),
1492 exact_pcurve_check: false,
1493 next_id: 1,
1494 };
1495 let requested_hermite_lane = hermite_sections(options);
1496 let hermite_lane = requested_hermite_lane || super::hermite::carried_uv_enabled();
1497 let hermite_min_stations = if hermite_lane { super::hermite::carried_uv_min_stations() } else { 2 };
1498 let exact_iso = exact_iso_pcurves(options);
1499 let (ordered_starts, consume_starts, tree_seeds) = march_starts(options, carrier_tree_seeds);
1500 builder.exact_pcurve_check = exact_iso == ExactIsoPcurves::Check;
1501 // The Hermite lane needs the march's span test; with no budget asked for
1502 // it carries the one the catalogue names, the pair's `intersection_fit`.
1503 let march_span_budget = span_budget(options, builder.scale)
1504 .or_else(|| requested_hermite_lane.then(|| crate::KernelTolerances::for_scale(builder.scale, options.tolerance).intersection_fit));
1505 // UV reuse must never request a different trace. Its stricter emission
1506 // check is applied after clipping; an unqualified run keeps the fit route.
1507 let emission_budget = super::hermite::carried_uv_emission_budget(march_span_budget,
1508 crate::KernelTolerances::for_scale(builder.scale, options.tolerance).intersection_fit);
1509 let mut first_faces = faces(solid_a, 0);
1510 let mut second_faces = faces(solid_b, 1);
1511 // Per-face trim-window carriers, computed once: tighter BVH bounds, and
1512 // the seed/march stages walk the window instead of the full carrier
1513 // (identical geometry and parameterization inside the window).
1514 //
1515 // A window LIFTED across a closed direction's seam (`restricted_carrier`)
1516 // is the exception to "same parameterization": it is the trim's frame, a
1517 // period off the carrier's on one side. Its face carries it as its
1518 // `chart`, and every uv the imprint reads for that face — the clip's
1519 // containment, the sections' pcurves, a seed's normal — is read there.
1520 let first_restricted: Vec<Option<MarchWindow>> = first_faces
1521 .iter()
1522 .map(|tagged| restricted_carrier_memoized(tagged.face))
1523 .collect();
1524 let second_restricted: Vec<Option<MarchWindow>> = second_faces
1525 .iter()
1526 .map(|tagged| restricted_carrier_memoized(tagged.face))
1527 .collect();
1528 for (tagged, window) in first_faces.iter_mut().zip(&first_restricted) {
1529 tagged.lifted = window.as_ref().filter(|window| window.lifted).map(|window| &window.surface);
1530 }
1531 for (tagged, window) in second_faces.iter_mut().zip(&second_restricted) {
1532 tagged.lifted = window.as_ref().filter(|window| window.lifted).map(|window| &window.surface);
1533 }
1534 let first_faces = first_faces;
1535 let second_faces = second_faces;
1536 // The lifted charts, by key, for the post-passes that rebuild a pcurve
1537 // after the mint (junction canonicalization, the origin dissolve, the
1538 // truncation bridge). A face absent here is read on its own carrier.
1539 let charts: FaceCharts<'_> = first_faces
1540 .iter()
1541 .chain(second_faces.iter())
1542 .filter_map(|tagged| tagged.lifted.map(|surface| (tagged.key(), surface)))
1543 .collect();
1544 let first_bounds = first_faces
1545 .iter()
1546 .zip(&first_restricted)
1547 .map(|(tagged, restricted)| {
1548 face_bounds(
1549 tagged.face,
1550 restricted.as_ref().map(|window| &window.surface),
1551 &builder.edges,
1552 tagged.operand,
1553 options.tolerance,
1554 )
1555 })
1556 .collect::<Result<Vec<_>, _>>()?;
1557 let second_bounds = second_faces
1558 .iter()
1559 .zip(&second_restricted)
1560 .map(|(tagged, restricted)| {
1561 face_bounds(
1562 tagged.face,
1563 restricted.as_ref().map(|window| &window.surface),
1564 &builder.edges,
1565 tagged.operand,
1566 options.tolerance,
1567 )
1568 })
1569 .collect::<Result<Vec<_>, _>>()?;
1570 let second_bvh = Bvh::build(&second_bounds);
1571 // Per-face classifier data and edge lists/subcurves, computed once and
1572 // reused across every pair the face participates in.
1573 let first_classify = first_faces
1574 .iter()
1575 .map(|tagged| SurfaceClassifyData::memoized(&tagged.face.surface, options.tolerance))
1576 .collect::<Result<Vec<_>, _>>().or_refuse(KernelStage::Intersect, "csg.imprint.driver")?;
1577 let second_classify = second_faces
1578 .iter()
1579 .map(|tagged| SurfaceClassifyData::memoized(&tagged.face.surface, options.tolerance))
1580 .collect::<Result<Vec<_>, _>>().or_refuse(KernelStage::Intersect, "csg.imprint.driver")?;
1581 // Per-face span hulls for the separation prefilter, built on first use.
1582 let first_hulls: Vec<std::cell::OnceCell<Option<crate::SpanHullSet>>> =
1583 (0..first_faces.len()).map(|_| std::cell::OnceCell::new()).collect();
1584 let second_hulls: Vec<std::cell::OnceCell<Option<crate::SpanHullSet>>> =
1585 (0..second_faces.len()).map(|_| std::cell::OnceCell::new()).collect();
1586 let mut face_edge_lists: HashMap<FaceKey, Vec<&EdgeRecord>> = HashMap::default();
1587 for tagged in first_faces.iter().chain(second_faces.iter()) {
1588 face_edge_lists.insert(tagged.key(), face_edges(*tagged, &builder.edges)?);
1589 }
1590 let mut subcurves: HashMap<(u8, u64), NurbsCurve> = HashMap::default();
1591 for (&key, edge) in &builder.edges {
1592 if !edge.degenerate {
1593 // Failures fall through: the use sites recompute and surface the
1594 // original error exactly where the uncached code did.
1595 if let Ok(curve) = edge_subcurve(edge) {
1596 subcurves.insert(key, curve);
1597 }
1598 }
1599 }
1600 let cached_subcurve = |operand: u8, edge: &EdgeRecord| -> Result<NurbsCurve, KernelRefusal> {
1601 match subcurves.get(&(operand, edge.id)) {
1602 Some(curve) => Ok(curve.clone()),
1603 None => edge_subcurve(edge),
1604 }
1605 };
1606 if let Some(started) = setup_started { profile_line!("imprint.setup ms={:.3} faces={} classify_reads={} windows_built={}", started.elapsed().as_secs_f64()*1000.0, first_faces.len()+second_faces.len(), crate::pair_classification::classify_reads()-classify_before, window_reads()-windows_before); }
1607 let mut profile = ImprintProfile::new();
1608 let mut march_swap_rescues = 0_u64;
1609 let mut clip_swap_rescues = 0_u64;
1610 // `imprint.fits`: the pcurve fits the pairs record, read through a nested
1611 // scope that folds into the operation's own ledger on close.
1612 let pairs_fits = profile.enabled.then(crate::PcurveFitScope::open);
1613 let mut tangent_nodes: Vec<Vec3> = Vec::new();
1614 let mut tangent_sections: Vec<TangentSectionRecord> = Vec::new();
1615 // Planar tangent runs to IMPRINT once every pair has minted its pieces
1616 // (`ImprintOptions::tangent_curve_imprint`): (section index, run, pair).
1617 let mut tangent_imprint_candidates: Vec<(usize, Vec<Vec3>, TaggedFace<'_>, TaggedFace<'_>)> = Vec::new();
1618 let mut cosurface_pairs: Vec<(FaceKey, FaceKey)> = Vec::new();
1619 let mut deferred_boundary_spans = Vec::new();
1620 let mut work_pairs = super::work_profile::Pairs::new(first_faces.len() * second_faces.len());
1621 let mut paired = Vec::new();
1622 // Every cross-operand pair whose face boxes met, and those of them the
1623 // imprint PROVED apart (`ImprintResultRecord::faces_in_unproved_pairs`).
1624 let mut visited_pairs: Vec<(usize, usize)> = Vec::new();
1625 let mut proved_apart_pairs: HashSet<(usize, usize)> = HashSet::default();
1626 for (first_index, first) in first_faces.iter().enumerate() {
1627 let first = *first;
1628 paired.clear();
1629 second_bvh.overlapping(
1630 first_bounds[first_index],
1631 options.tolerance * 100.0,
1632 &mut paired,
1633 );
1634 paired.sort_unstable();
1635 let debug_pairs = std::env::var("BREP_DEBUG_PAIRS").is_ok();
1636 if debug_pairs {
1637 eprintln!(
1638 "bvh first_face={} -> {} candidate pairs {:?}",
1639 first.face.id,
1640 paired.len(),
1641 paired
1642 .iter()
1643 .map(|&index| second_faces[index].face.id)
1644 .collect::<Vec<_>>()
1645 );
1646 }
1647 for &second_index in &paired {
1648 if let Some(admit) = self_pairs {
1649 if second_index <= first_index || !admit(first_index, second_index) {
1650 continue;
1651 }
1652 }
1653 let second = second_faces[second_index];
1654 visited_pairs.push((first_index, second_index));
1655 profile.pairs += 1;
1656 let _work_pair = super::work_profile::Pair::open(&mut work_pairs, first.face, second.face);
1657 // Set when this pair's section passes through an isolated TANGENT
1658 // NODE inside both trims (see the classification below). The march
1659 // is attempted anyway — that is the whole point — but a marcher
1660 // that cannot get through a node must refuse in the tangent-node
1661 // class naming the node, not leak its own step-budget message.
1662 let mut tangent_node: Option<Vec3> = None;
1663 // The pair's branches came from the sub-gate re-march below: a
1664 // run end that stalls in the tangency band then lands on a trim
1665 // edge the carriers share exactly as a tangent-node pair's does.
1666 let mut grazing_march = false;
1667 let mut lap_start = None;
1668 profile.lap(&mut lap_start);
1669 let pair_classification = classify_surface_pair_cached(
1670 &first.face.surface,
1671 &first_classify[first_index],
1672 &second.face.surface,
1673 &second_classify[second_index],
1674 options.tolerance,
1675 PAIR_ANGULAR_TOLERANCE,
1676 ).or_refuse(KernelStage::Intersect, "csg.imprint.driver")?;
1677 profile.classify += profile.lap(&mut lap_start);
1678 // A proof recorded, not acted on (the pair is imprinted as
1679 // before): two exact concentric analytic carriers whose surfaces
1680 // cannot meet (the walls of a closed hollow of a revolved solid).
1681 if concentric_carriers_apart(&first.face.surface, &second.face.surface, options.tolerance * 10.0) {
1682 proved_apart_pairs.insert((first_index, second_index));
1683 }
1684 if pair_classification.relation == SurfacePairRelation::Disjoint {
1685 // A proof: the control hulls' boxes, or two parallel planes,
1686 // apart by more than the contact band.
1687 proved_apart_pairs.insert((first_index, second_index));
1688 if debug_pairs {
1689 eprintln!(
1690 "pair {}x{}: DISJOINT-cull sep={:.4e}",
1691 first.face.id, second.face.id, pair_classification.minimum_separation
1692 );
1693 }
1694 continue;
1695 }
1696 // Coincident carriers are never marched: their true intersection
1697 // is a 2D region, not a curve, so anything the marcher traces on
1698 // them is noise ("similar faces we do not intersect" — Golovanov
1699 // §6.2). The sampled classification catches coincident pairs
1700 // the strict reconstruction test misses (partial overlaps,
1701 // differing parameterizations); both route to the boundary-curve
1702 // exchange below.
1703 let is_cosurface = pair_classification.relation == SurfacePairRelation::Cosurface
1704 || cosurface_pair(&first.face.surface, &second.face.surface, options.tolerance)?;
1705 profile.cosurface += profile.lap(&mut lap_start);
1706 if is_cosurface {
1707 if debug_pairs {
1708 eprintln!("pair {}x{}: cosurface", first.face.id, second.face.id);
1709 }
1710 cosurface_pairs.push((first.key(), second.key()));
1711 for edge in &face_edge_lists[&second.key()] {
1712 if !edge.degenerate {
1713 builder.process_curve(
1714 cached_subcurve(second.operand, edge)?,
1715 first,
1716 second,
1717 &[first],
1718 &[first],
1719 false,
1720 None,
1721 )?;
1722 }
1723 }
1724 for edge in &face_edge_lists[&first.key()] {
1725 if !edge.degenerate {
1726 builder.process_curve(
1727 cached_subcurve(first.operand, edge)?,
1728 first,
1729 second,
1730 &[second],
1731 &[second],
1732 false,
1733 None,
1734 )?;
1735 }
1736 }
1737 profile.process_curve += profile.lap(&mut lap_start);
1738 continue;
1739 }
1740
1741 // Exact lanes discard sections riding an ordinary trim boundary:
1742 // that face already owns the edge, but the other face still needs
1743 // the overlapping span as a cut. Keep the existing whole-edge
1744 // exchange order, and append missing partial spans after all pairs
1745 // have run so duplicate sections retain their established IDs and
1746 // fragment names. Seams are retained by the exact lane itself.
1747 let planar_iso = planar_iso_section(
1748 &first.face.surface,
1749 &second.face.surface,
1750 options.tolerance,
1751 )?;
1752 profile.planar_iso += profile.lap(&mut lap_start);
1753 let analytic = crate::intersect_analytic_pair(
1754 &first.face.surface,
1755 &second.face.surface,
1756 options.tolerance,
1757 );
1758 profile.analytic += profile.lap(&mut lap_start);
1759 let exact_section = planar_iso.is_some() || analytic.is_some();
1760
1761 for (source, target) in [(first, second), (second, first)] {
1762 for edge in &face_edge_lists[&source.key()] {
1763 if edge.degenerate {
1764 continue;
1765 }
1766 let curve = cached_subcurve(source.operand, edge)?;
1767 let spans = curve_spans_on_face(
1768 curve.clone(), target.face, &face_edge_lists[&target.key()],
1769 options.tolerance, exact_section,
1770 )?;
1771 let seam = source.face.loops.iter().flat_map(|loop_record| &loop_record.coedges)
1772 .filter(|coedge| coedge.edge_id == edge.id).count() >= 2;
1773 if spans.is_empty() && exact_section && !seam {
1774 // The whole-only call above returned empty: its exact
1775 // curve/carrier reading was false. Nothing has mutated.
1776 let partial = if reuse_whole_miss {
1777 profile.whole_reading_reuses += 1;
1778 curve_spans_after_whole_miss(
1779 curve, target.face, &face_edge_lists[&target.key()], options.tolerance,
1780 )?
1781 } else {
1782 curve_spans_on_face(
1783 curve, target.face, &face_edge_lists[&target.key()], options.tolerance, false,
1784 )?
1785 };
1786 for span in partial {
1787 deferred_boundary_spans.push((span, first, second, target));
1788 }
1789 }
1790 for span in spans {
1791 builder.process_curve(span, first, second, &[target], &[target], false, None)?;
1792 }
1793 }
1794 }
1795 profile.lies_on += profile.lap(&mut lap_start);
1796 // CENSUS ONLY (`BREP_FIT_CENSUS=1`): the lane this pair takes under
1797 // the count-keyed and the geometry-keyed gates, and — when it is
1798 // marched here and answered exactly there — the point-set comparison
1799 // of the two, printed when `pair_census` is dropped. `imprint/gate_census.rs`.
1800 let mut pair_census = if fit_census_enabled() {
1801 census_pair(first, second, options.tolerance)?
1802 } else {
1803 None
1804 };
1805 if let Some(IsoSection { curve, pcurves, own_lane }) = planar_iso {
1806 if debug_pairs {
1807 eprintln!("pair {}x{}: planar_iso", first.face.id, second.face.id);
1808 }
1809 // Slice 1: the exact pcurves ride along with the curve when
1810 // the lane is on (or checked). A face read in a lifted chart
1811 // declines: the iso line is in the carrier's own frame, and
1812 // the lifted chart's period is not the carrier's.
1813 let exact_iso = if own_lane { ExactIsoPcurves::On } else { exact_iso };
1814 let exact_pcurves = match (exact_iso, pcurves) {
1815 (ExactIsoPcurves::Off, _) => None,
1816 (_, Some(pcurves)) if first.lifted.is_none() && second.lifted.is_none() => {
1817 profile.exact_iso_sections += 1;
1818 Some(pcurves)
1819 }
1820 _ => {
1821 profile.exact_iso_declined += 1;
1822 None
1823 }
1824 };
1825 let lane_fits = profile.enabled.then(crate::PcurveFitScope::open);
1826 builder.process_curve(
1827 curve,
1828 first,
1829 second,
1830 &[first, second],
1831 &[first, second],
1832 true,
1833 exact_pcurves,
1834 )?;
1835 if let Some(scope) = lane_fits {
1836 profile.exact_lane_fits += scope.close().fits;
1837 }
1838 profile.process_curve += profile.lap(&mut lap_start);
1839 continue;
1840 }
1841
1842 // Recognized analytic pairs produce their exact intersection
1843 // curves (lines, circles, ellipses) directly — no marching, no
1844 // polyline fitting, no chord-sag drift. An empty result is a
1845 // proof of non-intersection and also skips the marcher. (Read
1846 // above, with the planar-iso curve.)
1847 if let Some(curves) = analytic {
1848 if debug_pairs {
1849 eprintln!(
1850 "pair {}x{}: analytic x{}",
1851 first.face.id,
1852 second.face.id,
1853 curves.len()
1854 );
1855 }
1856 // TANGENT-CURVE LANE. An exact lane's "provably empty" is a
1857 // proof about TRANSVERSE curves: a plane at exactly the
1858 // cylinder's radius from its axis has no generatrix pair, and
1859 // the pair would be dropped here without a word while the
1860 // carriers touch along a whole line. Where the classification
1861 // read the pair as near-tangent, the lane looks for the
1862 // extended contact and records it typed.
1863 if curves.is_empty()
1864 && options.tangent_curve_lane
1865 && pair_classification.relation == SurfacePairRelation::NearTangent
1866 {
1867 if let Some((section, run)) = tangent_curve_section(
1868 first, second, options, &first_faces, &second_faces, &face_edge_lists, debug_pairs,
1869 )? {
1870 if options.tangent_curve_imprint && section.planar && run.len() >= 2 {
1871 tangent_imprint_candidates.push((tangent_sections.len(), run, first, second));
1872 }
1873 tangent_sections.push(section);
1874 }
1875 }
1876 let lane_fits = profile.enabled.then(crate::PcurveFitScope::open);
1877 builder.exact_section = true;
1878 for curve in curves {
1879 let processed = builder.process_curve(
1880 curve,
1881 first,
1882 second,
1883 &[first, second],
1884 &[first, second],
1885 true,
1886 None,
1887 );
1888 if processed.is_err() {
1889 builder.exact_section = false;
1890 }
1891 processed?;
1892 }
1893 builder.exact_section = false;
1894 if let Some(scope) = lane_fits {
1895 profile.exact_lane_fits += scope.close().fits;
1896 }
1897 profile.process_curve += profile.lap(&mut lap_start);
1898 continue;
1899 }
1900
1901 // A pair whose every touching sample is TANGENTIAL cannot
1902 // contain a transverse intersection curve: the marcher would
1903 // walk the tangency band's noise, which neither closes nor
1904 // reaches a boundary (the distance-0 glue-extrude runaway).
1905 // Shared topology at a tangential contact comes from the
1906 // boundary-curve exchange above ("similar faces we do not
1907 // intersect" extended to tangential contacts — Golovanov §6.2;
1908 // where surfaces CROSS through a tangency, off-line samples
1909 // have non-parallel normals and the pair still marches).
1910 if pair_classification.relation == SurfacePairRelation::NearTangent
1911 && pair_classification.tangential_only
1912 {
1913 // The coarse 5×5 classifier can flag `tangential_only` off an
1914 // incidental tangential KISS between two curved carriers and
1915 // miss the transverse loop where they actually cross (two
1916 // overlapping tori: their tubes cross while their inner walls
1917 // just touch). Before honouring the skip, a GATED supplemental
1918 // detector (denser two-sided seeding, tangency-band seeds
1919 // rejected, trace-exhaustion swallowed, transverse-only
1920 // branches) checks whether a genuine transverse curve of
1921 // meaningful length lies inside BOTH trims.
1922 //
1923 // Such a pair's intersection is SINGULAR where a tangency
1924 // sits on it, and what the imprint can do about that depends
1925 // entirely on the SHAPE of the tangency — see
1926 // `imprint/tangent_contact.rs`. An isolated NODE (two branches
1927 // crossing, as every equal-radius pair produces) is already
1928 // assembled correctly by the ordinary march plus the 2D
1929 // arrangement's pinch carving; an EXTENDED contact along a
1930 // whole curve has no section to imprint at all and tears the
1931 // shell. Both are classified below and only the second is
1932 // refused. Skipping either silently would DROP the
1933 // intersection (torus∪torus double-counts; torus−torus removes
1934 // nothing — the two structural bugs the semantic oracle
1935 // found), so nothing here ever falls through quietly.
1936 let first_march = first_restricted[first_index]
1937 .as_ref()
1938 .map(|window| &window.surface)
1939 .unwrap_or(&first.face.surface);
1940 let second_march = second_restricted[second_index]
1941 .as_ref()
1942 .map(|window| &window.surface)
1943 .unwrap_or(&second.face.surface);
1944 let supplemental = super::work_profile::supplemental(
1945 first_march,
1946 second_march,
1947 &SurfaceIntersectionOptions {
1948 tolerance: options.tolerance,
1949 maximum_step: options.maximum_ssi_step,
1950 span_budget: march_span_budget,
1951 ..Default::default()
1952 },
1953 ).or_refuse(KernelStage::Intersect, "csg.imprint.driver")?;
1954 let mut dropped_length = 0.0f64;
1955 let mut clipped: Vec<Vec<Vec3>> = Vec::new();
1956 for branch in &supplemental {
1957 for run in clip_branch_to_trims(&branch.points, first, second)? {
1958 if run.len() < 2 {
1959 continue;
1960 }
1961 let length: f64 = run
1962 .windows(2)
1963 .map(|pair| pair[1].sub(pair[0]).length())
1964 .sum();
1965 dropped_length = dropped_length.max(length);
1966 clipped.push(run);
1967 }
1968 }
1969 if dropped_length <= options.tolerance * 100.0 {
1970 if debug_pairs {
1971 eprintln!(
1972 "pair {}x{}: tangential-only contact, march skipped",
1973 first.face.id, second.face.id
1974 );
1975 }
1976 // TANGENT-CURVE LANE: the skip is right for a transverse
1977 // march, which has nothing to walk here, but the contact
1978 // may still be a CURVE inside both trims (the same
1979 // generatrix on a carrier no exact lane recognises).
1980 // Recognise and record it, typed, rather than lose it.
1981 if options.tangent_curve_lane {
1982 if let Some((section, run)) = tangent_curve_section(
1983 first, second, options, &first_faces, &second_faces, &face_edge_lists, debug_pairs,
1984 )? {
1985 if options.tangent_curve_imprint && section.planar && run.len() >= 2 {
1986 tangent_imprint_candidates.push((tangent_sections.len(), run, first, second));
1987 }
1988 tangent_sections.push(section);
1989 }
1990 }
1991 // RIM BRIDGE (`BREP_RIM_BRIDGE`, default on, `=0` off). A pair
1992 // tangent along one stretch (two swept walls along the
1993 // join of the sweeps) can still cross elsewhere along a
1994 // section shorter than the march can see: where a rim of
1995 // each operand passes the other at a grazing angle, each
1996 // rim pierces the other operand's face a few
1997 // `tol / |tan·n|` from the other's pierce, and the section
1998 // between the two pierces lies on both faces of this pair.
1999 // Its neighbours end at the two pierces; without it the
2000 // shell tears there. The bridge is the straight segment
2001 // between a crossing pierce of each operand inside both
2002 // trims, mutual nearest and within the grazing reach.
2003 if rim_bridge_enabled() {
2004 rim_bridge(&mut builder, first, second, first_march, second_march, &face_edge_lists, options, debug_pairs)?;
2005 }
2006 continue;
2007 }
2008 // A transverse curve EXISTS. What would make it unimprintable is
2009 // a tangent NODE on it — and the node need not lie inside the
2010 // trims. Two equal-radius pipe arms are tangent to each other
2011 // where their axes' common perpendicular leaves the junction,
2012 // and a joint ball wider than the arms trims that crotch off
2013 // both faces; what is left inside the trims is an ordinary
2014 // crossing. So the question is not "does a transverse curve
2015 // exist" but "does the curve INSIDE BOTH TRIMS reach a
2016 // tangency". Only the latter is the checkerboard case.
2017 let mut tangency_inside_trims = false;
2018 let mut tangency_witness = Vec3::default();
2019 'clipped: for run in &clipped {
2020 for (index, &point) in run.iter().enumerate() {
2021 if pair_normals_parallel_at(first, second, point)? {
2022 tangency_inside_trims = true;
2023 tangency_witness = point;
2024 if debug_pairs {
2025 eprintln!(
2026 "pair {}x{}: TANGENCY at run index {}/{} ({:.6},{:.6},{:.6}) dropped_len={:.4e}",
2027 first.face.id, second.face.id, index, run.len(),
2028 point.x, point.y, point.z, dropped_length
2029 );
2030 }
2031 break 'clipped;
2032 }
2033 }
2034 }
2035 if tangency_inside_trims {
2036 // WHAT SHAPE is the tangency? The witness is only a marched
2037 // sample within the transverse-seed angular gate, so it is
2038 // REFINED onto the contact before being classified — at the
2039 // raw witness a G1 cylinder/torus join and a genuine
2040 // equal-radius node are eighteen-fold apart, which would be
2041 // a band; at the refined contact they are thirty orders
2042 // apart, which is a rank question. See
2043 // `imprint/tangent_contact.rs`.
2044 let contact = classify_tangent_contact(
2045 &first.face.surface,
2046 &second.face.surface,
2047 tangency_witness,
2048 options.tolerance,
2049 )?;
2050 if debug_pairs {
2051 eprintln!(
2052 "pair {}x{}: contact classification {:?}",
2053 first.face.id, second.face.id, contact
2054 );
2055 }
2056 match contact {
2057 // An isolated node: the section is a curve everywhere
2058 // but that one point, so the ordinary march below runs
2059 // and the 2D arrangement carves the pinch on both
2060 // faces. `tangent_node` records it so a march that
2061 // cannot get through still refuses in THIS class rather
2062 // than leaking the marcher's own message.
2063 Some(contact) if contact.is_isolated_node() => {
2064 tangent_node = Some(contact.point);
2065 tangent_nodes.push(contact.point);
2066 }
2067 // An extended contact (rank-deficient) or a witness we
2068 // could not refine onto any contact at all (None — so
2069 // nothing is proven and the pre-classification refusal
2070 // stands). Neither has a section curve the imprint can
2071 // represent.
2072 // The witness's refinement held on an open edge of a
2073 // carrier, short of a contact: the contact lies off
2074 // the carrier, so within both the pair only nears
2075 // tangency at that edge and its section is an ordinary
2076 // curve (`BREP_IMPRINT_TANGENCY_OFF_CARRIER`).
2077 None if super::tangent_contact::tangency_off_carrier_on()
2078 && super::tangent_contact::tangency_runs_off_carrier(
2079 &first.face.surface,
2080 &second.face.surface,
2081 tangency_witness,
2082 options.tolerance,
2083 )?
2084 && every_other_tangency_admitted(first, second, &clipped, options.tolerance)? =>
2085 {
2086 if debug_pairs {
2087 eprintln!(
2088 "pair {}x{}: tangency witness refines off the carrier, marched as a section",
2089 first.face.id, second.face.id
2090 );
2091 }
2092 }
2093 other => {
2094 let shape = match other {
2095 Some(contact) => contact.describe(),
2096 None => format!(
2097 "the tangency near ({:.6},{:.6},{:.6}) could not be refined \
2098 onto a contact, so its shape is unproven",
2099 tangency_witness.x, tangency_witness.y, tangency_witness.z
2100 ),
2101 };
2102 return Err(KernelRefusal::new(
2103 RefusalClass::TangentNodeSingularity,
2104 KernelStage::Intersect,
2105 format!(
2106 "boolean: unsupported singular/tangent-node surface intersection \
2107 between faces {} and {}: {shape}",
2108 first.face.id, second.face.id
2109 ),
2110 ));
2111 }
2112 }
2113 }
2114 if debug_pairs && tangent_node.is_none() {
2115 // Transverse the whole way inside both trims: the coarse
2116 // 5x5 classifier only saw the tangency the trims cut away.
2117 eprintln!(
2118 "pair {}x{}: classified tangential-only, but the curve inside both \
2119 trims is transverse ({dropped_length:.4}) — marching",
2120 first.face.id, second.face.id
2121 );
2122 }
2123 }
2124
2125 // The trim-window carriers: same surface and parameterization
2126 // over the window, so hit (u, v) values remain valid on the
2127 // originals; out-of-window intersections could never survive
2128 // clip_branch_to_trims and are not walked at all.
2129 let first_march = first_restricted[first_index]
2130 .as_ref()
2131 .map(|window| &window.surface)
2132 .unwrap_or(&first.face.surface);
2133 let second_march = second_restricted[second_index]
2134 .as_ref()
2135 .map(|window| &window.surface)
2136 .unwrap_or(&second.face.surface);
2137 // Trim-window carriers PROVED apart by their span hulls
2138 // (`BREP_SSI_SEPARATION_PREFILTER`) have nothing to seed or march:
2139 // every cheaper lane above has had the pair, and only the pairs
2140 // that reach the march pay for the proof (each face's hulls are
2141 // built once).
2142 let proved_apart = crate::separation_prefilter_enabled() && {
2143 let hulls_a = first_hulls[first_index].get_or_init(|| crate::SpanHullSet::of(first_march));
2144 let hulls_b = second_hulls[second_index].get_or_init(|| crate::SpanHullSet::of(second_march));
2145 matches!((hulls_a, hulls_b), (Some(a), Some(b)) if crate::hull_sets_proved_apart(a, b, options.tolerance * 10.0))
2146 };
2147 if proved_apart {
2148 proved_apart_pairs.insert((first_index, second_index));
2149 profile.seeds += profile.lap(&mut lap_start);
2150 if debug_pairs {
2151 eprintln!("pair {}x{}: trim-window carriers proved apart, not marched", first.face.id, second.face.id);
2152 }
2153 continue;
2154 }
2155 let pair_hermite_lane = hermite_lane && super::hermite::refinement_carriers_eligible(
2156 &first.face.surface, &second.face.surface,
2157 );
2158 let mut seed_points = Vec::new();
2159 // Smallest |edge_tangent · surface_normal| over accepted seeds — the
2160 // local grazing measure at the trim crossings (near 0 = the edge
2161 // pierces the other surface tangentially). Gates the near-tangent
2162 // clip-order rescue below to genuinely grazing pairs.
2163 let mut min_seed_tangency = f64::INFINITY;
2164 // Two grazing crossings of one trim edge bound a real, narrow
2165 // interval. It cannot tolerate a section fit that misses either
2166 // crossing, even when a coarse whole-model distance looks small.
2167 let mut paired_grazing_crossings = false;
2168 // Every hit the seed gate rejected, for the whole pair: the
2169 // point, its `|tan·n|`, the edge (its operand, its id) and the
2170 // parameter on it, and whether that edge belongs to `first`.
2171 // Read only when the march comes back empty, below, where the
2172 // genuine crossings among them are told from lies-on samples.
2173 let mut grazing_hits: Vec<(Vec3, f64, u8, u64, f64, bool)> = Vec::new();
2174 for (face, other_march, other) in
2175 [(first, second_march, second), (second, first_march, first)]
2176 {
2177 for edge in &face_edge_lists[&face.key()] {
2178 if edge.degenerate {
2179 continue;
2180 }
2181 let mut grazing_crossings: Vec<Vec3> = Vec::new();
2182 // LIES-ON SKIP (2026-10-17, the shelled-box report's
2183 // offset bore against the offset blend walls): an edge
2184 // that LIES ON the other carrier — the test the exchange
2185 // stage above already trusted to hand the whole edge over
2186 // as a shared span — returns a hit per sample from
2187 // `intersect_curve_surface`, every one grazing (|tan.n| = 0
2188 // on a curve in the surface) and every one rejected: three
2189 // such edges answered 8 580 of that pair's 8 586 seed hits
2190 // at 0.36 s. Such an edge contributes no seed, no tangency
2191 // minimum and no section evidence; its one effect is the
2192 // paired-grazing flag, set when two of its grazing points
2193 // sit more than the weld apart, which is reproduced here
2194 // from the edge's own extent. `BREP_IMPRINT_LIES_ON_SEED_SKIP=0`
2195 // runs the solve as before.
2196 if lies_on_seed_skip_enabled() {
2197 let subcurve = cached_subcurve(face.operand, edge)?;
2198 if super::support::curve_lies_on_surface(&subcurve, other_march, options.tolerance)? {
2199 let [start, end] = subcurve.domain().or_refuse(KernelStage::Intersect, "domain")?;
2200 let mut probes = Vec::with_capacity(5);
2201 for fraction in [0.0, 0.25, 0.5, 0.75, 1.0] {
2202 probes.push(subcurve.evaluate(start + (end - start) * fraction).or_refuse(KernelStage::Intersect, "evaluate")?);
2203 }
2204 let weld = assembler_weld(options.tolerance);
2205 if probes.iter().any(|a| probes.iter().any(|b| a.sub(*b).length() > weld)) {
2206 paired_grazing_crossings = true;
2207 }
2208 if debug_pairs {
2209 eprintln!(
2210 "pair {}x{}: seed edge {} lies on the other carrier — seed solve skipped",
2211 first.face.id, second.face.id, edge.id
2212 );
2213 }
2214 continue;
2215 }
2216 }
2217 for hit in intersect_curve_surface(&edge.curve, other_march, options.tolerance).or_refuse(KernelStage::Intersect, "intersect_curve_surface")?
2218 {
2219 if hit.t < edge.t0 - 1e-9 || hit.t > edge.t1 + 1e-9 {
2220 continue;
2221 }
2222 let derivative = edge.curve.derivatives(hit.t, 1).or_refuse(KernelStage::Intersect, "derivatives")?[1];
2223 // A STATIONARY POINT on the edge curve is not a reason
2224 // to refuse the boolean. An involute flank starts at
2225 // the base circle with an exactly zero tangent, so a
2226 // gear tooth's profile carries one cusp per flank, and
2227 // a hit landing on that parameter used to propagate
2228 // "Vec3.normalized: zero-length vector" out of the
2229 // whole union (the 2026-09-14 herringbone report: the
2230 // second tooth band's z=0 cap edge meets the first
2231 // band's flank exactly at the cusp). The direction is
2232 // still defined as the one-sided limit, so read it from
2233 // just inside the edge's own range; an edge with no
2234 // direction at all simply contributes no seed, exactly
2235 // as a hit whose face normal is unavailable already
2236 // does two lines below. Seeds are marcher hints, so a
2237 // dropped one costs a hint, never an answer.
2238 // Escape hatch for tamper-verification:
2239 // BREP_CUSP_TANGENT_RESCUE=0 restores the refusal.
2240 let tangent = match derivative.normalized() {
2241 Ok(tangent) => tangent,
2242 Err(error) => {
2243 if std::env::var("BREP_CUSP_TANGENT_RESCUE").as_deref() == Ok("0") {
2244 return Err(error)
2245 .or_refuse(KernelStage::Intersect, "normalized");
2246 }
2247 match edge.curve.stationary_tangent_rescue(hit.t, edge.t0, edge.t1)
2248 {
2249 Some(tangent) => tangent,
2250 None => continue,
2251 }
2252 }
2253 };
2254 // `hit` was solved on the other face's MARCH WINDOW, so
2255 // its uv is in that face's chart — a period off the
2256 // carrier's where the window is lifted, and `normal`
2257 // clamps a parameter past its domain.
2258 let normal = match other.chart().normal(hit.u, hit.v) {
2259 Ok(normal) => normal,
2260 Err(_) => continue,
2261 };
2262 if debug_pairs {
2263 eprintln!(
2264 "pair {}x{}: seed edge {} t={:.6} p=({:.5},{:.5},{:.5}) |tan.n|={:.4} {}",
2265 first.face.id,
2266 second.face.id,
2267 edge.id,
2268 hit.t,
2269 hit.point.x,
2270 hit.point.y,
2271 hit.point.z,
2272 tangent.dot(normal).abs(),
2273 if tangent.dot(normal).abs() >= 0.1 { "ACCEPT" } else { "reject" }
2274 );
2275 }
2276 if tangent.dot(normal).abs() >= 0.1 {
2277 seed_points.push(hit.point);
2278 min_seed_tangency = min_seed_tangency.min(tangent.dot(normal).abs());
2279 section_evidence = true;
2280 } else {
2281 if grazing_crossings.iter().any(|point| {
2282 point.sub(hit.point).length() > assembler_weld(options.tolerance)
2283 }) {
2284 paired_grazing_crossings = true;
2285 }
2286 grazing_crossings.push(hit.point);
2287 grazing_hits.push((
2288 hit.point,
2289 tangent.dot(normal).abs(),
2290 face.operand,
2291 edge.id,
2292 hit.t,
2293 face.operand == first.operand && face.face.id == first.face.id,
2294 ));
2295 }
2296 }
2297 }
2298 }
2299 profile.seeds += profile.lap(&mut lap_start);
2300 // POINT CONTACT (`BREP_IMPRINT_PLANE_POINT_SKIP`, lane X row 5):
2301 // two exact parallelograms meeting at one point have no section
2302 // curve. Once a seed is accepted the pair's contact evidence is
2303 // already recorded and the march could only trace that point, so
2304 // it is skipped; an unseeded pair still marches.
2305 if !seed_points.is_empty()
2306 && plane_point_skip_enabled()
2307 && super::support::planar_point_contact(&first.face.surface, &second.face.surface, options.tolerance) == Some(true)
2308 {
2309 PLANE_POINT_SKIPS.with(|count| count.set(count.get() + 1));
2310 if debug_pairs {
2311 eprintln!("pair {}x{}: planar point contact, march skipped", first.face.id, second.face.id);
2312 }
2313 continue;
2314 }
2315 // BOUNDARY TOUCH (`BREP_IMPRINT_BOUNDARY_TOUCH`, default off): a carrier
2316 // that meets a flat face's plane only along one of its own boundary
2317 // iso-curves ([`super::support::touches_plane_only_on_boundary`]) has
2318 // no section but that boundary, which the edge exchange imprints; the
2319 // march along it traced the rim in short branches a ULP decided.
2320 if super::support::boundary_touch_enabled()
2321 && (super::support::touches_plane_only_on_boundary(&first.face.surface, &second.face.surface, options.tolerance)
2322 || super::support::touches_plane_only_on_boundary(&second.face.surface, &first.face.surface, options.tolerance))
2323 {
2324 if debug_pairs {
2325 eprintln!("pair {}x{}: boundary touch on a flat face, march skipped", first.face.id, second.face.id);
2326 }
2327 continue;
2328 }
2329 profile.marched_pairs += 1;
2330 if debug_pairs {
2331 eprintln!(
2332 "pair {}x{}: marching (relation {:?})...",
2333 first.face.id, second.face.id, pair_classification.relation
2334 );
2335 }
2336 let marched = super::work_profile::trace(
2337 first_march,
2338 second_march,
2339 &SurfaceIntersectionOptions {
2340 tolerance: options.tolerance,
2341 maximum_step: march_maximum_step(
2342 &pair_classification,
2343 options.maximum_ssi_step,
2344 builder.scale,
2345 ),
2346 seed_points: seed_points.clone(),
2347 span_budget: march_span_budget,
2348 ordered_starts,
2349 consume_starts,
2350 tree_seeds,
2351 ..Default::default()
2352 },
2353 );
2354 // A pair carrying a tangent node keeps its OWN refusal class when
2355 // the march fails: the node is why the trace cannot close, and the
2356 // equal-radius torus pair depends on being told so rather than on
2357 // reading a step-budget message it cannot act on.
2358 let marched = match (marched, tangent_node) {
2359 (Err(error), Some(node)) => {
2360 return Err(KernelRefusal::new(
2361 RefusalClass::TangentNodeSingularity,
2362 KernelStage::Intersect,
2363 format!(
2364 "boolean: unsupported singular/tangent-node surface intersection \
2365 between faces {} and {}: the section through the tangent node at \
2366 ({:.6},{:.6},{:.6}) could not be marched ({error})",
2367 first.face.id, second.face.id, node.x, node.y, node.z
2368 ),
2369 ));
2370 }
2371 (marched, _) => marched,
2372 };
2373 let mut branches = marched
2374 .map_err(|error| {
2375 format!(
2376 "{error} (marching faces {} and {})",
2377 first.face.id, second.face.id
2378 )
2379 }).or_refuse(KernelStage::Intersect, "csg.imprint.driver")?;
2380 profile.march += profile.lap(&mut lap_start);
2381 let rescue_started = profile.enabled.then(Instant::now);
2382 // MARCH-ORDER SWAP RESCUE (hatch BREP_MARCH_SWAP_RESCUE=0).
2383 // `intersect_surfaces` is not order-symmetric: the coupled Newton
2384 // trace can fail to start/continue from a valid seed when the two
2385 // surfaces are presented in one operand order yet succeed in the
2386 // other. This is the sole reason t217's `subtract(sphere, step)`
2387 // fails while every other op passes — pair 118x842 (sphere-first)
2388 // marches ZERO branches, while 842x118 (step-first, the working
2389 // a\b order) marches the section from the IDENTICAL accepted pierce
2390 // seeds. When the forward order returns no branch AND an accepted
2391 // transverse pierce seed exists (so a real section provably crosses
2392 // both trims), retry the march with the surfaces swapped — i.e.
2393 // reproduce the exact call the working operand order makes for this
2394 // pair (measured: seed_only alone does NOT recover it — the section
2395 // is found from an auto-grid start, not from the near-tangent pierce
2396 // seeds, which the seed normal-cross gate rejects). The returned
2397 // branch points are 3D and therefore order-independent, so no
2398 // parameter remap is needed; they flow through the identical clip /
2399 // process_curve gates below, which drop any out-of-trim or
2400 // sub-length run exactly as today. The rescue only ever runs when
2401 // the forward order found NOTHING, so it cannot alter a pair that
2402 // already marched.
2403 if branches.is_empty()
2404 && !seed_points.is_empty()
2405 && pair_classification.relation == SurfacePairRelation::Candidate
2406 && std::env::var("BREP_MARCH_SWAP_RESCUE").as_deref() != Ok("0")
2407 {
2408 // FAIL-SOFT: the forward order already returned Ok(empty); a
2409 // swapped-march error (trace-exhaustion is a real error class —
2410 // `intersect_surfaces_supplemental` swallows it for exactly this
2411 // reason) must NOT convert that graceful empty into a hard error.
2412 // On Err, keep the (empty) forward result and carry on.
2413 let swapped = super::work_profile::trace(
2414 second_march,
2415 first_march,
2416 &SurfaceIntersectionOptions {
2417 tolerance: options.tolerance,
2418 maximum_step: march_maximum_step(
2419 &pair_classification,
2420 options.maximum_ssi_step,
2421 builder.scale,
2422 ),
2423 seed_points: seed_points.clone(),
2424 span_budget: march_span_budget,
2425 ordered_starts,
2426 consume_starts,
2427 tree_seeds,
2428 ..Default::default()
2429 },
2430 )
2431 .unwrap_or_default();
2432 if debug_pairs {
2433 eprintln!(
2434 "pair {}x{}: MARCH-SWAP RESCUE attempt -> {} branches, pts {:?}",
2435 first.face.id,
2436 second.face.id,
2437 swapped.len(),
2438 swapped.iter().map(|b| b.points.len()).collect::<Vec<_>>()
2439 );
2440 }
2441 if !swapped.is_empty() {
2442 branches = swapped;
2443 march_swap_rescues += 1;
2444 }
2445 }
2446 // NEAR-TANGENT CLIP-ORDER RESCUE (hatch BREP_MARCH_SWAP_CLIP_RESCUE=0).
2447 // Companion to the empty-branch MARCH-SWAP RESCUE above:
2448 // `intersect_surfaces` is order-asymmetric not only in WHETHER it
2449 // marches, but in the exact sample positions of the section
2450 // polyline. On a NEAR-TANGENT graze, `clip_branch_to_trims`
2451 // classifies those samples against the mutual trims, and a sample
2452 // landing just past the near-tangent boundary is dropped as a
2453 // false-Outside that TRUNCATES the clipped section. The two operand
2454 // orders drop DIFFERENT near-tangent tail samples, so one order
2455 // yields a section ~0.1-0.2mm shorter at ONE endpoint (t660: b\a's
2456 // step-first order clips pairs 223x105/399x105 ~0.22/0.14mm short of
2457 // the section a\b's cyl-first order keeps, stranding edge 173
2458 // one-use). Near-tangent clip errors are almost exclusively
2459 // false-Outside (a point truly outside a trim rarely projects to an
2460 // in-trim uv), so the order with the LONGER clipped section suffered
2461 // fewer drops and is the more complete one. When the swapped order
2462 // marches the SAME branch structure with a meaningfully longer
2463 // clipped total, adopt its branches (3D points, so they flow through
2464 // the identical clip/process_curve gates below). Gated to Candidate
2465 // pairs (the near-tangent/ambiguous class; clean Transverse
2466 // crossings clip identically in both orders and never differ) with
2467 // an accepted GRAZING pierce seed (min |tan·n| < 0.5 — a real
2468 // section provably crosses, and does so near-tangentially, the only
2469 // regime where the clip wobbles; this also bounds the extra march to
2470 // grazing pairs), and requires a >0.1%-of-length margin so
2471 // raw-sampling jitter (t660: 0.02%) cannot flip a clean pair.
2472 // Fail-soft: any swapped-march or comparison-clip error keeps the
2473 // forward result.
2474 if !branches.is_empty()
2475 && !seed_points.is_empty()
2476 && min_seed_tangency < 0.5
2477 && pair_classification.relation == SurfacePairRelation::Candidate
2478 && std::env::var("BREP_MARCH_SWAP_CLIP_RESCUE").as_deref() != Ok("0")
2479 {
2480 let swapped = super::work_profile::trace(
2481 second_march,
2482 first_march,
2483 &SurfaceIntersectionOptions {
2484 tolerance: options.tolerance,
2485 maximum_step: march_maximum_step(
2486 &pair_classification,
2487 options.maximum_ssi_step,
2488 builder.scale,
2489 ),
2490 seed_points: seed_points.clone(),
2491 span_budget: march_span_budget,
2492 ordered_starts,
2493 consume_starts,
2494 tree_seeds,
2495 ..Default::default()
2496 },
2497 )
2498 .unwrap_or_default();
2499 // Only a swap that reproduces the SAME branch count — a
2500 // refined-endpoint variant of the same section, not a different
2501 // branch decomposition (guards against adopting a spurious
2502 // extra branch as "longer").
2503 if !swapped.is_empty() && swapped.len() == branches.len() {
2504 let totals = (|| -> Result<(f64, f64), KernelRefusal> {
2505 let mut fwd = 0.0;
2506 for b in &branches {
2507 let refined = insert_seed_points_into_branch(
2508 &b.points,
2509 &seed_points,
2510 options.tolerance,
2511 );
2512 for run in clip_branch_to_trims(&refined, first, second)? {
2513 fwd += run
2514 .windows(2)
2515 .map(|p| p[1].sub(p[0]).length())
2516 .sum::<f64>();
2517 }
2518 }
2519 let mut swp = 0.0;
2520 for b in &swapped {
2521 let refined = insert_seed_points_into_branch(
2522 &b.points,
2523 &seed_points,
2524 options.tolerance,
2525 );
2526 for run in clip_branch_to_trims(&refined, first, second)? {
2527 swp += run
2528 .windows(2)
2529 .map(|p| p[1].sub(p[0]).length())
2530 .sum::<f64>();
2531 }
2532 }
2533 Ok((fwd, swp))
2534 })();
2535 if let Ok((fwd_clip, swp_clip)) = totals {
2536 let margin = fwd_clip.max(swp_clip) * 1.0e-3;
2537 let adopt = swp_clip > fwd_clip + margin;
2538 if debug_pairs {
2539 eprintln!(
2540 "pair {}x{}: CLIP-SWAP RESCUE fwd_clip={:.6} swp_clip={:.6} margin={:.6}{}",
2541 first.face.id,
2542 second.face.id,
2543 fwd_clip,
2544 swp_clip,
2545 margin,
2546 if adopt { " ADOPT" } else { "" }
2547 );
2548 }
2549 if adopt {
2550 branches = swapped;
2551 clip_swap_rescues += 1;
2552 }
2553 }
2554 }
2555 }
2556 if let Some(started) = rescue_started {
2557 profile.rescue_march += started.elapsed();
2558 }
2559 // CROSSING-NODE SPLIT (`BREP_SSI_NODE_SPLIT`, default on, `=0` off;
2560 // `intersect/crossing_node.rs`): a branch the marcher carried
2561 // through a saddle tangent node is cut at every passage, so the
2562 // node is a vertex where the four half-branches meet.
2563 if crate::crossing_node_split_enabled() && !branches.is_empty() {
2564 let (split, nodes) = crate::split_at_crossing_nodes(
2565 first_march,
2566 second_march,
2567 std::mem::take(&mut branches),
2568 options.tolerance,
2569 )
2570 .or_refuse(KernelStage::Intersect, "csg.imprint.driver")?;
2571 branches = split;
2572 for node in nodes {
2573 if debug_pairs {
2574 eprintln!(
2575 "pair {}x{}: crossing node ({:.9},{:.9},{:.9}) split the march",
2576 first.face.id, second.face.id, node.x, node.y, node.z
2577 );
2578 }
2579 tangent_node.get_or_insert(node);
2580 if !tangent_nodes.iter().any(|known| known.sub(node).length() <= options.tolerance * 10.0) {
2581 tangent_nodes.push(node);
2582 }
2583 }
2584 }
2585 if branches.iter().any(|branch| branch.points.len() >= 2) {
2586 section_evidence = true;
2587 }
2588 if debug_pairs {
2589 eprintln!(
2590 "pair {}x{}: MARCH {} branches, pts {:?}",
2591 first.face.id,
2592 second.face.id,
2593 branches.len(),
2594 branches.iter().map(|b| b.points.len()).collect::<Vec<_>>()
2595 );
2596 }
2597 // GRAZING PIERCE, NO SECTION (2026-10-17, the revolve-into-bore
2598 // report). A trim edge of one face pierces the other carrier at
2599 // an angle below the seed gate, inside BOTH trims, and the pair
2600 // marched nothing: the pierce proves a section crosses the faces
2601 // there, the empty march says the crossing is too near tangency
2602 // for the marcher's start gate to admit (the -4° revolve of a
2603 // bored box's top face about its back edge, unioned back: the
2604 // torus hole wall continues the bore tangentially along their
2605 // shared rim and crosses it again at 0.002 rad — a third-order
2606 // contact, `boolean::attribute_to_tangent_node`). Nothing is
2607 // imprinted here; the contact is RECORDED, with the faces across
2608 // the pierced edges, so a tear downstream of it is attributed to
2609 // the contact in the tangent-node class — which declines the
2610 // perturbation ladder — instead of leaking as an anonymous
2611 // open-edge arrangement and burning the ladder's rungs (12.5 s
2612 // on the report, every rung refused by its mirror). A pair whose
2613 // pierce the trims do not both contain is left alone, as is one
2614 // with an accepted seed: those pairs the march could and should
2615 // have answered. `BREP_GRAZING_PIERCE_RECORD=0` is the hatch.
2616 if branches.is_empty()
2617 && seed_points.is_empty()
2618 && !grazing_hits.is_empty()
2619 && options.tangent_curve_lane
2620 && std::env::var("BREP_GRAZING_PIERCE_RECORD").as_deref() != Ok("0")
2621 {
2622 let mut inside: Vec<(Vec3, f64, u8, u64)> = Vec::new();
2623 for &(point, tangency, operand, edge_id, t, on_first) in &grazing_hits {
2624 // A pierce, not a lies-on sample: the edge must CROSS the
2625 // carrier at the hit (a rim lying on the other carrier
2626 // reads |tan·n| = 0 at every sample and never changes
2627 // side) — and inside both trims.
2628 let (owner, other_march) = if on_first { (first, second_march) } else { (second, first_march) };
2629 let Some(edge) = face_edge_lists[&owner.key()].iter().find(|edge| edge.id == edge_id) else {
2630 continue;
2631 };
2632 let crosses = edge_crosses_carrier(edge, &face_edge_lists[&owner.key()], t, other_march, options.tolerance)?
2633 && !(super::support::near_end_snap_enabled() && pierce_is_end_contact(edge, t, point, other_march, options.tolerance)?);
2634 // The two halves of a split edge report one pierce at
2635 // their shared vertex: it is one section point, once.
2636 if crosses && inside.iter().any(|(seen, ..)| seen.sub(point).length() <= options.tolerance) {
2637 continue;
2638 }
2639 let contained = crosses && inside_both_trims(point, first, second)?;
2640 if debug_pairs && crosses {
2641 eprintln!(
2642 "pair {}x{}: grazing pierce op={operand} edge={edge_id} ({:.6},{:.6},{:.6}) |tan.n|={tangency:.4} inside both trims: {contained}",
2643 first.face.id, second.face.id, point.x, point.y, point.z
2644 );
2645 }
2646 if contained {
2647 inside.push((point, tangency, operand, edge_id));
2648 }
2649 }
2650 // SUB-GATE RE-MARCH (2026-10-17, the same report, second
2651 // half). The pierces are PROVEN section points, so the march
2652 // is retried from them alone, admitted below the marcher's
2653 // start gate: the crossing is resolvable while its lateral
2654 // uncertainty `tol / α` fits inside the tangency band's
2655 // half-width `√(2 R tol)`, i.e. `α ≥ √(tol / 2R)`, and no
2656 // carrier is curved tighter than the model, so the bound is
2657 // taken at `R = scale`. Grid starts stay gated (their
2658 // tangency-band runaway is the gate's reason). A branch that
2659 // comes back is imprinted exactly as a marched one; only when
2660 // none does is the contact recorded for the attribution. The
2661 // retry is fail-soft like the swap rescue: an Err keeps the
2662 // empty forward result. Hatch: BREP_GRAZING_SEED_MARCH=0.
2663 if !inside.is_empty() && std::env::var("BREP_GRAZING_SEED_MARCH").as_deref() != Ok("0") {
2664 let bound = (options.tolerance / (2.0 * builder.scale.max(options.tolerance))).sqrt();
2665 let pierces: Vec<Vec3> = inside.iter().map(|(point, _, _, _)| *point).collect();
2666 let rescued = super::work_profile::trace(
2667 first_march,
2668 second_march,
2669 &SurfaceIntersectionOptions {
2670 tolerance: options.tolerance,
2671 maximum_step: march_maximum_step(
2672 &pair_classification,
2673 options.maximum_ssi_step,
2674 builder.scale,
2675 ),
2676 seed_points: pierces.clone(),
2677 seed_only: true,
2678 seed_start_cross: Some(bound),
2679 span_budget: march_span_budget,
2680 ordered_starts,
2681 consume_starts,
2682 tree_seeds,
2683 ..Default::default()
2684 },
2685 )
2686 .unwrap_or_default();
2687 if debug_pairs {
2688 eprintln!(
2689 "pair {}x{}: SUB-GATE MARCH from {} pierce(s) at bound {bound:.3e} -> {} branches, pts {:?}",
2690 first.face.id,
2691 second.face.id,
2692 pierces.len(),
2693 rescued.len(),
2694 rescued.iter().map(|b| b.points.len()).collect::<Vec<_>>()
2695 );
2696 }
2697 if !rescued.is_empty() {
2698 branches = rescued;
2699 grazing_march = true;
2700 // The pierces are the branches' exact trim crossings,
2701 // inserted below like any accepted seed.
2702 seed_points.extend(pierces);
2703 inside.clear();
2704 }
2705 }
2706 if !inside.is_empty() {
2707 if debug_pairs {
2708 eprintln!(
2709 "pair {}x{}: {} grazing pierce(s) inside both trims and no marched branch: {}",
2710 first.face.id,
2711 second.face.id,
2712 inside.len(),
2713 inside
2714 .iter()
2715 .map(|(point, tangency, operand, edge)| format!(
2716 "op={operand} edge={edge} ({:.6},{:.6},{:.6}) |tan.n|={tangency:.4}",
2717 point.x, point.y, point.z
2718 ))
2719 .collect::<Vec<_>>()
2720 .join(", ")
2721 );
2722 }
2723 // The extended contact the lane can name, when it finds
2724 // one (the shared rim here); else the record stands on
2725 // the pierces alone.
2726 let mut section = match tangent_curve_section(
2727 first, second, options, &first_faces, &second_faces, &face_edge_lists, debug_pairs,
2728 )? {
2729 Some((section, _run)) => section,
2730 None => TangentSectionRecord {
2731 first: first.key(),
2732 second: second.key(),
2733 start: inside[0].0,
2734 end: inside[inside.len() - 1].0,
2735 length: 0.0,
2736 closed: false,
2737 stations: 0,
2738 planar: false,
2739 faces: vec![first.key(), second.key()],
2740 piece_ids: Vec::new(),
2741 grazing: Vec::new(),
2742 },
2743 };
2744 // The faces across each pierced edge: the pierce is where
2745 // the missing section meets that edge, so those faces are
2746 // the ones a tear downstream of it will name.
2747 for (_, _, operand, edge_id) in &inside {
2748 let siblings = if *operand == first.operand { &first_faces } else { &second_faces };
2749 for sibling in siblings.iter() {
2750 let shares = sibling
2751 .face
2752 .loops
2753 .iter()
2754 .flat_map(|loop_record| &loop_record.coedges)
2755 .any(|coedge| coedge.edge_id == *edge_id);
2756 if shares && !section.faces.contains(&sibling.key()) {
2757 section.faces.push(sibling.key());
2758 }
2759 }
2760 }
2761 section.grazing = inside.iter().map(|(point, tangency, _, _)| (*point, *tangency)).collect();
2762 tangent_sections.push(section);
2763 }
2764 }
2765 if profile.enabled {
2766 // Net metadata only: observing carriers must not warm their
2767 // recognition/projection caches before the section fitter.
2768 profile_line!("imprint.march_pair first={:?} second={:?} ids={}x{} degrees={}x{}/{}x{} nets={}x{}/{}x{} stations={:?}",
2769 first.face.name, second.face.name, first.face.id, second.face.id,
2770 first.face.surface.degree_u, first.face.surface.degree_v,
2771 second.face.surface.degree_u, second.face.surface.degree_v,
2772 first.face.surface.control_points.len(), first.face.surface.control_points.first().map_or(0, Vec::len),
2773 second.face.surface.control_points.len(), second.face.surface.control_points.first().map_or(0, Vec::len),
2774 branches.iter().map(|branch| branch.points.len()).collect::<Vec<_>>());
2775 }
2776 // GRAZING PIERCES BOUND CLIP INTERVALS TOO (hosted report
2777 // 2026-11-01, "Boolean seems to take way too long": the cage-box
2778 // union with the cylinder moved 0.165 off the cage's axis). The
2779 // seed gate rejects a pierce whose `|tan·n|` is under 0.1 as a
2780 // march START, but the point is still an exact section point on
2781 // a trim edge: the end of a trim interval. The cylinder's bottom
2782 // rim crosses the cage's flat-to-second-order side twice, 0.036
2783 // apart, at `|tan·n|` = 0.0035, so the disc keeps a 0.036-long
2784 // piece of the y = 0 section there. Marched from the accepted
2785 // seeds with ~0.9 stations, that interval held no station, the
2786 // clip dropped it, the disc's two lenses stayed unbounded and
2787 // the arrangement tore: an open-edge refusal that sent the union
2788 // up the perturbation ladder (64 imprints, ~39 s native, every
2789 // rung refused). Inserting the rejected hits — gated, like every
2790 // seed, to the ones lying on the branch — gives such an interval
2791 // its endpoints. Only a RESOLVABLE pierce is inserted: its
2792 // position along the edge is known to `tol / |tan·n|`, so the
2793 // same bound the sub-gate re-march below admits a start at,
2794 // `|tan·n| >= √(tol / 2·scale)`, keeps the lateral uncertainty
2795 // inside the tangency band. Below it the hits are lies-on
2796 // samples (an edge in the other carrier reads |tan·n| = 0 at
2797 // every sample) or near-tangent brushes whose along-edge
2798 // position is a guess: the 2026-10-25 offset-shell history
2799 // (`successive_fillet_history_shells_under_the_one_call_imprint`)
2800 // inserts 25 pairs' worth of such points at |tan·n| ≤ 1.1e-4 and
2801 // its O.S10 pcurve fit then misses its stations by 2.6e-3.
2802 // `BREP_GRAZING_CLIP_REFINE=0` restores the accepted seeds alone.
2803 let clip_points: std::borrow::Cow<'_, [Vec3]> = if grazing_hits.is_empty()
2804 || std::env::var("BREP_GRAZING_CLIP_REFINE").as_deref() == Ok("0")
2805 {
2806 std::borrow::Cow::Borrowed(&seed_points)
2807 } else {
2808 let resolvable = (options.tolerance / (2.0 * builder.scale.max(options.tolerance))).sqrt();
2809 // A crease fading to tangency along a rim brushes it at |tan.n|
2810 // around 1e-4 for its last stretch, and those hits cut the
2811 // section into micro-pieces whose ends disagree; the interval
2812 // this path exists for pierced at 3.5e-3. `BREP_GRAZING_CLIP_FLOOR=0`
2813 // restores the resolvable bound alone.
2814 let resolvable = if switch!("BREP_GRAZING_CLIP_FLOOR", true) { resolvable.max(1e-3) } else { resolvable };
2815 let mut points = seed_points.clone();
2816 points.extend(grazing_hits.iter().filter(|hit| hit.1 >= resolvable).map(|hit| hit.0));
2817 if debug_pairs && points.len() != seed_points.len() {
2818 eprintln!(
2819 "pair {}x{}: {} grazing pierce(s) at |tan.n| >= {resolvable:.3e} join the trim clip",
2820 first.face.id, second.face.id, points.len() - seed_points.len()
2821 );
2822 }
2823 std::borrow::Cow::Owned(points)
2824 };
2825 for branch in branches {
2826 // The pierce seeds are the section's exact trim-crossing
2827 // points — insert them so no trim interval shorter than the
2828 // march step is invisible to the point-classification clip.
2829 let refined_points =
2830 insert_seed_points_into_branch(&branch.points, &clip_points, options.tolerance);
2831 let clip_started = profile.enabled.then(Instant::now);
2832 let mut runs = clip_branch_to_trims(&refined_points, first, second)?;
2833 // TANGENT-RIM LANDING: a run the march stalled short of a trim
2834 // edge the two carriers are tangent along ends ON that edge
2835 // (see `land_run_ends_on_tangent_rim`).
2836 // Reached for the pairs whose march can stall short: one
2837 // carrying an admitted node, one marched from sub-gate
2838 // pierces, or one the classifier read as near-tangent (the
2839 // −10° sibling: no node admitted, an ordinary march that
2840 // stops 4e-5 short of the rim it is tangent along).
2841 if tangent_node.is_some()
2842 || grazing_march
2843 || pair_classification.relation == SurfacePairRelation::NearTangent
2844 {
2845 for run in runs.iter_mut() {
2846 for (operand, edge_id, parameter, from, to) in land_run_ends_on_tangent_node(
2847 run,
2848 first,
2849 second,
2850 &face_edge_lists,
2851 options.tolerance,
2852 )? {
2853 if debug_pairs {
2854 eprintln!(
2855 "pair {}x{}: tangent-node landing: run end ({:.6},{:.6},{:.6}) -> \
2856 node ({:.9},{:.9},{:.9}) on operand {operand} edge {edge_id} at t={parameter:.9}",
2857 first.face.id, second.face.id, from.x, from.y, from.z, to.x, to.y, to.z
2858 );
2859 }
2860 let edge = builder.edges[&(operand, edge_id)];
2861 builder.add_edge_split(operand, edge, parameter)?;
2862 }
2863 for (operand, edge_id, parameter, from, to) in land_run_ends_on_tangent_rim(
2864 run,
2865 tangent_node,
2866 first,
2867 second,
2868 &face_edge_lists,
2869 options.tolerance,
2870 )? {
2871 if debug_pairs {
2872 eprintln!(
2873 "pair {}x{}: tangent-rim landing: run end ({:.6},{:.6},{:.6}) -> \
2874 ({:.6},{:.6},{:.6}) on operand {operand} edge {edge_id} at t={parameter:.6}",
2875 first.face.id, second.face.id, from.x, from.y, from.z, to.x, to.y, to.z
2876 );
2877 }
2878 let edge = builder.edges[&(operand, edge_id)];
2879 builder.add_edge_split(operand, edge, parameter)?;
2880 }
2881 }
2882 }
2883 if debug_pairs {
2884 let dups = |points: &[Vec3]| points.windows(2).enumerate().filter(|(_, pair)| pair[1].sub(pair[0]).length() <= options.tolerance).map(|(i, pair)| format!("{i}:{:.2e}", pair[1].sub(pair[0]).length())).collect::<Vec<_>>();
2885 eprintln!(
2886 "pair {}x{}: DUPS branch {:?} seeded {:?} runs {:?} seeds {} branch_pts {} seeded_pts {}",
2887 first.face.id, second.face.id, dups(&branch.points), dups(&refined_points), runs.iter().map(|run| dups(run)).collect::<Vec<_>>(), seed_points.len(), branch.points.len(), refined_points.len()
2888 );
2889 }
2890 if let Some(started) = clip_started {
2891 profile.clip += started.elapsed();
2892 }
2893 for run in runs {
2894 if debug_pairs {
2895 eprintln!(
2896 "pair {}x{}: clip run len_pts={} length={:.4e}",
2897 first.face.id,
2898 second.face.id,
2899 run.len(),
2900 run.windows(2)
2901 .map(|pair| pair[1].sub(pair[0]).length())
2902 .sum::<f64>()
2903 );
2904 }
2905 if run.len() < 2 {
2906 continue;
2907 }
2908 let length: f64 = run
2909 .windows(2)
2910 .map(|pair| pair[1].sub(pair[0]).length())
2911 .sum();
2912 if length <= options.tolerance * 100.0 {
2913 continue;
2914 }
2915 let shared_started = profile.enabled.then(Instant::now);
2916 let follows_shared = branch_follows_shared_boundary(
2917 &run,
2918 first,
2919 second,
2920 &builder.edges,
2921 options.tolerance,
2922 builder.scale,
2923 )?;
2924 if let Some(started) = shared_started {
2925 profile.shared_boundary += started.elapsed();
2926 }
2927 if follows_shared {
2928 if debug_pairs {
2929 eprintln!(
2930 "pair {}x{}: run dropped (follows shared boundary)",
2931 first.face.id, second.face.id
2932 );
2933 }
2934 continue;
2935 }
2936 if let Some(census) = pair_census.as_mut() {
2937 census.record_stations(&run);
2938 }
2939 let pieces_before = builder.pieces.len();
2940 let chunk_points = options.fit_chunk_points.unwrap_or(run.len()).max(2);
2941 let mut start = 0;
2942 while start + 1 < run.len() {
2943 let end = (start + chunk_points - 1).min(run.len() - 1);
2944 // HERMITE EMISSION (`imprint/hermite.rs`): with the lane on
2945 // and every span of this run within the budget, the section
2946 // is the march's own cubic Hermite with its two parameter
2947 // Hermites, and the fit lane below is skipped.
2948 let hermite_started = profile.enabled.then(Instant::now);
2949 let hermite: Option<Result<super::hermite::HermiteSection, super::hermite::HermiteDecline>> = if pair_hermite_lane && end + 1 - start >= hermite_min_stations {
2950 Some(match emission_budget {
2951 Some(budget) => super::hermite::hermite_section(&run[start..=end], &branch, first_march, second_march, budget)
2952 .or_refuse(KernelStage::Intersect, "csg.imprint.driver.hermite")?,
2953 None => Err(super::hermite::HermiteDecline::NoTangents),
2954 })
2955 } else {
2956 None
2957 };
2958 if let Some(started) = hermite_started {
2959 profile.hermite += started.elapsed();
2960 }
2961 let (section_curve, exact_pcurves) = match hermite {
2962 Some(Ok(emitted)) => {
2963 super::work_profile::add(|c| { c.carried_uv_curves += 2; c.carried_uv_stations += 2 * emitted.stations as u64; });
2964 profile.hermite_runs += 1;
2965 span_census(|| {
2966 format!(
2967 "pair {}x{} budget {} branch_stations {} run_stations {} kept {} span_deviation {:.3e} tangents true route None met_requested true lane hermite inserted {}",
2968 first.face.id,
2969 second.face.id,
2970 march_span_budget.map_or("none".to_string(), |budget| format!("{budget:.3e}")),
2971 branch.points.len(),
2972 emitted.stations,
2973 emitted.stations,
2974 emitted.deviation,
2975 emitted.inserted,
2976 )
2977 });
2978 (emitted.curve, Some([emitted.pcurve_a, emitted.pcurve_b]))
2979 }
2980 other => {
2981 let hermite_decline = other.map(|lane| lane.err());
2982 profile.fit_runs += 1;
2983 let fit_started = profile.enabled.then(Instant::now);
2984 let fit_tolerance = options.tolerance.max(1e-7);
2985 let (mut section, mut fit, recovered, evening) = even_sliver_ends_measured(
2986 run[start..=end].to_vec(),
2987 &first.face.surface,
2988 &second.face.surface,
2989 options.tolerance,
2990 fit_tolerance,
2991 options.maximum_fit_points,
2992 options.local_fit,
2993 )
2994 .or_refuse(KernelStage::Intersect, "csg.imprint.driver.sliver_end")?;
2995 if evening != SliverEvening::NoSliver {
2996 if let Ok(path) = std::env::var("BREP_SECTION_SLIVER_CENSUS") {
2997 use std::io::Write;
2998 if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
2999 let _ = writeln!(file, "sliver-end census: pair {}x{} {evening:?} stations {}", first.face.id, second.face.id, section.len());
3000 }
3001 }
3002 }
3003 // A recovered fit may reproduce every march point yet
3004 // still wander off the carriers between sparse stations.
3005 // Measure it against both supports before accepting that
3006 // recovery, and use the existing bounded SSI refiner.
3007 let met_requested = fit.report.met_requested_tolerance();
3008 let refine_route = section_refine_route(
3009 section_refine_gate(),
3010 recovered,
3011 || {
3012 paired_grazing_crossings
3013 && std::env::var("BREP_GRAZE_SECTION_REFINE").as_deref() != Ok("0")
3014 },
3015 met_requested,
3016 )
3017 .or_else(|| {
3018 // `BREP_SECTION_CARRIER_MISS=0` restores the fast path
3019 // for an attribution A/B only (default on).
3020 if std::env::var("BREP_SECTION_CARRIER_MISS").as_deref() == Ok("0") {
3021 return None;
3022 }
3023 let (station_upper, midspan_upper) =
3024 fit_split_timed(FitSplitLane::CarrierReadings, || fast_path_carrier_readings(&fit, §ion, &first.face.surface, &second.face.surface));
3025 carrier_miss_route(station_upper, midspan_upper, fit_tolerance)
3026 });
3027 let mut refine_unconverged = false;
3028 let mut refine_worst = 0.0f64;
3029 if let Some((gate, route)) = refine_route {
3030 let stations_before = fit.kept.len();
3031 let refine_census = std::env::var("BREP_SECTION_REFINE_CENSUS").ok();
3032 let (census_head, census_tail) = (section[0], section[section.len() - 1]);
3033 let refine_started = refine_census.is_some().then(Instant::now);
3034 // The wrapper's own two lines, inlined so the receipt
3035 // can be read (behaviour identical to
3036 // `refine_section_against_carriers`).
3037 let representatives = std::env::var("BREP_SECTION_REPRESENTATIVES").as_deref() != Ok("0");
3038 let mut receipt = RefineReceipt::default();
3039 let (refined, worst, unrefined, rounds, exit) = refine_section_against_carriers_with(
3040 &mut section,
3041 fit,
3042 &first.face.surface,
3043 &second.face.surface,
3044 fit_tolerance,
3045 options.tolerance,
3046 options.local_fit,
3047 gate * fit_tolerance,
3048 representatives,
3049 &mut receipt,
3050 ).or_refuse(KernelStage::Intersect, "csg.imprint.driver.midspan")?;
3051 let _ = &receipt;
3052 // `BREP_SECTION_REFINE_CENSUS=<file>`: one line per section,
3053 // appended, so a corpus replay (whose children's stderr is
3054 // captured) can be read for trip counts and growth.
3055 // The route, whether the standing fit met its request, and
3056 // the refiner's own wall time close the line, so a run can
3057 // total the UNMET-REQUEST route's cost apart from the
3058 // global gate's (which reads every section).
3059 if let Some(path) = refine_census {
3060 use std::io::Write;
3061 if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
3062 let _ = writeln!(
3063 file,
3064 "section-refine census: pair {}x{} exit {:?} rounds {} stations {} -> {} unrefined {:.3e} worst {:.3e} route {:?} met_requested {} ms {:.3} head ({:.9}, {:.9}, {:.9}) tail ({:.9}, {:.9}, {:.9})",
3065 first.face.id, second.face.id, exit, rounds, stations_before, refined.kept.len(), unrefined, worst,
3066 route, met_requested, refine_started.map_or(0.0, |started| started.elapsed().as_secs_f64() * 1e3),
3067 census_head.x, census_head.y, census_head.z, census_tail.x, census_tail.y, census_tail.z
3068 );
3069 }
3070 }
3071 if debug_pairs && (rounds > 0 || !matches!(exit, MidspanExit::Converged | MidspanExit::BelowGate)) {
3072 eprintln!(
3073 "pair {}x{}: mid-span refinement {:?} after {} round(s): {} stations, worst {:.3e}",
3074 first.face.id, second.face.id, exit, rounds, section.len(), worst
3075 );
3076 }
3077 refine_unconverged = !matches!(exit, MidspanExit::Converged | MidspanExit::BelowGate);
3078 refine_worst = worst;
3079 fit = refined;
3080 }
3081 span_census(|| {
3082 format!(
3083 "pair {}x{} budget {} branch_stations {} run_stations {} kept {} span_deviation {} tangents {} route {:?} met_requested {} lane fit hermite {}",
3084 first.face.id,
3085 second.face.id,
3086 march_span_budget.map_or("none".to_string(), |budget| format!("{budget:.3e}")),
3087 branch.points.len(),
3088 section.len(),
3089 fit.kept.len(),
3090 branch.span_deviation.map_or("none".to_string(), |deviation| format!("{deviation:.3e}")),
3091 branch.tangents.is_some(),
3092 refine_route.map(|(_, route)| route),
3093 met_requested,
3094 hermite_decline.map_or("off".to_string(), |decline| decline.map_or("none".to_string(), |decline| format!("{decline:?}"))),
3095 )
3096 });
3097 // `BREP_SECTION_OVERSHOOT_CENSUS=<file>` (debug only; nothing
3098 // reads it): EVERY section's final fit, on any route, is read
3099 // against both carriers at its kept stations and at its
3100 // mid-spans, so a fit that stands further off the carriers
3101 // between its stations than at them (fixture 28 t217: 5.07e-4
3102 // shipped against a 1.32e-4 worst station) is counted, not
3103 // guessed. Projector distances are upper readings; the line
3104 // says so by its field names.
3105 {
3106 if let Ok(path) = std::env::var("BREP_SECTION_OVERSHOOT_CENSUS") {
3107 // An unreadable station makes the whole reading NaN
3108 // (f64::max would silently drop it).
3109 let read = |surface: &NurbsSurface, point: Vec3| {
3110 project_point_to_surface(surface, point).map_or(f64::NAN, |projection| projection.distance)
3111 };
3112 let mut station_worst = 0.0f64;
3113 for point in &fit.kept {
3114 let (a, b) = (read(&first.face.surface, *point), read(&second.face.surface, *point));
3115 station_worst = if a.is_nan() || b.is_nan() || station_worst.is_nan() { f64::NAN } else { station_worst.max(a).max(b) };
3116 }
3117 let (run_worst, _) = fast_path_carrier_readings(&fit, §ion, &first.face.surface, &second.face.surface);
3118 let interior_worst = knot_interior_carrier_upper(&fit.curve, &first.face.surface, &second.face.surface);
3119 let misses = midspan_misses_only(&fit, &first.face.surface, &second.face.surface).unwrap_or_default();
3120 let (worst_span, midspan_worst) = misses
3121 .iter()
3122 .copied()
3123 .enumerate()
3124 .fold((usize::MAX, 0.0f64), |best, (span, miss)| if miss > best.1 { (span, miss) } else { best });
3125 let line = format!(
3126 "section-overshoot census: pair {}x{} route {:?} kept {} spans_read {} station_upper {:.3e} midspan_upper {:.3e} worst_span {} fit_tolerance {:.1e} ratio {:.3} run {} run_upper {run_worst:.3e} knot_interior_upper {interior_worst:.3e} head ({:.9}, {:.9}, {:.9}) tail ({:.9}, {:.9}, {:.9})\n",
3127 first.face.id, second.face.id, refine_route.map(|(_, route)| route), fit.kept.len(), misses.len(), station_worst, midspan_worst,
3128 if worst_span == usize::MAX { -1 } else { worst_span as i64 }, fit_tolerance,
3129 midspan_worst / station_worst.max(fit_tolerance),
3130 section.len(),
3131 section[0].x, section[0].y, section[0].z,
3132 section[section.len() - 1].x, section[section.len() - 1].y, section[section.len() - 1].z
3133 );
3134 use std::io::Write;
3135 if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
3136 let _ = file.write_all(line.as_bytes());
3137 }
3138 }
3139 }
3140 if let Some(started) = fit_started {
3141 profile.fit += started.elapsed();
3142 }
3143 if let Some(census) = pair_census.as_mut() {
3144 census.record_fit(&fit);
3145 }
3146 // HERMITE 3-D LANE (`BREP_SECTION_HERMITE_3D`, default on;
3147 // `imprint/hermite.rs`): a fit the refiner left unconverged and
3148 // still missing a carrier by more than [`HERMITE_3D_GROSS_MISS`]
3149 // fit tolerances, or one standing further from its own polyline
3150 // between stations than half the run's longest chord (ringing,
3151 // not chord sag), is
3152 // replaced by the C1 cubic through the march stations and their
3153 // tangents, bisected onto true intersection points until every
3154 // span holds the fit tolerance on both carriers. A run the lane
3155 // cannot bring within that keeps the fit.
3156 let mut lane_pcurves = None;
3157 if super::hermite::hermite_3d_enabled() {
3158 let longest = section.windows(2).map(|pair| pair[1].sub(pair[0]).length()).fold(0.0f64, f64::max);
3159 let ringing = !(fit.report.between_stations <= 0.5 * longest);
3160 let gross = refine_unconverged && !(refine_worst <= HERMITE_3D_GROSS_MISS * fit_tolerance);
3161 if gross || ringing {
3162 let emitted = super::hermite::hermite_section_3d(
3163 &run[start..=end],
3164 &branch,
3165 &first.face.surface,
3166 &second.face.surface,
3167 fit_tolerance,
3168 )
3169 .or_refuse(KernelStage::Intersect, "csg.imprint.driver.hermite_3d")?;
3170 if debug_pairs {
3171 eprintln!(
3172 "pair {}x{}: hermite 3-D lane (gross {gross}, unconverged {refine_unconverged} worst {refine_worst:.3e}, ringing {ringing} between {:.3e} longest {longest:.3e}): {}",
3173 first.face.id,
3174 second.face.id,
3175 fit.report.between_stations,
3176 emitted.as_ref().map_or("declined".to_string(), |(curve, _)| format!("{} controls", curve.control_points.len()))
3177 );
3178 }
3179 // `BREP_HERMITE_3D_CENSUS=<file>`: one line per section the
3180 // lane is asked to take, appended (debug only).
3181 if let Ok(path) = std::env::var("BREP_HERMITE_3D_CENSUS") {
3182 use std::io::Write;
3183 if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
3184 let _ = writeln!(
3185 file,
3186 "hermite-3d census: label {} pair {}x{} gross {gross} ringing {ringing} worst {refine_worst:.3e} between {:.3e} -> {}",
3187 std::env::var("BREP_CENSUS_LABEL").unwrap_or_default(),
3188 first.face.id,
3189 second.face.id,
3190 fit.report.between_stations,
3191 emitted.as_ref().map_or("declined".to_string(), |(curve, _)| format!("{} controls", curve.control_points.len()))
3192 );
3193 }
3194 }
3195 if let Some((curve, pcurves)) = emitted {
3196 fit.curve = curve;
3197 lane_pcurves = Some(pcurves);
3198 }
3199 }
3200 }
3201 (fit.curve, lane_pcurves)
3202 }
3203 };
3204 let process_started = profile.enabled.then(Instant::now);
3205 builder.process_curve(
3206 section_curve,
3207 first,
3208 second,
3209 &[first, second],
3210 &[first, second],
3211 true,
3212 exact_pcurves,
3213 )?;
3214 if let Some(started) = process_started {
3215 profile.process += started.elapsed();
3216 }
3217 start = end;
3218 }
3219 for piece in &builder.pieces[pieces_before..] {
3220 builder.marched_pieces.insert(piece.id);
3221 }
3222 if debug_pairs {
3223 eprintln!(
3224 "pair {}x{}: run -> {} pieces",
3225 first.face.id,
3226 second.face.id,
3227 builder.pieces.len() - pieces_before
3228 );
3229 }
3230 }
3231 }
3232 profile.clip_and_fit += profile.lap(&mut lap_start);
3233 }
3234 }
3235 for (span, first, second, target) in deferred_boundary_spans {
3236 builder.process_curve(span, first, second, &[target], &[target], false, None)?;
3237 }
3238 if let Some(scope) = pairs_fits {
3239 profile.pairs_fits = scope.close().fits;
3240 }
3241 super::work_profile::faces(first_faces.iter().chain(&second_faces)
3242 .map(|face| (face.face, builder.by_face.contains_key(&face.key()))));
3243 profile.report();
3244 let hull_culls = super::builder::take_hull_culls();
3245 if profile.enabled && super::builder::hull_cull_enabled() {
3246 profile_line!("imprint.hull_culls edges={hull_culls}");
3247 }
3248 // The row counters are drained only when they are printed, so a test
3249 // reading them after a whole operation sees every call's count.
3250 if profile.enabled && super::builder::pierce_cull_enabled() {
3251 profile_line!("imprint.pierce_culls edges={}", super::builder::take_pierce_culls());
3252 }
3253 if profile.enabled {
3254 let overlap_hull_skips = super::sections::take_overlap_hull_skips();
3255 if overlap_hull_skips > 0 {
3256 profile_line!("imprint.overlap_hull_skips stations={overlap_hull_skips}");
3257 }
3258 let exchange_hull_skips = super::builder::take_exchange_hull_skips();
3259 if exchange_hull_skips > 0 {
3260 profile_line!("imprint.exchange_hull_skips answered={exchange_hull_skips}");
3261 }
3262 }
3263 // SELF-TOUCH SPLIT: a face whose loops touch at an edge interior (a hole
3264 // tangent to a fillet setback) gets a vertex minted at the touch on BOTH
3265 // edges, so the fragment arrangement's pinch resolution assembles — see
3266 // `imprint/self_touch.rs`. Escape hatch: BREP_SELF_TOUCH_SPLIT=0.
3267 let mut tail_lap: Option<Instant> = None;
3268 // Beside each stage's time, the pcurve fits it recorded (a nested
3269 // `PcurveFitScope` per stage, folded into the operation's ledger).
3270 let mut tail_fits: Option<crate::PcurveFitScope> = None;
3271 let mut tail_ms = Vec::<(&str, f64, u64)>::new();
3272 let lap = |name: &'static str,
3273 started: &mut Option<Instant>,
3274 fits: &mut Option<crate::PcurveFitScope>,
3275 tail_ms: &mut Vec<(&str, f64, u64)>| {
3276 if profile.enabled {
3277 let now = Instant::now();
3278 let recorded = fits.take().map_or(0, |scope| scope.close().fits);
3279 if let Some(previous) = *started {
3280 tail_ms.push((name, (now - previous).as_secs_f64() * 1_000.0, recorded));
3281 }
3282 *started = Some(now);
3283 *fits = Some(crate::PcurveFitScope::open());
3284 }
3285 };
3286 lap("pairs", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3287 if std::env::var("BREP_SELF_TOUCH_SPLIT").as_deref() != Ok("0") {
3288 let scans_before = super::self_touch::touch_scans();
3289 let pairs_before = super::self_touch::pair_reads();
3290 builder.split_self_touching_loops(&first_faces, &face_edge_lists, &cached_subcurve)?;
3291 builder.split_self_touching_loops(&second_faces, &face_edge_lists, &cached_subcurve)?;
3292 if profile.enabled {
3293 let pairs = super::self_touch::pair_reads();
3294 profile_line!("imprint.self_touch faces={} scanned={} pairs_served={} pairs_read={}", first_faces.len() + second_faces.len(), super::self_touch::touch_scans() - scans_before, pairs[0] - pairs_before[0], pairs[1] - pairs_before[1]);
3295 }
3296 }
3297 // PIECE-ENDPOINT EXCHANGE post-pass: with every pair's process_curve
3298 // done, the piece set is final for the ridden-edge class — imprint each
3299 // open riding piece's junction endpoints onto the ridden edges (see the
3300 // method doc; hatch BREP_OVERLAP_PIECE_ENDPOINT_SPLIT=0).
3301 builder.exchange_piece_endpoint_junctions()?;
3302 // TANGENT-SECTION IMPRINT (`ImprintOptions::tangent_curve_imprint`), after
3303 // every pair: whether a run splits a face is read against the face's trim
3304 // AND the pieces the other pairs minted on it, so the runs are minted
3305 // once the piece set is complete (the through-bore's contact ends on the
3306 // bore's cap circles, which the box's top and bottom minted).
3307 for (index, run, first, second) in std::mem::take(&mut tangent_imprint_candidates) {
3308 let closed = tangent_sections[index].closed;
3309 tangent_sections[index].piece_ids = imprint_tangent_run(
3310 &mut builder,
3311 &run,
3312 closed,
3313 first,
3314 second,
3315 &face_edge_lists,
3316 options,
3317 std::env::var("BREP_DEBUG_PAIRS").is_ok(),
3318 )?;
3319 }
3320 // TANGENT-SECTION T-JUNCTIONS (`ImprintOptions::tangent_curve_imprint`):
3321 // an imprinted contact ends on operand edges, which `process_curve` split,
3322 // and on earlier SECTIONS of the same carrier, which nothing splits — the
3323 // through-bore's contact line ends on the two cap circles the box's top
3324 // and bottom minted on the bore. Split those pieces at the contact's end
3325 // vertices so both faces of each circle carry the vertex the bore's
3326 // arrangement needs there (see `split_pieces_at_tangent_ends`).
3327 if tangent_sections.iter().any(|section| !section.piece_ids.is_empty()) {
3328 split_pieces_at_tangent_ends(
3329 &mut builder,
3330 &tangent_sections,
3331 &first_faces,
3332 &second_faces,
3333 options,
3334 std::env::var("BREP_DEBUG_PAIRS").is_ok(),
3335 )?;
3336 }
3337 lap("self_touch", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3338 let mut edge_splits = builder
3339 .edge_splits
3340 .into_iter()
3341 .map(|((operand, edge_id), mut parameters)| {
3342 parameters.sort_by(f64::total_cmp);
3343 EdgeSplitRecord {
3344 operand,
3345 edge_id,
3346 parameters,
3347 }
3348 })
3349 .collect::<Vec<_>>();
3350 edge_splits.sort_by_key(|record| (record.operand, record.edge_id));
3351 let mut by_face = builder
3352 .by_face
3353 .into_iter()
3354 .map(|(face, piece_ids)| FaceImprints {
3355 operand: face.operand,
3356 face_id: face.face_id,
3357 piece_ids,
3358 })
3359 .collect::<Vec<_>>();
3360 by_face.sort_by_key(|record| (record.operand, record.face_id));
3361 let section_evidence = section_evidence || !builder.pieces.is_empty();
3362 let marched_pieces = std::mem::take(&mut builder.marched_pieces);
3363 let mut emitted_pcurves = std::mem::take(&mut builder.emitted_pcurves);
3364 let junction_evidence = JunctionEvidence {
3365 radii: std::mem::take(&mut builder.vertex_radii),
3366 sources: std::mem::take(&mut builder.vertex_sources),
3367 };
3368 // Published for the plain two-operand loop only: a self-imprint's pairs
3369 // are within one solid and say nothing about the other operand.
3370 let faces_in_unproved_pairs = self_pairs.is_none().then(|| {
3371 let mut faces: HashSet<FaceKey> = HashSet::default();
3372 for pair in &visited_pairs {
3373 if !proved_apart_pairs.contains(pair) {
3374 faces.insert(first_faces[pair.0].key());
3375 faces.insert(second_faces[pair.1].key());
3376 }
3377 }
3378 let mut faces = faces.into_iter().collect::<Vec<_>>();
3379 faces.sort_by_key(|key| (key.operand, key.face_id));
3380 faces
3381 });
3382 let mut result = ImprintResultRecord {
3383 faces_in_unproved_pairs,
3384 tangent_nodes,
3385 tangent_sections,
3386 vertices: builder.vertices,
3387 pieces: builder.pieces,
3388 by_face,
3389 edge_splits,
3390 barrier_edges: builder.barrier_edges.into_iter().collect(),
3391 section_evidence,
3392 cosurface_pairs,
3393 };
3394 RESCUE_FIRINGS.with(|cell| cell.set((march_swap_rescues, clip_swap_rescues)));
3395 if profile.enabled {
3396 profile_line!("imprint.rescues march_swap={march_swap_rescues} clip_swap={clip_swap_rescues}");
3397 }
3398 // COINCIDENT-PIECE MERGE (and the generic one-circle-from-many-pairs
3399 // class): the SAME section curve can be minted by several pairs — a
3400 // cosurface boundary-edge copy (the cylinder cap ring lying ON the
3401 // inscribed sphere) AND the cap-plane's analytic section ring are one
3402 // circle minted twice, each carrying only its own pair's
3403 // supports/pcurves. Assembly then builds duplicate edges that cannot both
3404 // be two-use → one-use strands. Merge pieces whose curves coincide along
3405 // their whole span (bidirectional max deviation within the weld band):
3406 // keep the first, union the supports/pcurves/by_face registrations of the
3407 // rest into it. Escape hatch: BREP_COINCIDENT_PIECE_MERGE=0.
3408 lap("collect", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3409 if std::env::var("BREP_COINCIDENT_PIECE_MERGE").as_deref() != Ok("0") {
3410 let weld = assembler_weld(options.tolerance).max(options.tolerance * 10.0);
3411 // Two pieces that coincide along their WHOLE spans (deviation within
3412 // the weld both ways) also have matching end points, up to direction
3413 // and a weld or two of overhang, so a piece whose ends are nowhere
3414 // near the other's needs no 33-station projection sweep. The sweep is
3415 // what made this pass quadratic in wall time: 630 pieces cost 3.2 s
3416 // of a 3.8 s imprint on the 2026-09-12 mesh-import report, all of it
3417 // rejecting pairs an end-point look already rules out.
3418 let mut ends: Vec<[Vec3; 2]> = Vec::with_capacity(result.pieces.len());
3419 for piece in &result.pieces {
3420 let [d0, d1] = piece.curve.domain().or_refuse(KernelStage::Intersect, "domain")?;
3421 ends.push([
3422 piece.curve.evaluate(d0).or_refuse(KernelStage::Intersect, "evaluate")?,
3423 piece.curve.evaluate(d1).or_refuse(KernelStage::Intersect, "evaluate")?,
3424 ]);
3425 }
3426 let end_band = 4.0 * weld;
3427 // CONTROL-HULL CULL (2026-10-10): the plate minus 36 cylinders mints 72
3428 // CLOSED rings, every one of which took the full sweep against every other —
3429 // 2 556 pairs, 230 of the imprint's 288 ms — although rings 16 units apart
3430 // cannot coincide. A NURBS curve lies in the convex hull of its control
3431 // points, so two curves within `weld` of each other along their whole spans
3432 // have control boxes that overlap once each is grown by `weld`; a pair whose
3433 // boxes do not is skipped before any projection. Exact, so the merged set is
3434 // the one the sweep alone found. `BREP_COINCIDENT_MERGE_BOX=0` restores the
3435 // unculled sweep for a before/after reading.
3436 let box_cull = std::env::var("BREP_COINCIDENT_MERGE_BOX").as_deref() != Ok("0");
3437 let mut boxes: Vec<[Vec3; 2]> = Vec::with_capacity(result.pieces.len());
3438 for piece in &result.pieces {
3439 boxes.push(control_hull_box(&piece.curve, weld));
3440 }
3441 // A CLOSED piece (a full ring) has no end points to speak of: two
3442 // rings of the same circle seamed at different azimuths coincide
3443 // along their whole spans while their domain ends sit anywhere on
3444 // the ring, so a closed piece always takes the full sweep.
3445 let ends_match = |a: &[Vec3; 2], b: &[Vec3; 2]| -> bool {
3446 let near = |p: Vec3, q: Vec3| p.sub(q).length() <= end_band;
3447 near(a[0], a[1])
3448 || near(b[0], b[1])
3449 || (near(a[0], b[0]) && near(a[1], b[1]))
3450 || (near(a[0], b[1]) && near(a[1], b[0]))
3451 };
3452 let mut removed: Vec<u64> = Vec::new();
3453 let mut index = 0;
3454 while index < result.pieces.len() {
3455 let mut other = index + 1;
3456 while other < result.pieces.len() {
3457 let coincide = (!box_cull || boxes_overlap(&boxes[index], &boxes[other]))
3458 && ends_match(&ends[index], &ends[other])
3459 && {
3460 let a = &result.pieces[index];
3461 let b = &result.pieces[other];
3462 // FEATURE SCALE B2 (`BREP_FEATURE_SCALE_IMPRINT`):
3463 // the weld (1e-6) equals the hairline slot's width,
3464 // so the two walls' pieces read as one; beside a
3465 // feature the weld is capped at a quarter of it.
3466 let weld = if tail_feature_scale.is_empty() {
3467 weld
3468 } else {
3469 tail_feature_scale.cap(ends[index][0], weld).min(tail_feature_scale.cap(ends[index][1], weld))
3470 };
3471 max_curve_deviation(&a.curve, &b.curve)? <= weld
3472 && max_curve_deviation(&b.curve, &a.curve)? <= weld
3473 };
3474 if coincide {
3475 let absorbed = result.pieces.remove(other);
3476 ends.remove(other);
3477 boxes.remove(other);
3478 removed.push(absorbed.id);
3479 let keeper = &mut result.pieces[index];
3480 for pcurve in absorbed.pcurves {
3481 if !keeper
3482 .pcurves
3483 .iter()
3484 .any(|existing| {
3485 existing.operand == pcurve.operand
3486 && existing.face_id == pcurve.face_id
3487 })
3488 {
3489 let key = FaceKey { operand: pcurve.operand, face_id: pcurve.face_id };
3490 if emitted_pcurves.remove(&(absorbed.id, key)) {
3491 emitted_pcurves.insert((keeper.id, key));
3492 }
3493 keeper.pcurves.push(pcurve);
3494 }
3495 }
3496 let keeper_id = keeper.id;
3497 for record in &mut result.by_face {
3498 if let Some(position) =
3499 record.piece_ids.iter().position(|&id| id == absorbed.id)
3500 {
3501 if record.piece_ids.contains(&keeper_id) {
3502 record.piece_ids.remove(position);
3503 } else {
3504 record.piece_ids[position] = keeper_id;
3505 }
3506 }
3507 }
3508 } else {
3509 other += 1;
3510 }
3511 }
3512 index += 1;
3513 }
3514 if !removed.is_empty() && std::env::var("BREP_DEBUG_BOOL").is_ok() {
3515 eprintln!("coincident-piece merge: absorbed {:?}", removed);
3516 }
3517 }
3518 // Rescue near-tangent SSI truncations BEFORE canonicalization so the added
3519 // bridge pieces' endpoints (existing crossing/stub vertices) fold into the
3520 // same junction merges as every other section.
3521 lap("coincident_merge", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3522 extend_truncated_sections(
3523 &mut result,
3524 &face_edge_lists,
3525 solid_a,
3526 solid_b,
3527 &charts,
3528 options.tolerance,
3529 )?;
3530 lap("extend_truncated", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3531 canonicalize_imprint_junctions(
3532 &mut result,
3533 solid_a,
3534 solid_b,
3535 &charts,
3536 options.tolerance,
3537 &emitted_pcurves,
3538 &junction_evidence,
3539 junction_combine_mode(options),
3540 &tail_feature_scale,
3541 // The composite one-call carrier imprint keeps the per-pair contract:
3542 // no residual-evidence vertex merge across its admitted pairs (see
3543 // the parameter doc on `canonicalize_imprint_junctions`).
3544 self_pairs.is_none(),
3545 )?;
3546 lap("canonicalize", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3547 // ONE RIM, ONE EDGE: with vertex identity final, dissolve the section
3548 // vertices that no operand edge passes through — the marcher's own
3549 // parameterization origin, which `process_curve` cannot tell from a
3550 // junction because it sees one pair at a time. See the method doc.
3551 let dissolved = dissolve_section_origin_vertices(
3552 &mut result,
3553 &marched_pieces,
3554 solid_a,
3555 solid_b,
3556 &charts,
3557 options.tolerance,
3558 )?;
3559 if dissolved > 0 && std::env::var("BREP_DEBUG_BOOL").is_ok() {
3560 eprintln!("origin-dissolve: {dissolved} parameterization vertex/vertices removed");
3561 }
3562 lap("origin_dissolve", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3563 // B2: reuse an existing boundary edge as the shared section edge wherever a
3564 // section coincides with one along its whole span (vertices are final after
3565 // canonicalization; `face_edge_lists` holds each face's boundary edges on
3566 // the healed operands). Runs here so both operands reference ONE edge.
3567 reuse_boundary_section_edges(
3568 &mut result,
3569 &face_edge_lists,
3570 solid_a,
3571 solid_b,
3572 options.tolerance,
3573 )?;
3574 // Capstone step 1 — instrumentation only, zero behavior change: report
3575 // every (section piece × boundary edge) contact where the piece runs
3576 // within the scale-derived band of the edge over a real span. Measuring
3577 // the bands here first validates the graze-contact model on the
3578 // acceptance suite before step 2's common-block machinery replaces a
3579 // grazed overlap with a shared edge.
3580 lap("reuse_boundary", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3581 report_graze_contacts(&result, &face_edge_lists, solid_a, solid_b, options.tolerance)?;
3582 if profile.enabled {
3583 if let Some(scope) = tail_fits.take() {
3584 scope.close();
3585 }
3586 let line = tail_ms
3587 .iter()
3588 .map(|(name, ms, _)| format!("{name}={ms:.2}"))
3589 .collect::<Vec<_>>()
3590 .join(" ");
3591 profile_line!("imprint.stages {line}");
3592 let split = imprint_split_take();
3593 let ms = |d: Duration| d.as_secs_f64() * 1_000.0;
3594 profile_line!(
3595 "imprint.split pierce={:.3} pierce_edges={} overlap={:.3} overlap_edges={} crossing={:.3} crossing_edges={} recover={:.3} recover_pierces={} lies_whole={:.3} lies_whole_calls={} lies_whole_hits={} lies_span={:.3} lies_span_calls={} reuse_edges={}",
3596 ms(split.pierce), split.pierce_edges, ms(split.overlap), split.overlap_edges, ms(split.crossing), split.crossing_edges,
3597 ms(split.recover), split.recover_pierces, ms(split.lies_whole), split.lies_whole_calls, split.lies_whole_hits,
3598 ms(split.lies_span), split.lies_span_calls, split.reuse_edges,
3599 );
3600 let fits = tail_ms
3601 .iter()
3602 .map(|(name, _, fits)| format!("{name}={fits}"))
3603 .collect::<Vec<_>>()
3604 .join(" ");
3605 profile_line!("imprint.stage_fits {fits}");
3606 }
3607 if let Ok(path) = std::env::var("BREP_IMPRINT_SECTION_CENSUS") {
3608 use std::io::Write;
3609 // A private observation of the complete imprint, including section
3610 // curves, pcurves and junctions. Canonicalize only the set-valued
3611 // barrier list on a COPY; leave every returned record untouched.
3612 let mut observed = result.clone();
3613 observed.barrier_edges.sort_unstable();
3614 let bytes = serde_json::to_vec(&observed).expect("serialize imprint census");
3615 let digest = bytes.iter().fold(0xcbf29ce484222325_u64,
3616 |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3));
3617 let mut file = std::fs::OpenOptions::new().create(true).append(true).open(path)
3618 .expect("open imprint section census");
3619 writeln!(file, "imprint.sections digest={digest:016x} bytes={} pieces={} vertices={}",
3620 bytes.len(), observed.pieces.len(), observed.vertices.len()).expect("append imprint section census");
3621 }
3622 Ok(result)
3623}
3624
3625/// Debug-only graze-contact survey (`BREP_DEBUG_GRAZE=1`): for each section
3626/// piece and each boundary edge of its support faces, sample the piece and
3627/// measure distance to the edge; report contacts whose in-band span exceeds
3628/// both the weld scale and 4× the minimum deviation (span-wise proximity, not
3629/// a point touch). `band_cap` reuses the residual-merge `sep_cap` ceiling —
3630/// measured, never grown. The output is the raw material for capstone step 2
3631/// (partial-span common-block): which contacts exist, their spans, and their
3632/// measured bands.
3633fn report_graze_contacts(
3634 result: &ImprintResultRecord,
3635 face_edge_lists: &HashMap<FaceKey, Vec<&EdgeRecord>>,
3636 solid_a: &BrepSolid,
3637 solid_b: &BrepSolid,
3638 tolerance: f64,
3639) -> Result<(), KernelRefusal> {
3640 if std::env::var("BREP_DEBUG_GRAZE").as_deref() != Ok("1") {
3641 return Ok(());
3642 }
3643 let raw_extent = raw_solid_extent(solid_a).max(raw_solid_extent(solid_b));
3644 let (_, band_cap) = residual_merge_bands(raw_extent, tolerance);
3645 const SAMPLES: usize = 17;
3646 for piece in &result.pieces {
3647 let [t0, t1] = [piece.t0, piece.t1];
3648 if !(t1 > t0) {
3649 continue;
3650 }
3651 for key in piece.support_faces {
3652 let Some(edges) = face_edge_lists.get(&key) else {
3653 continue;
3654 };
3655 for edge in edges {
3656 if edge.degenerate {
3657 continue;
3658 }
3659 let mut in_band = 0usize;
3660 let mut min_dev = f64::INFINITY;
3661 let mut max_dev_in_band = 0.0f64;
3662 let mut span = 0.0f64;
3663 let mut prev: Option<(bool, Vec3)> = None;
3664 for k in 0..SAMPLES {
3665 let t = t0 + (t1 - t0) * k as f64 / (SAMPLES - 1) as f64;
3666 let point = piece.curve.evaluate(t).or_refuse(KernelStage::Intersect, "evaluate")?;
3667 let deviation = project_point_to_curve(&edge.curve, point).or_refuse(KernelStage::Intersect, "project_point_to_curve")?.distance;
3668 min_dev = min_dev.min(deviation);
3669 let inside = deviation <= band_cap;
3670 if inside {
3671 in_band += 1;
3672 max_dev_in_band = max_dev_in_band.max(deviation);
3673 if let Some((true, prev_point)) = prev {
3674 span += point.sub(prev_point).length();
3675 }
3676 }
3677 prev = Some((inside, point));
3678 }
3679 // Span-wise contact: several consecutive samples in band and a
3680 // span that dwarfs the closest-approach (not a transversal
3681 // crossing, which dips in and out at one sample).
3682 if in_band >= 3 && span > (4.0 * min_dev).max(assembler_weld(tolerance)) {
3683 eprintln!(
3684 "graze: piece {} sup=[{}:{},{}:{}] ~ edge {}:{} span={:.3e} band=[{:.3e},{:.3e}] samples_in_band={}/{}",
3685 piece.id,
3686 piece.support_faces[0].operand,
3687 piece.support_faces[0].face_id,
3688 piece.support_faces[1].operand,
3689 piece.support_faces[1].face_id,
3690 key.operand,
3691 edge.id,
3692 span,
3693 min_dev,
3694 max_dev_in_band,
3695 in_band,
3696 SAMPLES
3697 );
3698 }
3699 }
3700 }
3701 }
3702 Ok(())
3703}
3704
3705/// `BREP_RIM_BRIDGE` (default on, `=0` off): see RIM BRIDGE in the pair loop.
3706fn rim_bridge_enabled() -> bool {
3707 crate::switch!("BREP_RIM_BRIDGE", true)
3708}
3709
3710/// The rim pierces of a tangential-only pair, bridged (see RIM BRIDGE in the
3711/// pair loop): every edge of each face that CROSSES the other carrier at a
3712/// grazing angle (`|tan·n|` under the seed gate) inside both trims, and for
3713/// each pierce of the first operand whose nearest pierce of the second is
3714/// mutually nearest, farther apart than the assembler weld and within
3715/// `4 tol / |tan·n|` (capped at 1e-3), the segment between them is imprinted.
3716#[allow(clippy::too_many_arguments)]
3717fn rim_bridge(
3718 builder: &mut ImprintBuilder<'_>,
3719 first: TaggedFace<'_>,
3720 second: TaggedFace<'_>,
3721 first_march: &NurbsSurface,
3722 second_march: &NurbsSurface,
3723 face_edge_lists: &HashMap<FaceKey, Vec<&EdgeRecord>>,
3724 options: &ImprintOptions,
3725 debug_pairs: bool,
3726) -> Result<(), KernelRefusal> {
3727 let mut pierces: [Vec<(Vec3, f64)>; 2] = [Vec::new(), Vec::new()];
3728 for (side, (face, other, other_march)) in [(first, second, second_march), (second, first, first_march)].into_iter().enumerate() {
3729 let edges = &face_edge_lists[&face.key()];
3730 for edge in edges {
3731 if edge.degenerate {
3732 continue;
3733 }
3734 // An edge lying ON the other carrier (the rims along the join the
3735 // pair is tangent across) reads a grazing hit per sample and
3736 // crosses nowhere: skip its solve, as the seed loop does.
3737 if super::support::curve_lies_on_surface(&edge_subcurve(edge)?, other_march, options.tolerance)? {
3738 continue;
3739 }
3740 for hit in intersect_curve_surface(&edge.curve, other_march, options.tolerance).or_refuse(KernelStage::Intersect, "intersect_curve_surface")? {
3741 if hit.t <= edge.t0 || hit.t >= edge.t1 {
3742 continue;
3743 }
3744 let Ok(tangent) = edge.curve.derivatives(hit.t, 1).or_refuse(KernelStage::Intersect, "derivatives")?[1].normalized() else {
3745 continue;
3746 };
3747 let Ok(normal) = other.chart().normal(hit.u, hit.v) else {
3748 continue;
3749 };
3750 let tangency = tangent.dot(normal).abs();
3751 if !(tangency > 0.0 && tangency < 0.1) {
3752 continue;
3753 }
3754 if !edge_crosses_carrier(edge, edges, hit.t, other_march, options.tolerance)? {
3755 continue;
3756 }
3757 if !inside_both_trims(hit.point, first, second)? {
3758 continue;
3759 }
3760 pierces[side].push((hit.point, tangency));
3761 }
3762 }
3763 }
3764 let nearest = |point: Vec3, among: &[(Vec3, f64)]| -> Option<(Vec3, f64)> {
3765 among.iter().copied().min_by(|a, b| a.0.sub(point).length().total_cmp(&b.0.sub(point).length()))
3766 };
3767 let weld = assembler_weld(options.tolerance);
3768 for &(from, from_tangency) in &pierces[0] {
3769 let Some((to, to_tangency)) = nearest(from, &pierces[1]) else {
3770 continue;
3771 };
3772 let mutual = nearest(to, &pierces[0]).is_some_and(|(back, _)| back.sub(from).length() <= options.tolerance);
3773 let gap = from.sub(to).length();
3774 let reach = (4.0 * options.tolerance / from_tangency.min(to_tangency)).min(1e-3);
3775 if debug_pairs {
3776 eprintln!(
3777 "pair {}x{}: rim bridge candidate ({:.7},{:.7},{:.7}) -> ({:.7},{:.7},{:.7}) gap {gap:.3e} reach {reach:.3e} mutual {mutual}",
3778 first.face.id, second.face.id, from.x, from.y, from.z, to.x, to.y, to.z
3779 );
3780 }
3781 if !mutual || gap <= weld || gap > reach {
3782 continue;
3783 }
3784 let segment = crate::make_line(from, to).or_refuse(KernelStage::Intersect, "make_line")?;
3785 builder.process_curve(segment, first, second, &[first, second], &[first, second], true, None)?;
3786 }
3787 Ok(())
3788}
3789
3790/// `BREP_PIERCE_NEAR_END_STEP` (default on, `=0` off): [`edge_crosses_carrier`] reads
3791/// a hit within its step of an open edge's end with the step shortened to it.
3792fn pierce_near_end_step_enabled() -> bool {
3793 crate::switch!("BREP_PIERCE_NEAR_END_STEP", true)
3794}
3795
3796/// Does `edge` CROSS `carrier` at parameter `t` — leave one side of the
3797/// surface for the other — rather than touch it or lie on it? Read from the
3798/// signed distance of the edge to the carrier a step either side of `t`
3799/// (one hundredth of the edge's live window): a crossing changes sign with
3800/// both readings clear of the tolerance; a lies-on edge reads zero on both
3801/// sides and a kiss reads one sign on both. A hit at the edge's end has no
3802/// far side and is not a crossing, UNLESS the face's boundary continues the
3803/// same curve there: `siblings` are the face's edges, and one that carries
3804/// this edge's curve bit for bit over the adjoining parameter window is the
3805/// other half of an edge a vertex was put on (`apply_edge_splits` keeps the
3806/// parent curve and narrows the window). The live window is then the whole
3807/// chain's, so the step and both readings are the ones the unsplit edge
3808/// gave. Fixture 31's union on its own split operands: pad edge 2 pierces
3809/// the model's blend at 0.0525 rad inside both trims, the imprint had put a
3810/// vertex at that very pierce, both halves then read "at the end", the
3811/// sub-gate march never started and the section it imprints on the unsplit
3812/// operands was missing (4 open edges). The signed distance is read against the
3813/// carrier itself (projection), never against the tangent plane at the hit,
3814/// where a curve lying ON a curved carrier would read a same-signed sagitta
3815/// on both sides that outweighs a grazing crossing's first-order departure.
3816/// A CLOSED edge (a cap's rim circle) has no end: a hit within a step of its
3817/// seam reads its far side across the seam (the G1 elbow's arm cap pierces
3818/// the lower torus half at t = 0.0037 of its rim circle).
3819/// A grazing pierce of `edge` near one of its end vertices that is the vertex
3820/// touching `carrier`, not a crossing (`BREP_IMPRINT_NEAR_END_SNAP`): the end
3821/// lies on the carrier and the edge from the pierce to it stays within the
3822/// overlap floor of it, inside the tangency band where a touch reads as a dip
3823/// through the carrier and back (a sweep's top edge leaving a disk's rim at the
3824/// sweep's end corner pierced the tool's wall 1.5e-3 from the corner and set
3825/// off a march along the contact). The end must be a true vertex of an open
3826/// edge lying on the carrier, and the stretch is certified over its whole
3827/// length ([`super::support::span_hull_within_surface`]), not sampled.
3828fn pierce_is_end_contact(edge: &EdgeRecord, t: f64, point: Vec3, carrier: &NurbsSurface, tolerance: f64) -> Result<bool, KernelRefusal> {
3829 let floor = tolerance.max(1e-5);
3830 let reach = 256.0 * floor;
3831 let (start, end) = (
3832 edge.curve.evaluate(edge.t0).or_refuse(KernelStage::Intersect, "evaluate")?,
3833 edge.curve.evaluate(edge.t1).or_refuse(KernelStage::Intersect, "evaluate")?,
3834 );
3835 // A closed edge's seam is no vertex the edge touches anything at.
3836 if edge.degenerate || start.sub(end).length() <= floor {
3837 return Ok(false);
3838 }
3839 for (parameter, end_point) in [(edge.t0, start), (edge.t1, end)] {
3840 if parameter == t || end_point.sub(point).length() > reach {
3841 continue;
3842 }
3843 // The end itself lies on the carrier, as the corner a touch is at does.
3844 let on = project_point_to_surface(carrier, end_point).or_refuse(KernelStage::Intersect, "project_point_to_surface")?;
3845 if !(on.distance <= tolerance * 10.0) {
3846 continue;
3847 }
3848 let mut budget = super::support::hug_budget();
3849 if super::support::span_hull_within_surface(&edge.curve, t.min(parameter), t.max(parameter), carrier, floor, &mut budget)? {
3850 return Ok(true);
3851 }
3852 }
3853 Ok(false)
3854}
3855
3856fn edge_crosses_carrier(
3857 edge: &EdgeRecord,
3858 siblings: &[&EdgeRecord],
3859 t: f64,
3860 carrier: &NurbsSurface,
3861 tolerance: f64,
3862) -> Result<bool, KernelRefusal> {
3863 if !(edge.t1 - edge.t0 > 0.0) {
3864 return Ok(false);
3865 }
3866 let (t0, t1) = same_curve_chain_window(edge, siblings);
3867 let window = t1 - t0;
3868 let mut delta = window * 1e-2;
3869 // A hit inside the step of an open edge's end is read with the step
3870 // halved to the end (`BREP_PIERCE_NEAR_END_STEP`): the readings must still
3871 // clear the band either side, so a hit at the end vertex itself is no
3872 // crossing, while one a short real distance in from it is.
3873 if pierce_near_end_step_enabled() && t > t0 && t < t1 {
3874 let (start, end) = (
3875 edge.curve.evaluate(t0).or_refuse(KernelStage::Intersect, "evaluate")?,
3876 edge.curve.evaluate(t1).or_refuse(KernelStage::Intersect, "evaluate")?,
3877 );
3878 if start.sub(end).length() > tolerance {
3879 delta = delta.min(0.5 * (t - t0)).min(0.5 * (t1 - t));
3880 }
3881 }
3882 let (mut before, mut after) = (t - delta, t + delta);
3883 if before < t0 || after > t1 {
3884 let start = edge.curve.evaluate(t0).or_refuse(KernelStage::Intersect, "evaluate")?;
3885 let end = edge.curve.evaluate(t1).or_refuse(KernelStage::Intersect, "evaluate")?;
3886 if start.sub(end).length() > tolerance {
3887 return Ok(false);
3888 }
3889 if before < t0 {
3890 before += window;
3891 }
3892 if after > t1 {
3893 after -= window;
3894 }
3895 }
3896 let mut readings = [0.0f64; 2];
3897 for (slot, parameter) in [before, after].into_iter().enumerate() {
3898 let point = edge.curve.evaluate(parameter).or_refuse(KernelStage::Intersect, "evaluate")?;
3899 let projection = project_point_to_surface(carrier, point).or_refuse(KernelStage::Intersect, "project_point_to_surface")?;
3900 let normal = match carrier.normal(projection.u, projection.v) {
3901 Ok(normal) => normal,
3902 Err(_) => return Ok(false),
3903 };
3904 readings[slot] = point.sub(projection.point).dot(normal);
3905 }
3906 let clear = tolerance * 10.0;
3907 Ok(readings[0] * readings[1] < 0.0 && readings[0].abs() > clear && readings[1].abs() > clear)
3908}
3909
3910/// The parameter window of the chain of `siblings` that continue `edge`'s own
3911/// curve: edges with a bit-identical curve whose windows adjoin end to start.
3912/// `edge`'s own window when nothing continues it.
3913fn same_curve_chain_window(edge: &EdgeRecord, siblings: &[&EdgeRecord]) -> (f64, f64) {
3914 let same_curve = |other: &EdgeRecord| other.id != edge.id && !other.degenerate && same_curve_bits(&other.curve, &edge.curve);
3915 let halves: Vec<&&EdgeRecord> = siblings.iter().filter(|other| same_curve(other)).collect();
3916 let (mut t0, mut t1) = (edge.t0, edge.t1);
3917 for _ in 0..halves.len() {
3918 let mut grew = false;
3919 for other in &halves {
3920 if other.t1 == t0 && other.t0 < t0 {
3921 t0 = other.t0;
3922 grew = true;
3923 } else if other.t0 == t1 && other.t1 > t1 {
3924 t1 = other.t1;
3925 grew = true;
3926 }
3927 }
3928 if !grew {
3929 break;
3930 }
3931 }
3932 (t0, t1)
3933}
3934
3935/// `BREP_IMPRINT_LIES_ON_SEED_SKIP=0` runs the seed solve on an edge that lies
3936/// on the other carrier as before (see the seed loop); unset or anything else
3937/// skips it. Read once.
3938fn lies_on_seed_skip_enabled() -> bool {
3939 switch!("BREP_IMPRINT_LIES_ON_SEED_SKIP", true)
3940}
3941
3942/// TANGENT-RIM LANDING (hosted report 2026-10-17, "boolean fails": a box
3943/// with a bore, its top face revolved 25° about a top edge and subtracted).
3944///
3945/// The revolve turns the profile's hole into a torus whose start rim IS the
3946/// bore's top rim, so the bore cylinder and the torus are tangent along that
3947/// whole circle — a shared TRIM EDGE of both faces, not an interior contact —
3948/// and inside the trims they cross along two transverse branches that leave
3949/// the rim at the two points where the torus's revolution-direction curvature
3950/// vanishes against the cylinder's. The classifier admits those as isolated
3951/// nodes (`tangent_contact.rs`: a third-order cusp reads as a saddle at every
3952/// stopping rule) and the branch is marched — but the marcher's step direction
3953/// `n_a × n_b` collapses as it nears the node, so the trace STALLS a few 1e-5
3954/// short of the rim instead of running past the trim with its usual slack.
3955/// Measured: the run ends 6.95e-5 and 1.17e-4 below y = 20, which on the
3956/// cylinder's 30-tall chart is 2.3e-6 and 3.9e-6 — just over the arrangement's
3957/// 1.4e-6 band — so the cut never reaches the boundary, the cylinder face is
3958/// not split, and six edges stand one-use (the torus faces, whose pcurve is
3959/// clamped at the rim's domain wall, DID split there, which is the asymmetry
3960/// the one-use count reads). The exact `A − B` is a manifold solid (two
3961/// slivers of box material inside the torus tube pinching to a zero-dihedral
3962/// edge along the rim), so the refusal was wrong, not the model.
3963///
3964/// A transverse section cannot end strictly inside both trims; a run end that
3965/// stops within the on-boundary clearance (`polish_endpoint`'s band) of a trim
3966/// edge which lies on BOTH carriers at the foot of that stop has merely been
3967/// truncated, and the foot — on the edge, hence on both carriers exactly — is
3968/// where the exact section continues to. Land the end there and split the
3969/// edge at it, so the ordinary machinery (pcurve projection, the arrangement's
3970/// boundary split, the assembler's vertex weld) takes the junction from here.
3971/// Reach: pairs carrying an admitted tangent node (the only place the march
3972/// stalls short — elsewhere it overshoots the trim), a foot within
3973/// `1e-2·(1 + |foot|)` of that node, and an end not already on the edge. The
3974/// moved sample is the run's own last station, so the section polyline keeps
3975/// every marched point and the landing segment is at most the clearance long.
3976/// Returns the splits to register, one per edge sharing the landing point:
3977/// `(operand, edge id, parameter, from, to)`.
3978///
3979/// Without an admitted node (`node` is `None`: the pair was marched from
3980/// sub-gate pierces, or its branch simply ran into a tangency — the −10°
3981/// sibling of the revolve-into-bore report, a near-tangent pair with no node
3982/// admitted whose ordinary march stalled 4e-5 and 2.4e-4 short of its rim),
3983/// the certificate is the run end itself: it must sit where the carriers are
3984/// TANGENT (`|n_a × n_b|` under the seed gate), which is the only place a
3985/// march stalls short. With or without a node the reach is `1e-2 (1 +
3986/// |point|)`, and a gap beyond the plain clearance is earned sample by
3987/// sample: the straight landing segment must stay within the on-boundary
3988/// clearance of BOTH carriers at every sample — a section through a tangency
3989/// band is within tolerance of both carriers all the way to the rim, so a
3990/// segment that leaves either is not the missing stretch (the −20° sibling's
3991/// 7x6 end stops 3e-4 short, over the plain clearance of 2.1e-4). A gap
3992/// within the plain clearance lands exactly as before.
3993fn land_run_ends_on_tangent_rim(
3994 run: &mut [Vec3],
3995 node: Option<Vec3>,
3996 first: TaggedFace<'_>,
3997 second: TaggedFace<'_>,
3998 face_edge_lists: &HashMap<FaceKey, Vec<&EdgeRecord>>,
3999 tolerance: f64,
4000) -> Result<Vec<(u8, u64, f64, Vec3, Vec3)>, KernelRefusal> {
4001 let mut landings = Vec::new();
4002 if run.len() < 2 || std::env::var("BREP_TANGENT_RIM_LANDING").as_deref() == Ok("0") {
4003 return Ok(landings);
4004 }
4005 for index in [0, run.len() - 1] {
4006 let point = run[index];
4007 let clearance = (tolerance * 100.0).max(1e-6) * (1.0 + point.length());
4008 // No node: the end must stand in the tangency band, and the reach
4009 // beyond the plain clearance is earned sample by sample below.
4010 let stalled = match node {
4011 Some(_) => true,
4012 None => pair_normals_parallel_at(first, second, point)?,
4013 };
4014 if !stalled {
4015 continue;
4016 }
4017 let reach = 1e-2 * (1.0 + point.length());
4018 // Every qualifying foot over both faces' trim edges; the nearest is
4019 // where the end lands, and every edge whose foot coincides with it
4020 // (the two operands' copies of the shared rim) is split there, so
4021 // neither side depends on its pcurve happening to clamp at a domain
4022 // wall for its vertex.
4023 let mut feet: Vec<(f64, u8, u64, f64, Vec3)> = Vec::new();
4024 for face in [first, second] {
4025 let Some(edges) = face_edge_lists.get(&face.key()) else {
4026 continue;
4027 };
4028 for edge in edges {
4029 if edge.degenerate {
4030 continue;
4031 }
4032 let projection = project_point_to_curve(&edge.curve, point)
4033 .or_refuse(KernelStage::Intersect, "project_point_to_curve")?;
4034 let parameter = projection.u.clamp(edge.t0.min(edge.t1), edge.t0.max(edge.t1));
4035 let foot = edge.curve.evaluate(parameter).or_refuse(KernelStage::Intersect, "evaluate")?;
4036 let gap = foot.sub(point).length();
4037 if gap <= tolerance || gap > reach {
4038 continue;
4039 }
4040 if let Some(node) = node {
4041 if foot.sub(node).length() > 1e-2 * (1.0 + foot.length()) {
4042 continue;
4043 }
4044 }
4045 if gap > clearance
4046 && !landing_segment_within(&first.face.surface, &second.face.surface, point, foot, clearance)
4047 {
4048 continue;
4049 }
4050 // The edge must ride BOTH carriers at the foot: that is what
4051 // makes the foot a point of the section.
4052 let on_both = [first, second].iter().all(|face| {
4053 project_point_to_surface(&face.face.surface, foot)
4054 .map(|projection| projection.distance <= clearance)
4055 .unwrap_or(false)
4056 });
4057 if !on_both {
4058 continue;
4059 }
4060 feet.push((gap, face.operand, edge.id, parameter, foot));
4061 }
4062 }
4063 let Some(&(_, _, _, _, landing)) = feet.iter().min_by(|a, b| a.0.total_cmp(&b.0)) else {
4064 continue;
4065 };
4066 for (_, operand, edge_id, parameter, foot) in feet {
4067 if foot.sub(landing).length() <= tolerance * 10.0 {
4068 landings.push((operand, edge_id, parameter, point, landing));
4069 }
4070 }
4071 run[index] = landing;
4072 }
4073 Ok(landings)
4074}
4075/// TANGENT-NODE LANDING (hosted report 2026-11-01, "Boolean fails": a NURBS
4076/// Solid BOX cage, 10³ with 8 segments and 3 rings, unioned with a radius-5
4077/// cylinder standing on `y = 0`).
4078///
4079/// Three collinear cage points per side make the body flat to second order at
4080/// each side midpoint, and the cylinder's bottom rim passes through all four:
4081/// the two carriers touch at four isolated higher-order NODES that lie ON a
4082/// trim edge. Two section branches leave each node, mutually tangent there
4083/// (`z = ±c·y^{3/2}` on the wall). The march cannot place a station near such
4084/// a node: across the contact the carriers separate only as `δ² κ / 2`, so at
4085/// the model tolerance a station is uncertain by `√(2·tol/κ)` along the rim
4086/// (`1e-3` here). Measured: the four arcs ended ON the rim but 1.4e-5..2e-4
4087/// along it from their nodes, so each node's two arrivals split the rim twice
4088/// and left `On` slivers between, and the arcs into the node on the cylinder's
4089/// seam wobbled ACROSS the seam at `y ≈ 1.3e-3` (the true branch touches the
4090/// seam only at the node), leaving seam-hugging slivers. Six open corners and
4091/// a torn shell; [`land_run_ends_on_tangent_rim`] does not reach it because
4092/// those ends are already on the edge — they stopped at the wrong place ALONG
4093/// it, not short of it.
4094///
4095/// So: a run end where the carriers are tangent is refined onto its contact
4096/// (`classify_tangent_contact`); when that contact is an isolated node within
4097/// the landing reach that lies on a trim edge of either face, the stations
4098/// inside the node's ambiguity radius `3·√(2·tol/κ)` are dropped — they carry
4099/// no position the march could resolve — and the end is the node itself,
4100/// provided the closing chord stays on both carriers
4101/// ([`landing_segment_within`]). Every edge through the node is split exactly
4102/// there, so both branches arriving at a node share one vertex. Returns the
4103/// splits as [`land_run_ends_on_tangent_rim`] does.
4104fn land_run_ends_on_tangent_node(
4105 run: &mut Vec<Vec3>,
4106 first: TaggedFace<'_>,
4107 second: TaggedFace<'_>,
4108 face_edge_lists: &HashMap<FaceKey, Vec<&EdgeRecord>>,
4109 tolerance: f64,
4110) -> Result<Vec<(u8, u64, f64, Vec3, Vec3)>, KernelRefusal> {
4111 let mut landings = Vec::new();
4112 if run.len() < 2 || std::env::var("BREP_TANGENT_NODE_LANDING").as_deref() == Ok("0") {
4113 return Ok(landings);
4114 }
4115 for at_end in [false, true] {
4116 let end = if at_end { run[run.len() - 1] } else { run[0] };
4117 if !pair_normals_parallel_at(first, second, end)? {
4118 continue;
4119 }
4120 let reach = 1e-2 * (1.0 + end.length());
4121 let Some(contact) =
4122 classify_tangent_contact(&first.face.surface, &second.face.surface, end, tolerance)?
4123 else {
4124 continue;
4125 };
4126 let node = contact.point;
4127 if !contact.is_isolated_node() || node.sub(end).length() > reach || contact.curvature_scale <= 0.0 {
4128 continue;
4129 }
4130 let clearance = (tolerance * 100.0).max(1e-6) * (1.0 + node.length());
4131 // Every trim edge of either face the node lies on.
4132 let mut splits: Vec<(u8, u64, f64)> = Vec::new();
4133 for face in [first, second] {
4134 let Some(edges) = face_edge_lists.get(&face.key()) else {
4135 continue;
4136 };
4137 for edge in edges {
4138 if edge.degenerate {
4139 continue;
4140 }
4141 let projection = project_point_to_curve(&edge.curve, node)
4142 .or_refuse(KernelStage::Intersect, "project_point_to_curve")?;
4143 let parameter = projection.u.clamp(edge.t0.min(edge.t1), edge.t0.max(edge.t1));
4144 let foot = edge.curve.evaluate(parameter).or_refuse(KernelStage::Intersect, "evaluate")?;
4145 if foot.sub(node).length() <= tolerance * 10.0
4146 && !splits.iter().any(|&(operand, id, _)| operand == face.operand && id == edge.id)
4147 {
4148 splits.push((face.operand, edge.id, parameter));
4149 }
4150 }
4151 }
4152 if splits.is_empty() {
4153 continue;
4154 }
4155 // The ambiguity radius: the stations inside it are noise along the
4156 // contact and are dropped outright. Beyond it, keep dropping while
4157 // the closing chord to the node still rides both carriers to ten
4158 // times the tolerance: near the node the branch is TANGENT to the
4159 // contact direction (on the seam node, to the seam itself), so its
4160 // true offset from that direction grows only as `r^{3/2}` and a
4161 // station must be far enough out for that offset to dominate the
4162 // corrector's noise — or the fitted piece wobbles across the seam.
4163 let ambiguity = 3.0 * (2.0 * tolerance / contact.curvature_scale).sqrt();
4164 let tight = tolerance * 10.0;
4165 let mut kept: Vec<Vec3> = if at_end { run.clone() } else { run.iter().rev().copied().collect() };
4166 while kept.len() > 1 && kept[kept.len() - 1].sub(node).length() <= ambiguity {
4167 kept.pop();
4168 }
4169 let last = kept[kept.len() - 1];
4170 if last.sub(node).length() > reach
4171 || !landing_segment_within(&first.face.surface, &second.face.surface, last, node, clearance)
4172 {
4173 continue;
4174 }
4175 while kept.len() > 2 {
4176 let further = kept[kept.len() - 2];
4177 if further.sub(node).length() > reach
4178 || !landing_segment_within(&first.face.surface, &second.face.surface, further, node, tight)
4179 {
4180 break;
4181 }
4182 kept.pop();
4183 }
4184 kept.push(node);
4185 if !at_end {
4186 kept.reverse();
4187 }
4188 *run = kept;
4189 for (operand, edge_id, parameter) in splits {
4190 landings.push((operand, edge_id, parameter, end, node));
4191 }
4192 }
4193 Ok(landings)
4194}
4195
4196/// The widened landing's certificate: is the straight segment from the
4197/// stalled run end `from` to the foot `to` within `clearance` of BOTH
4198/// carriers at every interior sample?
4199///
4200/// Why this is a construction guarantee and not a reading: the foot is on a
4201/// trim edge that rides both carriers (checked by the caller), so it is a
4202/// point of the carriers' intersection set to within the clearance. The run
4203/// end is a marched station, on both carriers to the corrector's residual.
4204/// A segment whose every sample is within the clearance of both carriers is
4205/// a chord of the band where the two carriers are within tolerance of each
4206/// other — exactly the set a section through a tangency is confined to —
4207/// and the section polyline's last chord is held to the same deviation every
4208/// marched chord is. A segment that leaves either carrier mid-way (a chord
4209/// across a curved rim: its sagitta clears the clearance by orders) is NOT
4210/// the missing stretch, whatever its ends read, and is refused here.
4211fn landing_segment_within(
4212 first: &NurbsSurface,
4213 second: &NurbsSurface,
4214 from: Vec3,
4215 to: Vec3,
4216 clearance: f64,
4217) -> bool {
4218 const SAMPLES: usize = 8;
4219 (1..SAMPLES).all(|k| {
4220 let sample = from.add(to.sub(from).scale(k as f64 / SAMPLES as f64));
4221 [first, second].iter().all(|surface| {
4222 project_point_to_surface(surface, sample)
4223 .map(|projection| projection.distance <= clearance)
4224 .unwrap_or(false)
4225 })
4226 })
4227}
4228
4229/// Are the two carriers TANGENT (normals parallel) where they both pass through
4230/// `point`?
4231///
4232/// The test the tangential-only refusal above needs: a point on the marched
4233/// intersection is a TANGENT NODE when the two surface normals there are
4234/// parallel. The threshold is the transversality bound the supplemental
4235/// detector already accepts seeds by (`TRANSVERSE_SEED_CROSS`), not the far
4236/// tighter pair-classifier bound — a node the march merely passes CLOSE to
4237/// still poisons the assembly, so this errs toward calling a pair singular.
4238/// The tangent-curve lane's recognition of one pair: find the pair's
4239/// tangential contact without a witness, keep only an EXTENDED one (a node or
4240/// a point contact is the existing paths' business), and with one planar
4241/// carrier march it along the null direction of `II_a − II_b` and clip the
4242/// curve to both trims. `None` when there is no extended contact, or its trace
4243/// has no run inside both trims (a contact on the carriers' extensions
4244/// imprints nothing, exactly as today).
4245///
4246/// The section is RECORDED, not imprinted: a tangent edge whose two sides
4247/// both survive is a four-coedge incidence the assembler cannot represent
4248/// (the pinch gate in `csg/boolean/mod.rs` names the subtract case), and a
4249/// tangent edge only one side of which survives dissolves into its face.
4250/// What the record buys is the boolean's attribution: a refusal whose faces
4251/// the contact involves names the contact instead of the arrangement's own
4252/// symptom. The involved faces are the two carriers' and every face sharing
4253/// an edge a run end lies on (`TangentSectionRecord::faces`).
4254#[allow(clippy::too_many_arguments)]
4255fn tangent_curve_section(
4256 first: TaggedFace<'_>,
4257 second: TaggedFace<'_>,
4258 options: &ImprintOptions,
4259 first_faces: &[TaggedFace<'_>],
4260 second_faces: &[TaggedFace<'_>],
4261 face_edge_lists: &HashMap<FaceKey, Vec<&EdgeRecord>>,
4262 debug_pairs: bool,
4263) -> Result<Option<(TangentSectionRecord, Vec<Vec3>)>, KernelRefusal> {
4264 let _clock = ImprintSubphaseClock::new("tangent_section");
4265 let Some(contact) =
4266 crate::find_tangent_contact(&first.face.surface, &second.face.surface, options.tolerance)
4267 .or_refuse(KernelStage::Intersect, "find_tangent_contact")?
4268 else {
4269 return Ok(None);
4270 };
4271 if debug_pairs {
4272 eprintln!(
4273 "pair {}x{}: tangent-curve lane contact {:?}",
4274 first.face.id, second.face.id, contact
4275 );
4276 }
4277 if !contact.is_extended() {
4278 return Ok(None);
4279 }
4280 let is_plane = |face: TaggedFace<'_>| {
4281 matches!(face.face.surface.analytic(), Some(crate::AnalyticSurface::Plane { .. }))
4282 };
4283 let planar = is_plane(first) || is_plane(second);
4284 if !planar {
4285 // The curved/curved branch: recognised and named, not traced.
4286 return Ok(Some((
4287 TangentSectionRecord {
4288 first: first.key(),
4289 second: second.key(),
4290 start: contact.point,
4291 end: contact.point,
4292 length: 0.0,
4293 closed: false,
4294 stations: 0,
4295 planar: false,
4296 faces: vec![first.key(), second.key()],
4297 piece_ids: Vec::new(),
4298 grazing: Vec::new(),
4299 },
4300 Vec::new(),
4301 )));
4302 }
4303 let Some(curve) = crate::trace_tangent_curve(
4304 &first.face.surface,
4305 &second.face.surface,
4306 &contact,
4307 &SurfaceIntersectionOptions {
4308 tolerance: options.tolerance,
4309 maximum_step: options.maximum_ssi_step,
4310 ..Default::default()
4311 },
4312 )
4313 .or_refuse(KernelStage::Intersect, "trace_tangent_curve")?
4314 else {
4315 return Ok(None);
4316 };
4317 let mut longest: Option<Vec<Vec3>> = None;
4318 let mut longest_length = 0.0f64;
4319 for run in clip_branch_to_trims(&curve.points, first, second)? {
4320 if run.len() < 2 {
4321 continue;
4322 }
4323 let length: f64 = run.windows(2).map(|pair| pair[1].sub(pair[0]).length()).sum();
4324 if length > longest_length {
4325 longest_length = length;
4326 longest = Some(run);
4327 }
4328 }
4329 let Some(run) = longest else {
4330 return Ok(None);
4331 };
4332 if longest_length <= options.tolerance * 100.0 {
4333 return Ok(None);
4334 }
4335 if debug_pairs {
4336 eprintln!(
4337 "pair {}x{}: tangent-curve lane traced {} stations, run of {} inside both trims, length {:.6}, closed {}",
4338 first.face.id, second.face.id, curve.points.len(), run.len(), longest_length, curve.closed
4339 );
4340 }
4341 let closed = curve.closed && run.len() == curve.points.len();
4342 // The faces the contact involves: the carriers' own, and across every
4343 // edge of theirs that a run end lies on, the faces sharing that edge.
4344 let mut faces = vec![first.key(), second.key()];
4345 if !closed {
4346 let band = options.tolerance * 100.0;
4347 for end in [run[0], run[run.len() - 1]] {
4348 for face in [first, second] {
4349 let Some(edges) = face_edge_lists.get(&face.key()) else {
4350 continue;
4351 };
4352 for edge in edges {
4353 if edge.degenerate {
4354 continue;
4355 }
4356 let Ok(projection) = project_point_to_curve(&edge.curve, end) else {
4357 continue;
4358 };
4359 if projection.distance > band {
4360 continue;
4361 }
4362 let siblings = if face.operand == first.operand { first_faces } else { second_faces };
4363 for sibling in siblings {
4364 let shares = sibling
4365 .face
4366 .loops
4367 .iter()
4368 .flat_map(|loop_record| &loop_record.coedges)
4369 .any(|coedge| coedge.edge_id == edge.id);
4370 if shares && !faces.contains(&sibling.key()) {
4371 faces.push(sibling.key());
4372 }
4373 }
4374 }
4375 }
4376 }
4377 }
4378 if debug_pairs {
4379 eprintln!(
4380 "pair {}x{}: tangent-curve lane involves faces {:?}",
4381 first.face.id, second.face.id, faces
4382 );
4383 }
4384 Ok(Some((
4385 TangentSectionRecord {
4386 first: first.key(),
4387 second: second.key(),
4388 start: run[0],
4389 end: run[run.len() - 1],
4390 length: longest_length,
4391 closed,
4392 stations: run.len(),
4393 planar: true,
4394 faces,
4395 piece_ids: Vec::new(),
4396 grazing: Vec::new(),
4397 },
4398 run,
4399 )))
4400}
4401
4402/// Imprint a traced tangent run ([`ImprintOptions::tangent_curve_imprint`]):
4403/// the run's stations become a section curve — the exact line through its
4404/// ends when they are collinear (a plane's contact with a cylinder or cone is
4405/// a generatrix), the marched lane's polyline fit otherwise (a torus parallel)
4406/// — and `process_curve` mints it on both carriers exactly as it mints a
4407/// transverse section: pieces with pcurves on each face, the operand edges the
4408/// ends lie on split there. Returns the ids of the pieces minted, in order.
4409///
4410/// Only a run that SPLITS both faces is minted: a closed run, or one each of
4411/// whose ends lies, on each carrier, on that face's trim or on a section
4412/// piece already minted on it (the through-bore's contact ends on the wall's
4413/// top and bottom edges and, on the bore, on the circles the box's top and
4414/// bottom cut there). A run with an end inside a face — the blind pocket's
4415/// contact ends on the bore's cap rings but inside the wall, where both of
4416/// its sides are one face — would be a slit, and a slit is not a boundary:
4417/// measured with the slit minted, the wall's four edges came out one-use and
4418/// the pocket refused `NonIntegralGenus`. Such a contact stays recorded only,
4419/// as before.
4420#[allow(clippy::too_many_arguments)]
4421fn imprint_tangent_run(
4422 builder: &mut ImprintBuilder<'_>,
4423 run: &[Vec3],
4424 closed: bool,
4425 first: TaggedFace<'_>,
4426 second: TaggedFace<'_>,
4427 face_edge_lists: &HashMap<FaceKey, Vec<&EdgeRecord>>,
4428 options: &ImprintOptions,
4429 debug: bool,
4430) -> Result<Vec<u64>, KernelRefusal> {
4431 if run.len() < 2 {
4432 return Ok(Vec::new());
4433 }
4434 if !closed {
4435 let band = options.tolerance * 100.0;
4436 let within = |curve: &NurbsCurve, t0: f64, t1: f64, point: Vec3| -> bool {
4437 project_point_to_curve(curve, point)
4438 .map(|projection| {
4439 projection.distance <= band
4440 && projection.u >= t0.min(t1) - 1e-9
4441 && projection.u <= t0.max(t1) + 1e-9
4442 })
4443 .unwrap_or(false)
4444 };
4445 let on_boundary = |face: TaggedFace<'_>, point: Vec3| -> bool {
4446 let on_trim = face_edge_lists
4447 .get(&face.key())
4448 .map(|edges| {
4449 edges
4450 .iter()
4451 .any(|edge| !edge.degenerate && within(&edge.curve, edge.t0, edge.t1, point))
4452 })
4453 .unwrap_or(false);
4454 on_trim
4455 || builder
4456 .pieces
4457 .iter()
4458 .any(|piece| piece.support_faces.contains(&face.key()) && within(&piece.curve, piece.t0, piece.t1, point))
4459 };
4460 let ends = [run[0], run[run.len() - 1]];
4461 for face in [first, second] {
4462 if !ends.iter().all(|end| on_boundary(face, *end)) {
4463 if debug {
4464 eprintln!(
4465 "pair {}x{}: tangent-curve lane run not imprinted: an end lies inside face {}:{}'s trim (a slit)",
4466 first.face.id, second.face.id, face.operand, face.face.id
4467 );
4468 }
4469 return Ok(Vec::new());
4470 }
4471 }
4472 }
4473 let start = run[0];
4474 let end = run[run.len() - 1];
4475 let chord = end.sub(start);
4476 let chord_length = chord.length();
4477 let fit_tolerance = options.tolerance.max(1e-7);
4478 let collinear = chord_length > fit_tolerance && {
4479 let direction = chord.scale(1.0 / chord_length);
4480 run.iter().all(|station| {
4481 let offset = station.sub(start);
4482 offset.sub(direction.scale(offset.dot(direction))).length() <= 10.0 * fit_tolerance
4483 })
4484 };
4485 let curve = if collinear {
4486 crate::make_line(start, end).or_refuse(KernelStage::Intersect, "make_line")?
4487 } else {
4488 fit_polyline_of_degree(
4489 run,
4490 fit_tolerance,
4491 run.len().min(MAX_FIT_STATIONS),
4492 options.local_fit,
4493 section_fit_degree(),
4494 )
4495 .or_refuse(KernelStage::Intersect, "fit_polyline_of_degree")?
4496 .curve
4497 };
4498 let before = builder.pieces.len();
4499 builder.process_curve(curve, first, second, &[first, second], &[first, second], true, None)?;
4500 let ids: Vec<u64> = builder.pieces[before..].iter().map(|piece| piece.id).collect();
4501 if debug {
4502 eprintln!(
4503 "pair {}x{}: tangent-curve lane imprinted the run as {} ({} piece(s) {:?})",
4504 first.face.id,
4505 second.face.id,
4506 if collinear { "a line" } else { "a fitted section" },
4507 ids.len(),
4508 ids
4509 );
4510 }
4511 Ok(ids)
4512}
4513
4514/// Split every piece an imprinted tangent section ENDS ON, at that end
4515/// (`ImprintOptions::tangent_curve_imprint`). A tangent run is clipped to both
4516/// trims, so its ends lie on operand edges — split by `process_curve` — or on
4517/// the trim of the OTHER carrier's neighbours, where they also lie on the
4518/// sections those neighbours minted on this carrier: the through-bore's
4519/// contact line ends on the circles the box's top and bottom cut on the bore,
4520/// at a point no edge pierce put a vertex on (the box edge grazes the bore
4521/// there, and a grazing pierce is deliberately not a junction). Without the
4522/// vertex, the bore's arrangement would split the circle where the line
4523/// meets it while the cap's arrangement keeps the circle whole — one closed
4524/// edge against two arcs, one-use at assembly. The piece is split here, at
4525/// the imprint, so every face it is minted on sees the vertex: the halves
4526/// take the tangent end's vertex id, the pcurves are split with the curve
4527/// where they were emitted on its knots and rebuilt on the face's chart
4528/// otherwise, and the piece's face lists and lane sets follow the halves. A
4529/// piece that resolves to an operand edge (`shared_edge`) is left as it is:
4530/// that edge's own split is the exchange pass's.
4531fn split_pieces_at_tangent_ends(
4532 builder: &mut ImprintBuilder<'_>,
4533 sections: &[TangentSectionRecord],
4534 first_faces: &[TaggedFace<'_>],
4535 second_faces: &[TaggedFace<'_>],
4536 options: &ImprintOptions,
4537 debug: bool,
4538) -> Result<(), KernelRefusal> {
4539 let tangent_ids: HashSet<u64> = sections.iter().flat_map(|section| section.piece_ids.iter().copied()).collect();
4540 if tangent_ids.is_empty() {
4541 return Ok(());
4542 }
4543 let overlap_limit = options.tolerance.max(1e-5);
4544 let vertex_points: HashMap<u64, Vec3> =
4545 builder.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
4546 // (end vertex, its point, the tangent piece's supports)
4547 let mut ends: Vec<(u64, Vec3, [FaceKey; 2])> = Vec::new();
4548 for piece in builder.pieces.iter().filter(|piece| tangent_ids.contains(&piece.id)) {
4549 for vertex_id in [piece.start_vertex_id, piece.end_vertex_id] {
4550 if let Some(point) = vertex_points.get(&vertex_id) {
4551 if !ends.iter().any(|(id, _, _)| *id == vertex_id) {
4552 ends.push((vertex_id, *point, piece.support_faces));
4553 }
4554 }
4555 }
4556 }
4557 let face_of = |key: FaceKey| {
4558 first_faces
4559 .iter()
4560 .chain(second_faces)
4561 .copied()
4562 .find(|face| face.key() == key)
4563 };
4564 let mut index = 0;
4565 while index < builder.pieces.len() {
4566 let piece = &builder.pieces[index];
4567 if tangent_ids.contains(&piece.id) || piece.shared_edge.is_some() || !(piece.t1 > piece.t0) {
4568 index += 1;
4569 continue;
4570 }
4571 let mut split: Option<(u64, f64, Vec3)> = None;
4572 for (vertex_id, point, supports) in &ends {
4573 if *vertex_id == piece.start_vertex_id || *vertex_id == piece.end_vertex_id {
4574 continue;
4575 }
4576 if !supports.iter().any(|support| piece.support_faces.contains(support)) {
4577 continue;
4578 }
4579 let projection = project_point_to_curve(&piece.curve, *point)
4580 .or_refuse(KernelStage::Intersect, "project_point_to_curve")?;
4581 if projection.distance > overlap_limit {
4582 continue;
4583 }
4584 let span = piece.t1 - piece.t0;
4585 let margin = (span * KNOT_IDENTITY_TOL).max(2e-9);
4586 if projection.u <= piece.t0 + margin || projection.u >= piece.t1 - margin {
4587 continue;
4588 }
4589 // Interior in PARAMETER but at an END in space: a closed piece's
4590 // origin seen from the far side of its domain.
4591 if projection.point.sub(vertex_points[&piece.start_vertex_id]).length() <= overlap_limit
4592 || projection.point.sub(vertex_points[&piece.end_vertex_id]).length() <= overlap_limit
4593 {
4594 continue;
4595 }
4596 split = Some((*vertex_id, projection.u, *point));
4597 break;
4598 }
4599 let Some((vertex_id, parameter, point)) = split else {
4600 index += 1;
4601 continue;
4602 };
4603 let piece = builder.pieces.remove(index);
4604 let (left, right) = piece.curve.split(parameter).or_refuse(KernelStage::Intersect, "split")?;
4605 let [left_t0, _] = left.domain().or_refuse(KernelStage::Intersect, "domain")?;
4606 let [_, right_t1] = right.domain().or_refuse(KernelStage::Intersect, "domain")?;
4607 let start_point = vertex_points[&piece.start_vertex_id];
4608 let end_point = vertex_points[&piece.end_vertex_id];
4609 let left = snap_curve_ends(&left, start_point, point)?;
4610 let right = snap_curve_ends(&right, point, end_point)?;
4611 let left_id = builder.next_id;
4612 let right_id = builder.next_id + 1;
4613 builder.next_id += 2;
4614 let mut left_pcurves = Vec::with_capacity(piece.pcurves.len());
4615 let mut right_pcurves = Vec::with_capacity(piece.pcurves.len());
4616 for face_pcurve in &piece.pcurves {
4617 let key = FaceKey { operand: face_pcurve.operand, face_id: face_pcurve.face_id };
4618 let emitted = builder.emitted_pcurves.remove(&(piece.id, key));
4619 let halves = if emitted {
4620 match face_pcurve.pcurve.split(parameter) {
4621 Ok((a, b)) => {
4622 builder.emitted_pcurves.insert((left_id, key));
4623 builder.emitted_pcurves.insert((right_id, key));
4624 Some((a, b))
4625 }
4626 Err(_) => None,
4627 }
4628 } else {
4629 None
4630 };
4631 let (a, b) = match halves {
4632 Some(halves) => halves,
4633 None => {
4634 let Some(face) = face_of(key) else {
4635 return Err(KernelRefusal::internal(
4636 KernelStage::Intersect,
4637 "imprint.tangent_split",
4638 format!("tangent-section split: piece {} has a pcurve on an unknown face {key:?}", piece.id),
4639 ));
4640 };
4641 (
4642 build_pcurve_on_surface_marched(face.chart(), &left)
4643 .or_refuse(KernelStage::Intersect, "build_pcurve_on_surface_marched")?,
4644 build_pcurve_on_surface_marched(face.chart(), &right)
4645 .or_refuse(KernelStage::Intersect, "build_pcurve_on_surface_marched")?,
4646 )
4647 }
4648 };
4649 left_pcurves.push(FacePcurve { operand: key.operand, face_id: key.face_id, pcurve: a });
4650 right_pcurves.push(FacePcurve { operand: key.operand, face_id: key.face_id, pcurve: b });
4651 }
4652 if builder.marched_pieces.remove(&piece.id) {
4653 builder.marched_pieces.insert(left_id);
4654 builder.marched_pieces.insert(right_id);
4655 }
4656 for ids in builder.by_face.values_mut() {
4657 if let Some(slot) = ids.iter().position(|id| *id == piece.id) {
4658 ids[slot] = left_id;
4659 ids.insert(slot + 1, right_id);
4660 }
4661 }
4662 if debug {
4663 eprintln!(
4664 "tangent-curve lane: piece {} split at vertex {} (t={parameter:.6}) into pieces {left_id} and {right_id}",
4665 piece.id, vertex_id
4666 );
4667 }
4668 builder.pieces.insert(
4669 index,
4670 ImprintPieceRecord {
4671 id: left_id,
4672 curve: left,
4673 t0: left_t0,
4674 t1: parameter,
4675 start_vertex_id: piece.start_vertex_id,
4676 end_vertex_id: vertex_id,
4677 pcurves: left_pcurves,
4678 support_faces: piece.support_faces,
4679 shared_edge: None,
4680 },
4681 );
4682 builder.pieces.insert(
4683 index + 1,
4684 ImprintPieceRecord {
4685 id: right_id,
4686 curve: right,
4687 t0: parameter,
4688 t1: right_t1,
4689 start_vertex_id: vertex_id,
4690 end_vertex_id: piece.end_vertex_id,
4691 pcurves: right_pcurves,
4692 support_faces: piece.support_faces,
4693 shared_edge: None,
4694 },
4695 );
4696 // Re-examine the halves: a run may end on the same piece twice.
4697 }
4698 Ok(())
4699}
4700
4701/// Past the first tangency witness of `clipped` (judged by the caller), every
4702/// other stretch of the runs where the pair's normals are parallel is judged
4703/// once, at its first point: an isolated node or a tangency off its carrier
4704/// is admitted; anything else (an extended or an unproven contact) is not
4705/// (`BREP_IMPRINT_TANGENCY_OFF_CARRIER`).
4706fn every_other_tangency_admitted(
4707 first: TaggedFace<'_>,
4708 second: TaggedFace<'_>,
4709 clipped: &[Vec<Vec3>],
4710 tolerance: f64,
4711) -> Result<bool, KernelRefusal> {
4712 later_parallel_stretch_starts_all(
4713 clipped,
4714 |point| pair_normals_parallel_at(first, second, point),
4715 |point| {
4716 Ok(match classify_tangent_contact(&first.face.surface, &second.face.surface, point, tolerance)? {
4717 Some(contact) => contact.is_isolated_node(),
4718 None => super::tangent_contact::tangency_runs_off_carrier(&first.face.surface, &second.face.surface, point, tolerance)?,
4719 })
4720 },
4721 )
4722}
4723
4724/// Walk `runs` and hand `admit` the first point of every stretch of
4725/// consecutive `parallel` points past the first such stretch (the caller's
4726/// witness), in order, as each is found; `false` at the first one `admit`
4727/// rejects, before any later point is read (so a later point's failure never
4728/// takes precedence over an earlier verdict). A stretch ends where a point is
4729/// not parallel or its run ends.
4730pub(super) fn later_parallel_stretch_starts_all(
4731 runs: &[Vec<Vec3>],
4732 mut parallel: impl FnMut(Vec3) -> Result<bool, KernelRefusal>,
4733 mut admit: impl FnMut(Vec3) -> Result<bool, KernelRefusal>,
4734) -> Result<bool, KernelRefusal> {
4735 let mut first_stretch = true;
4736 for run in runs {
4737 let mut inside_stretch = false;
4738 for &point in run {
4739 let is_parallel = parallel(point)?;
4740 if is_parallel && !inside_stretch {
4741 if first_stretch {
4742 first_stretch = false;
4743 } else if !admit(point)? {
4744 return Ok(false);
4745 }
4746 }
4747 inside_stretch = is_parallel;
4748 }
4749 }
4750 Ok(true)
4751}
4752
4753fn pair_normals_parallel_at(
4754 first: TaggedFace<'_>,
4755 second: TaggedFace<'_>,
4756 point: Vec3,
4757) -> Result<bool, KernelRefusal> {
4758 let mut normals = [Vec3::default(); 2];
4759 for (slot, face) in normals.iter_mut().zip([first, second]) {
4760 let projection = project_point_to_surface(&face.face.surface, point)
4761 .or_refuse(KernelStage::Intersect, "project_point_to_surface")?;
4762 let Ok(normal) = face.face.surface.normal(projection.u, projection.v) else {
4763 // A pole/singular parameter point cannot witness transversality;
4764 // treat it as tangential so the pair stays refused.
4765 return Ok(true);
4766 };
4767 *slot = normal;
4768 }
4769 Ok(normals[0].cross(normals[1]).length() <= crate::TRANSVERSE_SEED_CROSS)
4770}
4771
4772
4773
4774/// Two exact analytic carriers on one axis (or one centre) whose surfaces are
4775/// apart everywhere by more than `band`: concentric spheres of different
4776/// radii; coaxial tori in one plane whose tubes are nested or clear of each
4777/// other (their centre circles `|R1 - R2|` apart against the tube radii);
4778/// coaxial cylinders of different radii. A PROOF, read only by the boolean's
4779/// scoped acceptance (`ImprintResultRecord::faces_in_unproved_pairs`).
4780fn concentric_carriers_apart(first: &NurbsSurface, second: &NurbsSurface, band: f64) -> bool {
4781 use crate::AnalyticSurface as A;
4782 let (Some(a), Some(b)) = (first.analytic(), second.analytic()) else {
4783 return false;
4784 };
4785 let same_point = |p: Vec3, q: Vec3| p.sub(q).length() <= band * 1e-3;
4786 // The axes are one line over the carriers' whole EXTENT: an angle moves
4787 // the far end of a long carrier by the angle times its size (cross
4788 // review: two 1e7-long cylinders 5e-13 rad apart cross).
4789 let extent = match (crate::Aabb::from_surface_controls(first), crate::Aabb::from_surface_controls(second)) {
4790 (Ok(a), Ok(b)) => a.diagonal().max(b.diagonal()),
4791 _ => return false,
4792 };
4793 if !(extent.is_finite() && extent > 0.0) {
4794 return false;
4795 }
4796 let same_axis = |fa: &crate::RevolutionFrame, fb: &crate::RevolutionFrame| {
4797 fa.axis.cross(fb.axis).length() * extent <= band * 1e-3
4798 };
4799 // The second frame's origin on the first frame's axis line.
4800 let on_axis = |fa: &crate::RevolutionFrame, fb: &crate::RevolutionFrame| {
4801 let offset = fb.origin.sub(fa.origin);
4802 offset.sub(fa.axis.scale(offset.dot(fa.axis))).length() <= band * 1e-3
4803 };
4804 match (a, b) {
4805 (A::Sphere { frame: fa, radius: ra }, A::Sphere { frame: fb, radius: rb }) => {
4806 same_point(fa.origin, fb.origin) && (ra - rb).abs() > band
4807 }
4808 (A::Torus { frame: fa, major_radius: big_a, minor_radius: small_a }, A::Torus { frame: fb, major_radius: big_b, minor_radius: small_b }) => {
4809 if !(same_axis(fa, fb) && same_point(fa.origin, fb.origin)) {
4810 return false;
4811 }
4812 let apart = (big_a - big_b).abs();
4813 let (small, large) = (small_a.min(*small_b), small_a.max(*small_b));
4814 apart + small < large - band || apart > small_a + small_b + band
4815 }
4816 (A::RuledRevolution { frame: fa, rho0: a0, rho1: a1, .. }, A::RuledRevolution { frame: fb, rho0: b0, rho1: b1, .. }) => {
4817 (a0 - a1).abs() <= band * 1e-3
4818 && (b0 - b1).abs() <= band * 1e-3
4819 && same_axis(fa, fb)
4820 && on_axis(fa, fb)
4821 && (a0 - b0).abs() > band
4822 }
4823 _ => false,
4824 }
4825}