BREP_boolean 0.30.0

Rust B-rep CAD kernel (next.BREP.io): booleans and healing: imprint, fragment, boolean assembly, sewing and face merging.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
use crate::curve::interior_knot_count;
use crate::{KernelRefusal, KernelStage, OrRefuse};
use super::*;

pub(super) fn subcurve_by_fraction(
    curve: &NurbsCurve,
    start_fraction: f64,
    end_fraction: f64,
) -> Result<NurbsCurve, KernelRefusal> {
    let [start, end] = curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
    let first = start + (end - start) * start_fraction;
    let second = start + (end - start) * end_fraction;
    // NurbsCurve::split refuses parameters within its ABSOLUTE knot
    // tolerance (1e-9) of the domain ends; the skip epsilon must cover that
    // or a near-edge trim parameter slips past the guard and errors.
    let epsilon = (1e-9 * (end - start)).max(2e-9);
    let mut result = curve.clone();
    if first > start + epsilon && first < end - epsilon {
        result = result.split(first).or_refuse(KernelStage::Fragment, "split")?.1;
    }
    let domain = result.domain().or_refuse(KernelStage::Fragment, "domain")?;
    if second < domain[1] - epsilon && second > domain[0] + epsilon {
        result = result.split(second).or_refuse(KernelStage::Fragment, "split")?.0;
    } else if env_read!("BREP_DEBUG_SUBRANGE").is_some() && second < domain[1] - epsilon {
        eprintln!("abnormal subrange skip in fragment subcurve");
    }
    Ok(result)
}

pub(super) fn trimmed_curve(curve: &NurbsCurve, t0: f64, t1: f64) -> Result<NurbsCurve, KernelRefusal> {
    let [start, end] = curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
    let span = end - start;
    if span <= 0.0 {
        return Err(KernelRefusal::internal(KernelStage::Fragment, "fragment.sampling", "fragment_face: invalid edge curve domain"));
    }
    subcurve_by_fraction(curve, (t0 - start) / span, (t1 - start) / span)
}

fn curve_is_rational(curve: &NurbsCurve) -> bool {
    curve
        .control_points
        .iter()
        .any(|control| (control.w - 1.0).abs() > 1e-12)
}


pub(super) fn sample_chain(curve: &NurbsCurve) -> Result<Vec<Vec2>, KernelRefusal> {
    let [start, end] = curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
    let straight = curve.degree == 1 && !curve_is_rational(curve);
    let spans = interior_knot_count(&curve.knots, curve.degree) + 1;
    let count = if straight {
        1
    } else {
        96usize.min(16usize.max(spans * 8))
    };
    (0..=count)
        .map(|index| {
            let point = curve.evaluate(start + (end - start) * index as f64 / count as f64).or_refuse(KernelStage::Fragment, "evaluate")?;
            Ok(Vec2 {
                x: point.x,
                y: point.y,
            })
        })
        .collect()
}

/// A boundary chain's uniform sampling, DOUBLED until every chord's midpoint
/// stays within `bound` of the pcurve, or `cap` samples are reached (hosted
/// report 2026-11-02 "boolean fails", the shelf pin's foot cut): the pin's
/// 0.01-wide cap ring is bounded by two concentric circles that
/// [`sample_chain`] drew at 24 and 32 chords, sagging 0.02 and 0.0115 — more
/// than the ring is wide — so the two polygons crossed each other all the way
/// round and the arrangement that was to cut the ring in two at the foot's
/// floor read one region. Uniform in parameter, so `refine_near_hints` can
/// still take the result. Escape hatch `BREP_BOUNDARY_SAG_SAMPLING=0|off`
/// restores the fixed count.
pub(super) fn sample_boundary_chain(curve: &NurbsCurve, bound: f64, cap: usize) -> Result<Vec<Vec2>, KernelRefusal> {
    let points = sample_chain(curve)?;
    if !boundary_sag_sampling_enabled() || points.len() < 3 || !(bound > 0.0) || !bound.is_finite() {
        return Ok(points);
    }
    let [start, end] = curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
    let mut count = points.len() - 1;
    let mut points = points;
    loop {
        let mut worst = 0.0f64;
        for index in 0..count {
            let a = points[index];
            let b = points[index + 1];
            let parameter = start + (end - start) * (index as f64 + 0.5) / count as f64;
            let mid = curve.evaluate(parameter).or_refuse(KernelStage::Fragment, "evaluate")?;
            let mid = Vec2 { x: mid.x, y: mid.y };
            let chord = b.sub(a);
            let length = chord.length();
            let sag = if length > 0.0 {
                let t = mid.sub(a).dot(chord) / (length * length);
                mid.sub(a.add(chord.scale(t.clamp(0.0, 1.0)))).length()
            } else {
                mid.sub(a).length()
            };
            worst = worst.max(sag);
        }
        if worst <= bound || count * 2 > cap {
            return Ok(points);
        }
        count *= 2;
        points = (0..=count)
            .map(|index| {
                let point = curve.evaluate(start + (end - start) * index as f64 / count as f64).or_refuse(KernelStage::Fragment, "evaluate")?;
                Ok(Vec2 { x: point.x, y: point.y })
            })
            .collect::<Result<Vec<_>, KernelRefusal>>()?;
    }
}

