BREP_kernel 0.33.0

Rust B-rep CAD kernel (next.BREP.io): a boundary representation (B-rep) geometry kernel for building CAD applications, native and WebAssembly.
Documentation
//! Containment between the closed loops of a planar profile — the ONE predicate
//! behind every outer/hole decision a profile makes (the sketch's region
//! grouping, `sketch::regions::classify_regions`, and the profile consumers'
//! hole forest, `common::hole_nesting`).
//!
//! It classifies the loops' EMITTED curves — the exact NURBS the solid is built
//! from — never a second, independent derivation of the same geometry. A user's
//! failing sketch was exactly such a derivation: the sketch's
//! own sampler re-derived each arc's direction from its end points by the
//! shortest turn, sampled a half-circle slot cap on the wrong side, and a hole
//! concentric with the cap was extruded as a separate disc.
//!
//! Two more safeguards against the classes of error a coarse sampler invites:
//!
//! * each curve is sampled ADAPTIVELY until every chord is within `tolerance`
//!   of the exact curve, and that achieved deviation (`slack`) is carried, so a
//!   test point closer than it to a loop counts as ON that loop, never
//!   decisively inside or outside it;
//! * containment is decided by a VOTE of exact points spread over every curve
//!   of the loop (interior parameters only, so a vertex a hole shares with its
//!   outer — a touching, legal sketch — never votes). Points on the other
//!   loop's boundary abstain; the decisive majority wins. A loop with no
//!   decisive point (it coincides with the other) is not inside it.

use crate::{NurbsCurve, Vec3};

/// Relative chord tolerance: a sampled chord stays within this fraction of the
/// profile's extent of the exact curve.
const RELATIVE_TOLERANCE: f64 = 1e-6;
/// Initial pieces per knot span, before adaptive refinement (an S-shaped span
/// whose midpoint happens to lie on its chord is still split).
const PIECES_PER_SPAN: usize = 4;
/// Refinement depth per initial piece (2^12 sub-chords at most).
const MAX_DEPTH: u32 = 12;
/// Interior parameters (fractions of each curve's domain) that vote.
const VOTE_FRACTIONS: [f64; 5] = [0.13, 0.31, 0.5, 0.69, 0.87];

/// One closed loop sampled in the profile plane.
pub(crate) struct NestingLoop {
    polygon: Vec<[f64; 2]>,
    votes: Vec<[f64; 2]>,
    /// Largest distance between the exact curve and `polygon` actually reached.
    slack: f64,
    min: [f64; 2],
    max: [f64; 2],
}

/// Plane projection of a profile: `origin` plus the in-plane axes.
#[derive(Clone, Copy)]
pub(crate) struct PlaneFrame {
    pub origin: Vec3,
    pub x_axis: Vec3,
    pub y_axis: Vec3,
}

impl PlaneFrame {
    fn uv(&self, point: Vec3) -> [f64; 2] {
        let delta = point.sub(self.origin);
        [delta.dot(self.x_axis), delta.dot(self.y_axis)]
    }
}

/// Sample every loop (each a head-to-tail list of curves) in `frame`. The chord
/// tolerance is relative to the extent of ALL the loops' control points, so
/// every loop is sampled to the same absolute accuracy.
pub(crate) fn sample_loops(
    loops: &[&[NurbsCurve]],
    frame: PlaneFrame,
) -> Result<Vec<NestingLoop>, String> {
    let mut lo = [f64::INFINITY; 2];
    let mut hi = [f64::NEG_INFINITY; 2];
    for curves in loops {
        for curve in curves.iter() {
            for control in &curve.control_points {
                let uv = frame.uv(control.point()?);
                for k in 0..2 {
                    lo[k] = lo[k].min(uv[k]);
                    hi[k] = hi[k].max(uv[k]);
                }
            }
        }
    }
    let extent = (hi[0] - lo[0]).hypot(hi[1] - lo[1]);
    let tolerance = (extent * RELATIVE_TOLERANCE).max(1e-12);
    loops
        .iter()
        .map(|curves| sample_loop(curves, frame, tolerance))
        .collect()
}

