BREP_boolean 0.34.1

Rust B-rep CAD kernel (next.BREP.io): booleans and healing: imprint, fragment, boolean assembly, sewing and face merging.
Documentation
//! `BREP_BOOLEAN_ISOTROPIC_CHART` (default on since 2026-11-28; `=0` off): the boolean's chart
//! tolerances (the loop split's band and clearance, the arrangement's junction
//! match) are lengths in a face's (u, v) chart, read the same way in both
//! directions. A face whose chart is far from isotropic (the benchy bow side:
//! 997 model units per unit u against 12 per unit v, its u domain 0.035 wide)
//! turns a uv band of 1e-4 into 0.1 along u, and a section that ends 0.055 off
//! a vertex there reads as crossing the loop: the face was declined by the loop
//! split and left unsplit by the arrangement, and the result had a hole.
//!
//! With the switch on, a boolean that REFUSES is retried, FIRST (ahead of the
//! perturbation and window ladders: on the benchy port cut they spent 71 s
//! failing before it), with every face whose
//! mean parameter speeds differ by more than [`ANISOTROPY`] rescaled linearly
//! along its fast parameter (its knots, and that coordinate of each of its
//! pcurves, by the speed ratio): the geometry is the same, only the chart is
//! stretched. A boolean that builds is never re-run: a chart-tuned lane (the
//! feature-scale wedge resolution of `slab_corner_wedge`) answers differently
//! on a rescaled chart, and rescaled up front it built a union whose volume
//! broke inclusion-exclusion.
use crate::{BrepSolid, NurbsCurve, Vec4};

/// The parameter-speed ratio past which a face's chart is rescaled.
const ANISOTROPY: f64 = 20.0;

pub(crate) fn isotropic_chart_on() -> bool {
    crate::switch!(live "BREP_BOOLEAN_ISOTROPIC_CHART", true)
}

thread_local! {
    static ACTIVE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

thread_local! {
    static SUPPRESSED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Whether the rescaled attempt is suppressed (the window retry's attempts).
pub(crate) fn is_suppressed() -> bool {
    SUPPRESSED.with(|cell| cell.get())
}

/// Run `action` with the rescaled attempt suppressed.
pub(crate) fn suppressed<T>(action: impl FnOnce() -> T) -> T {
    let previous = SUPPRESSED.with(|cell| cell.replace(true));
    let result = action();
    SUPPRESSED.with(|cell| cell.set(previous));
    result
}

/// Whether the boolean is already running on rescaled operands.
pub(crate) fn active() -> bool {
    ACTIVE.with(|cell| cell.get())
}

/// Run `action` as the rescaled boolean.
pub(crate) fn with_active<T>(action: impl FnOnce() -> T) -> T {
    let previous = ACTIVE.with(|cell| cell.replace(true));
    let result = action();
    ACTIVE.with(|cell| cell.set(previous));
    result
}

/// Mean |S_u| and |S_v| over a 5 x 5 grid of the surface's domain.
fn mean_speeds(surface: &crate::NurbsSurface) -> Option<(f64, f64)> {
    let [u0, u1] = surface.domain_u().ok()?;
    let [v0, v1] = surface.domain_v().ok()?;
    let (mut su, mut sv) = (0.0, 0.0);
    for i in 0..5 {
        for j in 0..5 {
            let u = u0 + (u1 - u0) * (i as f64 + 0.5) / 5.0;
            let v = v0 + (v1 - v0) * (j as f64 + 0.5) / 5.0;
            let d = surface.derivatives(u, v, 1).ok()?;
            su += d[1][0].length();
            sv += d[0][1].length();
        }
    }
    (su > 0.0 && sv > 0.0 && su.is_finite() && sv.is_finite()).then_some((su / 25.0, sv / 25.0))
}

/// `curve` (a pcurve) with its u (`along_u`) or v coordinate scaled by `k`.
fn scaled_pcurve(curve: &NurbsCurve, along_u: bool, k: f64) -> Option<NurbsCurve> {
    let controls = curve
        .control_points
        .iter()
        .map(|c| if along_u { Vec4 { x: c.x * k, ..*c } } else { Vec4 { y: c.y * k, ..*c } })
        .collect();
    NurbsCurve::new(curve.degree, curve.knots.clone(), controls).ok()
}

/// `solid` with every anisotropic face chart rescaled, or `None` when none is.
pub(crate) fn isotropic(solid: &BrepSolid) -> Option<BrepSolid> {
    let mut result = solid.clone();
    let mut changed = 0usize;
    for face in result.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
        let Some((su, sv)) = mean_speeds(&face.surface) else { continue };
        let (along_u, k) = if su > ANISOTROPY * sv {
            (true, su / sv)
        } else if sv > ANISOTROPY * su {
            (false, sv / su)
        } else {
            continue;
        };
        let s = &face.surface;
        let (knots_u, knots_v) = if along_u {
            (s.knots_u.iter().map(|t| t * k).collect(), s.knots_v.clone())
        } else {
            (s.knots_u.clone(), s.knots_v.iter().map(|t| t * k).collect())
        };
        let Ok(surface) = crate::NurbsSurface::new(s.degree_u, s.degree_v, knots_u, knots_v, s.control_points.clone()) else { continue };
        let mut pcurves = Vec::new();
        for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
            pcurves.push(scaled_pcurve(&coedge.pcurve, along_u, k));
        }
        if pcurves.iter().any(Option::is_none) {
            continue;
        }
        face.surface = surface;
        for (coedge, pcurve) in face.loops.iter_mut().flat_map(|lp| &mut lp.coedges).zip(pcurves) {
            coedge.pcurve = pcurve.expect("checked");
        }
        changed += 1;
        if std::env::var("BREP_DEBUG_BOOL").is_ok() {
            eprintln!("isotropic chart: face {} {} scaled by {k:.3e} (speeds {su:.3e} / {sv:.3e})", face.id, if along_u { "u" } else { "v" });
        }
    }
    (changed > 0 && result.validate().is_empty()).then_some(result)
}