fn boundary_sag_sampling_enabled() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| !matches!(std::env::var("BREP_BOUNDARY_SAG_SAMPLING").as_deref(), Ok("0") | Ok("off")))
}

/// Deterministic midpoint-bisection refinement of a cut chain's uniform
/// sampling until every chord stays within `bound` of the true pcurve (the
/// arrangement tolerance — a polyline within it cannot invent crossings the
/// arrangement would distinguish). Probes each segment at the 1/4, 1/2 and
/// 3/4 parameters (the off-centre probes catch S-shaped folds whose midpoint
/// happens to sit on the chord) and inserts the segment midpoint while any
/// probe exceeds the bound. Purely additive sampling of the SAME curve —
/// no point is moved, merged or snapped — capped defensively (best-effort:
/// hitting the cap leaves the chain no worse than the unrefined sampling).
/// Escape hatch: BREP_CHAIN_SAG_REFINE=0 restores the raw uniform sampling.
/// Turning it off costs three known outcomes, not one: boolean `fixture_21`,
/// plus corpus rows `AnotherOffsetShellProblem2` and `BadBoolean` (both
/// `success` -> `refused` in the offset shell's watertight close), measured by
/// the 2026-09-16 coarseness census.
///
/// Returns the refined points plus a parallel flag vector marking which points
/// belong to the ORIGINAL sampling (`true`) versus refinement insertions
/// (`false`) — the boundary-crossing parity guard downstream needs to compare
/// each inserted run against its raw anchor chord.
pub(super) fn sag_refine_chain(
    curve: &NurbsCurve,
    points: Vec<Vec2>,
    bound: f64,
) -> Result<(Vec<Vec2>, Vec<bool>), KernelRefusal> {
    if points.len() < 2 || std::env::var("BREP_CHAIN_SAG_REFINE").as_deref() == Ok("0") {
        let flags = vec![true; points.len()];
        return Ok((points, flags));
    }
    // A chain whose whole sampling collapsed to ONE zero-length segment is a
    // COLLAPSED cut, and downstream machinery depends on that collapse as a
    // contract — the offset-shell pipeline deliberately leaves the fragile
    // carrier∩opening-plane graze collapsed (a closed degree-1 polyline
    // pcurve that `sample_chain`'s straight shortcut reduces to its
    // coincident endpoints) and sews the orphan rim EXACTLY afterwards
    // (`weld_coplanar_orphan_rims` + isoline upgrade). Refining it here
    // would resurrect the ring as a fitted-polyline trim and bypass that
    // exactness path. Fidelity refinement must never create topology the
    // unrefined sampling did not have, so leave collapsed chains alone.
    if points.len() == 2 && points[0].sub(points[1]).length() <= bound {
        let flags = vec![true; points.len()];
        return Ok((points, flags));
    }
    let [start, end] = curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
    let span = end - start;
    if !(span > 0.0) || !bound.is_finite() || bound <= 0.0 {
        let flags = vec![true; points.len()];
        return Ok((points, flags));
    }
    let segment_count = points.len() - 1;
    let mut refined: Vec<(f64, Vec2, bool)> = points
        .iter()
        .enumerate()
        .map(|(index, point)| {
            (
                start + span * index as f64 / segment_count as f64,
                *point,
                true,
            )
        })
        .collect();
    const MAX_POINTS: usize = 4096;
    let minimum_step = (span * 1e-7).max(1e-12);
    let uv = |parameter: f64| -> Result<Vec2, KernelRefusal> {
        let point = curve.evaluate(parameter).or_refuse(KernelStage::Fragment, "evaluate")?;
        Ok(Vec2 {
            x: point.x,
            y: point.y,
        })
    };
    let mut index = 0;
    while index + 1 < refined.len() && refined.len() < MAX_POINTS {
        let (parameter_a, point_a, _) = refined[index];
        let (parameter_b, point_b, _) = refined[index + 1];
        if parameter_b - parameter_a <= minimum_step {
            index += 1;
            continue;
        }
        let mut sag = 0.0f64;
        for fraction in [0.25, 0.5, 0.75] {
            let probe = uv(parameter_a + (parameter_b - parameter_a) * fraction)?;
            sag = sag.max(point_segment_distance(probe, point_a, point_b));
        }
        if sag > bound {
            let middle = 0.5 * (parameter_a + parameter_b);
            refined.insert(index + 1, (middle, uv(middle)?, false));
            // Re-check the halved front segment before advancing.
        } else {
            index += 1;
        }
    }
    let flags = refined.iter().map(|(_, _, original)| *original).collect();
    Ok((refined.into_iter().map(|(_, point, _)| point).collect(), flags))
}