fn sample_loop(
    curves: &[NurbsCurve],
    frame: PlaneFrame,
    tolerance: f64,
) -> Result<NestingLoop, String> {
    let mut polygon = Vec::new();
    let mut votes = Vec::new();
    let mut slack: f64 = 0.0;
    for curve in curves {
        let [t0, t1] = curve.domain()?;
        let at = |t: f64| -> Result<[f64; 2], String> { Ok(frame.uv(curve.evaluate(t)?)) };
        // Distinct knots inside the domain bound the spans.
        let mut breaks = vec![t0];
        for &knot in &curve.knots {
            if knot > t0 && knot < t1 && knot > *breaks.last().unwrap() {
                breaks.push(knot);
            }
        }
        breaks.push(t1);
        // The polygon holds each sample's START; the loop is head-to-tail, so
        // the next curve (or the closing edge) supplies the end.
        for span in breaks.windows(2) {
            for piece in 0..PIECES_PER_SPAN {
                let a = span[0] + (span[1] - span[0]) * (piece as f64 / PIECES_PER_SPAN as f64);
                let b = span[0]
                    + (span[1] - span[0]) * ((piece + 1) as f64 / PIECES_PER_SPAN as f64);
                let (pa, pb) = (at(a)?, at(b)?);
                refine(&at, a, pa, b, pb, tolerance, MAX_DEPTH, &mut polygon, &mut slack)?;
            }
        }
        for fraction in VOTE_FRACTIONS {
            votes.push(at(t0 + (t1 - t0) * fraction)?);
        }
    }
    let mut min = [f64::INFINITY; 2];
    let mut max = [f64::NEG_INFINITY; 2];
    for point in &polygon {
        for k in 0..2 {
            min[k] = min[k].min(point[k]);
            max[k] = max[k].max(point[k]);
        }
    }
    Ok(NestingLoop {
        polygon,
        votes,
        slack: slack.max(tolerance),
        min,
        max,
    })
}

/// Push `pa` and the refined interior samples of `[a, b)`, splitting until the
/// chord's midpoint deviation is within `tolerance` (or the depth runs out, in
/// which case the larger deviation is recorded in `slack`).
#[allow(clippy::too_many_arguments)]
fn refine(
    at: &impl Fn(f64) -> Result<[f64; 2], String>,
    a: f64,
    pa: [f64; 2],
    b: f64,
    pb: [f64; 2],
    tolerance: f64,
    depth: u32,
    polygon: &mut Vec<[f64; 2]>,
    slack: &mut f64,
) -> Result<(), String> {
    let m = 0.5 * (a + b);
    let pm = at(m)?;
    let deviation = distance_to_segment(pm, pa, pb);
    if deviation <= tolerance || depth == 0 {
        // Quarter points too, so a chord whose midpoint happens to sit on it
        // (an inflection) still reports its real deviation.
        let q1 = distance_to_segment(at(0.5 * (a + m))?, pa, pb);
        let q3 = distance_to_segment(at(0.5 * (m + b))?, pa, pb);
        let worst = deviation.max(q1).max(q3);
        if worst <= tolerance || depth == 0 {
            *slack = slack.max(worst);
            polygon.push(pa);
            return Ok(());
        }
    }
    refine(at, a, pa, m, pm, tolerance, depth - 1, polygon, slack)?;
    refine(at, m, pm, b, pb, tolerance, depth - 1, polygon, slack)
}

/// `contains[i][j]`: loop `i` lies inside loop `j`.
pub(crate) fn containment(loops: &[NestingLoop]) -> Vec<Vec<bool>> {
    let count = loops.len();
    let mut contains = vec![vec![false; count]; count];
    for i in 0..count {
        for j in 0..count {
            if i != j {
                contains[i][j] = inside(&loops[i], &loops[j]);
            }
        }
    }
    contains
}

/// Whether `inner` lies inside `outer` by the vote of `inner`'s points.
fn inside(inner: &NestingLoop, outer: &NestingLoop) -> bool {
    if outer.polygon.len() < 3 {
        return false;
    }
    // A point closer to `outer`'s sampled boundary than both samplings'
    // deviation (plus a hair) may be on either side of the exact boundary.
    let band = 2.0 * (outer.slack + inner.slack);
    if inner.max[0] < outer.min[0] - band
        || inner.max[1] < outer.min[1] - band
        || inner.min[0] > outer.max[0] + band
        || inner.min[1] > outer.max[1] + band
    {
        return false;
    }
    let (mut ins, mut outs) = (0usize, 0usize);
    for &point in &inner.votes {
        if point[0] < outer.min[0] - band
            || point[1] < outer.min[1] - band
            || point[0] > outer.max[0] + band
            || point[1] > outer.max[1] + band
        {
            outs += 1;
            continue;
        }
        let count = outer.polygon.len();
        let on_boundary = (0..count).any(|k| {
            distance_to_segment(point, outer.polygon[k], outer.polygon[(k + 1) % count]) <= band
        });
        if on_boundary {
            continue;
        }
        if crate::polygon::parity_inside(point, count, |k| outer.polygon[k]) {
            ins += 1;
        } else {
            outs += 1;
        }
    }
    ins > outs
}

fn distance_to_segment(p: [f64; 2], a: [f64; 2], b: [f64; 2]) -> f64 {
    let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
    let length_squared = dx * dx + dy * dy;
    let t = if length_squared > 0.0 {
        (((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / length_squared).clamp(0.0, 1.0)
    } else {
        0.0
    };
    (p[0] - (a[0] + t * dx)).hypot(p[1] - (a[1] + t * dy))
}