pub(super) fn point_segment_distance(point: Vec2, start: Vec2, end: Vec2) -> f64 {
    point.distance_to_segment(start, end, 1e-30)
}

/// BOUNDARY-CROSSING PARITY GUARD for sag-refined cut chains (t164, the
/// sphere×tube rim graze). Boundary-crossing TOPOLOGY is owned by the imprint
/// layer: `process_curve` clips section pieces at the face boundary and mints
/// the junctions + edge splits for every crossing it adjudicates. Sag
/// refinement is a FIDELITY device — it may pull a chord off a boundary the
/// true pcurve clears (t70's phantom hole-corner junctions, crossings
/// REMOVED), but it must never ADD a boundary crossing the raw sampling did
/// not have: the refined polyline of a near-tangent graze (t164: the rim dips
/// 4.6e-7 mm into the sphere between two true crossings 0.105 mm apart, only
/// ONE of which the imprint minted) faithfully pokes past the trim row and
/// re-crosses it, and the arrangement then splits the boundary at a locally
/// minted position no other face ever hears about — the neighbouring cap
/// keeps the un-split imprint arc, and assembly strands both records plus the
/// poked micro-arc as one-use edges. Reverting exactly the offending runs to
/// their raw anchor chords restores the imprint-consistent sub-tolerance
/// collapse while keeping the refinement everywhere it stays inside.
/// Deterministic, purely structural (crossing parity per refined run), no
/// vertex is moved and no tolerance widened. Escape hatch:
/// BREP_SAG_CROSSING_GUARD=0.
pub(super) fn enforce_boundary_crossing_parity(
    points: Vec<Vec2>,
    original: &[bool],
    boundaries: &[(Vec2, Vec2)],
    tolerance: f64,
    debug: bool,
    face_id: u64,
) -> Vec<Vec2> {
    if boundaries.is_empty()
        || points.len() != original.len()
        || original.iter().all(|flag| *flag)
        || std::env::var("BREP_SAG_CROSSING_GUARD").as_deref() == Ok("0")
    {
        return points;
    }
    // A crossing within the junction slack of a run anchor is not a NEW
    // crossing — chain endpoints legitimately sit ON boundary junctions and
    // the arrangement cannot distinguish below its own slack anyway.
    let exclusion = tolerance * 50.0;
    // Sequential cut speed (see `loops::sequential_cut_speed`): the boundary
    // segments a polyline segment's box can meet come from a grid over their
    // boxes instead of a scan of all of them. Every segment the box test
    // below admits shares a cell with the query, so the count is the same.
    let (grid_on, grid_check) = super::loops::sequential_cut_speed();
    let grid = (grid_on || grid_check).then(|| BoundaryGrid::new(boundaries)).flatten();
    let visit = std::cell::RefCell::new((vec![0u32; boundaries.len()], 0u32));
    let crossings_with = |polyline: &[Vec2], anchor_start: Vec2, anchor_end: Vec2, use_grid: bool| -> usize {
        let mut count = 0usize;
        let mut candidates: Vec<usize> = Vec::new();
        for pair in polyline.windows(2) {
            let (p, q) = (pair[0], pair[1]);
            let low_x = p.x.min(q.x) - exclusion;
            let high_x = p.x.max(q.x) + exclusion;
            let low_y = p.y.min(q.y) - exclusion;
            let high_y = p.y.max(q.y) + exclusion;
            let direction = q.sub(p);
            candidates.clear();
            match (&grid, use_grid) {
                (Some(grid), true) => {
                    let mut visit = visit.borrow_mut();
                    let (stamps, stamp) = &mut *visit;
                    *stamp = stamp.wrapping_add(1);
                    if *stamp == 0 {
                        stamps.iter_mut().for_each(|s| *s = 0);
                        *stamp = 1;
                    }
                    grid.candidates(low_x, high_x, low_y, high_y, stamps, *stamp, &mut candidates);
                }
                _ => candidates.extend(0..boundaries.len()),
            }
            for (a, b) in candidates.iter().map(|&i| &boundaries[i]) {
                if a.x.max(b.x) < low_x
                    || a.x.min(b.x) > high_x
                    || a.y.max(b.y) < low_y
                    || a.y.min(b.y) > high_y
                {
                    continue;
                }
                let boundary_direction = b.sub(*a);
                let denominator = direction.x * boundary_direction.y
                    - direction.y * boundary_direction.x;
                if denominator.abs() <= 1e-30 {
                    // Parallel/degenerate: never counted as a crossing (a
                    // coincident overlap is handled by the duplicate-chain
                    // drop downstream, and counting it here could only
                    // revert refinement — stay conservative).
                    continue;
                }
                let offset = a.sub(p);
                let t = (offset.x * boundary_direction.y - offset.y * boundary_direction.x)
                    / denominator;
                let s = (offset.x * direction.y - offset.y * direction.x) / denominator;
                if !(0.0..=1.0).contains(&t) || !(0.0..=1.0).contains(&s) {
                    continue;
                }
                let hit = p.add(direction.scale(t));
                if hit.sub(anchor_start).length() <= exclusion
                    || hit.sub(anchor_end).length() <= exclusion
                {
                    continue;
                }
                count += 1;
            }
        }
        count
    };
    let crossings = |polyline: &[Vec2], anchor_start: Vec2, anchor_end: Vec2| -> usize {
        let count = crossings_with(polyline, anchor_start, anchor_end, grid_on);
        if grid_check && grid.is_some() {
            let other = crossings_with(polyline, anchor_start, anchor_end, true);
            if other != count {
                eprintln!("BREP_SEQUENTIAL_CUT_SPEED check: boundary crossings {count} scanned vs {other} from the grid (face {face_id})");
                super::loops::sequential_cut_speed_mismatch("crossing_grid");
            }
        }
        count
    };
    let mut kept: Vec<Vec2> = Vec::with_capacity(points.len());
    let mut run_start = 0usize;
    kept.push(points[0]);
    for index in 1..points.len() {
        if !original[index] {
            continue;
        }
        // Run of inserted points between original anchors run_start..index.
        if index > run_start + 1 {
            let run = &points[run_start..=index];
            let anchor_start = points[run_start];
            let anchor_end = points[index];
            let chord = [anchor_start, anchor_end];
            let refined_crossings = crossings(run, anchor_start, anchor_end);
            let chord_crossings = crossings(&chord, anchor_start, anchor_end);
            if refined_crossings > 0 && chord_crossings == 0 {
                if debug {
                    eprintln!(
                        "  sag-guard: face {face_id} run {}..{} reverted to chord (refined polyline crosses boundary {refined_crossings}x, raw chord 0x)",
                        run_start, index
                    );
                }
                // Revert: drop the inserted points, keep the raw chord.
                if env_read!("BREP_DEBUG_SAG_REVERT").is_some() {
                    let dropped = run[1..run.len() - 1]
                        .iter()
                        .map(|point| point_segment_distance(*point, anchor_start, anchor_end))
                        .fold(0.0f64, f64::max);
                    eprintln!("sag-revert: face {face_id} chord sag {dropped:.3e} arrangement tolerance {tolerance:.3e} ratio {:.3e}", dropped / tolerance);
                }
            } else {
                kept.extend(run[1..run.len() - 1].iter().copied());
            }
        }
        kept.push(points[index]);
        run_start = index;
    }
    kept
}

/// A uniform grid over boundary segments' boxes, for
/// [`enforce_boundary_crossing_parity`]: each segment is listed in every cell
/// its box spans; a query box gets every segment listed in a cell it spans,
/// once. Cell indices are monotone in the coordinate, so two boxes that
/// overlap (closed intervals) span a common cell, and no segment whose box
/// meets the query box is left out. `None` for few segments or any
/// non-finite coordinate (the caller then scans them all).
struct BoundaryGrid {
    origin: Vec2,
    cell: Vec2,
    columns: usize,
    rows: usize,
    cells: Vec<Vec<u32>>,
}

impl BoundaryGrid {
    fn new(boundaries: &[(Vec2, Vec2)]) -> Option<Self> {
        if boundaries.len() < 64 || boundaries.len() > u32::MAX as usize {
            return None;
        }
        let mut low = Vec2 { x: f64::INFINITY, y: f64::INFINITY };
        let mut high = Vec2 { x: f64::NEG_INFINITY, y: f64::NEG_INFINITY };
        for (a, b) in boundaries {
            for p in [a, b] {
                if !(p.x.is_finite() && p.y.is_finite()) {
                    return None;
                }
                low.x = low.x.min(p.x);
                low.y = low.y.min(p.y);
                high.x = high.x.max(p.x);
                high.y = high.y.max(p.y);
            }
        }
        let side = (boundaries.len() as f64).sqrt().ceil().clamp(1.0, 1024.0) as usize;
        let cell = Vec2 { x: ((high.x - low.x) / side as f64).max(f64::MIN_POSITIVE), y: ((high.y - low.y) / side as f64).max(f64::MIN_POSITIVE) };
        let mut grid = Self { origin: low, cell, columns: side, rows: side, cells: vec![Vec::new(); side * side] };
        for (index, (a, b)) in boundaries.iter().enumerate() {
            let (c0, c1) = (grid.column(a.x.min(b.x)), grid.column(a.x.max(b.x)));
            let (r0, r1) = (grid.row(a.y.min(b.y)), grid.row(a.y.max(b.y)));
            for row in r0..=r1 {
                for column in c0..=c1 {
                    grid.cells[row * grid.columns + column].push(index as u32);
                }
            }
        }
        Some(grid)
    }

    fn column(&self, x: f64) -> usize {
        let at = ((x - self.origin.x) / self.cell.x).floor();
        if at.is_nan() || at <= 0.0 { 0 } else { (at as usize).min(self.columns - 1) }
    }

    fn row(&self, y: f64) -> usize {
        let at = ((y - self.origin.y) / self.cell.y).floor();
        if at.is_nan() || at <= 0.0 { 0 } else { (at as usize).min(self.rows - 1) }
    }

    /// Every segment listed in a cell the box spans, each once (`stamps`
    /// marks the segments already taken under `stamp`). A box with a
    /// non-finite side takes every segment.
    #[allow(clippy::too_many_arguments)]
    fn candidates(&self, low_x: f64, high_x: f64, low_y: f64, high_y: f64, stamps: &mut [u32], stamp: u32, out: &mut Vec<usize>) {
        if !(low_x.is_finite() && high_x.is_finite() && low_y.is_finite() && high_y.is_finite()) {
            out.extend(0..stamps.len());
            return;
        }
        for row in self.row(low_y)..=self.row(high_y) {
            for column in self.column(low_x)..=self.column(high_x) {
                for &index in &self.cells[row * self.columns + column] {
                    let index = index as usize;
                    if stamps[index] != stamp {
                        stamps[index] = stamp;
                        out.push(index);
                    }
                }
            }
        }
    }
}

pub(super) fn refine_near_hints(
    points: &[Vec2],
    curve: &NurbsCurve,
    hints: &[Vec2],
) -> Result<Vec<Vec2>, KernelRefusal> {
    if hints.is_empty() || points.len() < 3 {
        return Ok(points.to_vec());
    }
    let [start, end] = curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
    let segment_count = points.len() - 1;
    let mut result = vec![points[0]];
    for index in 0..segment_count {
        let a = points[index];
        let b = points[index + 1];
        let length = b.sub(a).length();
        if length > 0.0
            && hints
                .iter()
                .any(|hint| point_segment_distance(*hint, a, b) <= length)
        {
            let parameter_a = start + (end - start) * index as f64 / segment_count as f64;
            let parameter_b = start + (end - start) * (index + 1) as f64 / segment_count as f64;
            for sub in 1..16 {
                let point = curve
                    .evaluate(parameter_a + (parameter_b - parameter_a) * sub as f64 / 16.0).or_refuse(KernelStage::Fragment, "evaluate")?;
                result.push(Vec2 {
                    x: point.x,
                    y: point.y,
                });
            }
        }
        result.push(b);
    }
    Ok(result)
}