BREP_boolean 0.35.0

Rust B-rep CAD kernel (next.BREP.io): booleans and healing: imprint, fragment, boolean assembly, sewing and face merging.
Documentation
//! Closed-form booleans (`BREP_CLOSED_FORM_BOOLEAN`, off unless set): for a
//! fixed list of operand pairs whose result can be written down from closed
//! forms, the result is built directly instead of being imprinted, fragmented,
//! selected and assembled.
//!
//! Only the arrangement is replaced. The result is validated here with the
//! boolean's own policy and then goes through the same soundness acceptance
//! as any other boolean result, at the caller. A pair no rule recognises
//! exactly, a configuration inside a rule's decline band, or a built body
//! that does not validate, runs the general pipeline as before: there is no
//! partial path.
//!
//! `BREP_CLOSED_FORM_BOOLEAN=check` builds the closed-form result, runs the
//! general pipeline beside it, reports every difference between the two on
//! stderr (`closed_form.check`) and returns the pipeline's answer.
//! `BREP_CLOSED_FORM_CENSUS=1` prints one line per boolean: the rule that
//! matched, or why none did.
use super::{boolean_policy, BooleanOperation, BooleanOptions, BrepSolid, KernelRefusal};
use crate::env_read::Mode;
use crate::topology::HashSet;
use crate::{KernelDiagnostics, KernelOutcome, KernelTolerances, Vec3};

mod ball_cut;
mod compare;
mod through_hole;

/// What the general pipeline hands its caller.
pub(super) type PipelineAnswer = Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal>;

/// Why a rule did not answer: a fixed phrase for the census.
pub(super) type Decline = &'static str;

fn mode() -> Mode {
    crate::mode_switch!("BREP_CLOSED_FORM_BOOLEAN", false)
}

fn census() -> bool {
    crate::debug_flag!("BREP_CLOSED_FORM_CENSUS")
}

/// The boolean's arrangement: the closed-form result where a rule recognises
/// the pair and the switch is on, the general `pipeline` otherwise.
pub(super) fn run(
    first: &BrepSolid,
    second: &BrepSolid,
    operation: BooleanOperation,
    options: &BooleanOptions,
    tangent_nodes: &mut Vec<Vec3>,
    pipeline: impl FnOnce(&BrepSolid, &BrepSolid, BooleanOperation, &BooleanOptions, &mut Vec<Vec3>) -> PipelineAnswer,
) -> PipelineAnswer {
    let mode = mode();
    let census = census();
    if mode == Mode::Off && !census {
        return pipeline(first, second, operation, options, tangent_nodes);
    }
    let started = web_time::Instant::now();
    let attempt = attempt(first, second, operation, options);
    if census {
        let ms = started.elapsed().as_secs_f64() * 1e3;
        match &attempt {
            Ok(answer) => eprintln!("closed_form.census {operation:?} rule={} ms={ms:.3} {}", answer.rule, signature(first, second)),
            Err(why) => eprintln!("closed_form.census {operation:?} declined=\"{why}\" ms={ms:.3} {}", signature(first, second)),
        }
    }
    match (mode, attempt) {
        (Mode::On, Ok(Answer { rule, solid, candidates, policy })) => {
            let mut diagnostics = KernelDiagnostics::default();
            diagnostics.count("boolean.closed_form");
            diagnostics.count(format!("boolean.closed_form.{rule}"));
            diagnostics.measure_max("tolerance.model", policy.model);
            diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
            diagnostics.measure_max("timing.total_ms", started.elapsed().as_secs_f64() * 1e3);
            if let Some(candidates) = &candidates {
                diagnostics.count_n("passthrough.soundness_candidates", candidates.len() as u64);
            }
            Ok((KernelOutcome { value: solid, diagnostics }, candidates))
        }
        (Mode::Check, Ok(Answer { rule, solid, candidates, .. })) => {
            let general = pipeline(first, second, operation, options, tangent_nodes);
            let mut differences = match &general {
                Ok((outcome, _)) => compare::body_differences(&solid, &outcome.value),
                Err(refusal) => vec![format!("the pipeline refused: {refusal}")],
            };
            // The built body's scan may not read fewer faces than the
            // pipeline's own scope.
            if let (Some(mine), Ok((_, Some(theirs)))) = (&candidates, &general) {
                if mine.len() < theirs.len() {
                    differences.push(format!("{} soundness candidates against the pipeline's {}", mine.len(), theirs.len()));
                }
            }
            // The scoped soundness scan the built body would get, with the
            // whole-body scan beside it: the two must give one verdict.
            let scoped = match &candidates {
                Some(candidates) => crate::accept_sound_against_scoped(&[first, second], solid.clone(), "boolean", candidates),
                None => crate::accept_sound_against(&[first, second], solid.clone(), "boolean"),
            };
            let whole = crate::accept_sound_against(&[first, second], solid, "boolean");
            match (&scoped, &whole) {
                (Ok(_), Ok(_)) => {}
                (Err(a), Err(b)) => differences.push(format!("the built body is refused: {a} (whole body: {b})")),
                (Ok(_), Err(refusal)) => differences.push(format!("the scoped scan passes what the whole-body scan refuses: {refusal}")),
                (Err(refusal), Ok(_)) => differences.push(format!("the scoped scan refuses what the whole-body scan passes: {refusal}")),
            }
            if differences.is_empty() {
                eprintln!("closed_form.check {operation:?} rule={rule} agree");
            } else {
                DISAGREEMENTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                eprintln!("closed_form.check {operation:?} rule={rule} DISAGREE: {}", differences.join("; "));
            }
            general
        }
        _ => pipeline(first, second, operation, options, tangent_nodes),
    }
}

static DISAGREEMENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// How many check-mode comparisons have disagreed in this process.
#[doc(hidden)]
pub fn check_disagreements() -> u64 {
    DISAGREEMENTS.load(std::sync::atomic::Ordering::Relaxed)
}

/// What a rule built.
pub(super) struct Built {
    pub(super) solid: BrepSolid,
    /// The faces the operation made or changed.
    pub(super) touched: HashSet<u64>,
    /// Each face's operand of origin.
    pub(super) operand_of: crate::topology::HashMap<u64, u8>,
}

/// What `attempt` hands back: the rule's name, its body, the soundness
/// candidates and the policy.
struct Answer {
    rule: &'static str,
    solid: BrepSolid,
    /// `None`: the whole body.
    candidates: Option<HashSet<u64>>,
    policy: KernelTolerances,
}

/// The faces the pipeline's own scope reads, by the pipeline's own rules
/// (`AssemblyScope::build` and `soundness_candidates`): the touched faces;
/// every face sharing a vertex with one, where an edge the operation made
/// ends at that vertex (any vertex with `BREP_SCOPE_CHANGED_RING=0`); and
/// (`reaching`) every other face whose control-net box reaches the other
/// operand's bounds.
fn examined(built: &Built, operands: [&BrepSolid; 2], reaching: Option<([crate::Aabb; 2], f64)>) -> HashSet<u64> {
    use super::touch::{changed_ring_on, edge_content};
    let ends: crate::topology::HashMap<u64, (u64, u64)> =
        built.solid.edges.iter().map(|edge| (edge.id, (edge.start_vertex_id, edge.end_vertex_id))).collect();
    // An edge whose geometry no operand held, bit for bit, is one the
    // operation made.
    let changed: Option<HashSet<u64>> = changed_ring_on().then(|| {
        let held: HashSet<[u64; 2]> = operands.iter().flat_map(|solid| &solid.edges).map(edge_content).collect();
        built
            .solid
            .edges
            .iter()
            .filter(|edge| !held.contains(&edge_content(edge)))
            .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
            .collect()
    });
    let vertices_of = |face: &crate::topology::FaceRecord| {
        face.loops
            .iter()
            .flat_map(|ring| &ring.coedges)
            .filter_map(|coedge| ends.get(&coedge.edge_id))
            .flat_map(|(start, end)| [*start, *end])
            .collect::<Vec<_>>()
    };
    let faces = || built.solid.shells.iter().flat_map(|shell| &shell.faces);
    let on_touched: HashSet<u64> = faces()
        .filter(|face| built.touched.contains(&face.id))
        .flat_map(vertices_of)
        .filter(|vertex| changed.as_ref().is_none_or(|changed| changed.contains(vertex)))
        .collect();
    faces()
        .filter(|face| {
            built.touched.contains(&face.id)
                || vertices_of(face).iter().any(|vertex| on_touched.contains(vertex))
                || reaching.is_some_and(|(bounds, band)| {
                    let other = bounds[usize::from(built.operand_of.get(&face.id) == Some(&0))];
                    !crate::Aabb::from_surface_controls(&face.surface).is_ok_and(|own| !own.intersects(other, band))
                })
        })
        .map(|face| face.id)
        .collect()
}

/// The rule that answered, its result and the policy it was validated under.
fn attempt(
    first: &BrepSolid,
    second: &BrepSolid,
    operation: BooleanOperation,
    options: &BooleanOptions,
) -> Result<Answer, Decline> {
    if matches!(operation, BooleanOperation::Union) {
        return Err("no rule for this operation");
    }
    if !plain(options) {
        return Err("non-default options");
    }
    for solid in [first, second] {
        if solid.kind != crate::BodyKind::Solid || !solid.cells.is_empty() {
            return Err("an operand is not a plain solid");
        }
    }
    let policy = boolean_policy(first, second, options).map_err(|_| "the tolerance policy refuses")?;
    // The first rule that answers; a pair none answers reports the last
    // rule's reason.
    let (rule, built) = match operation {
        BooleanOperation::Subtract => match through_hole::subtract(first, second, &policy) {
            Ok(built) => ("through_hole", built),
            Err(_) => ("ball_cut", ball_cut::cut(first, second, false, &policy)?),
        },
        BooleanOperation::Intersect => ("ball_cut", ball_cut::cut(first, second, true, &policy)?),
        BooleanOperation::Union => return Err("no rule for this operation"),
    };
    // With pass-through off (`BREP_UNTOUCHED_PASSTHROUGH=0`) the pipeline
    // scopes nothing, and neither does this.
    let scoped = super::untouched_passthrough(options);
    let geometry = scoped.then(|| examined(&built, [first, second], None));
    if !built.solid.validate_detailed_scoped(&policy, geometry.as_ref()).issues.is_empty() {
        return Err("the built body does not validate");
    }
    if !scoped {
        return Ok(Answer { rule, solid: built.solid, candidates: None, policy });
    }
    // The soundness candidates: the examined faces and every face whose box
    // reaches the other operand. The pipeline leaves out of the second group
    // the faces its imprint proved apart; no imprint ran here, and a rule's
    // own clearance proof is not a soundness certificate, so none is left
    // out: this set is never smaller than the pipeline's.
    let reaching = Some(([super::operand_bounds(first), super::operand_bounds(second)], policy.sew_search));
    let candidates = examined(&built, [first, second], reaching);
    Ok(Answer { rule, solid: built.solid, candidates: Some(candidates), policy })
}

/// Whether `options` are the default ones: the only options the rules have
/// been compared against the pipeline under. (`BooleanOptions` has no
/// equality; its `Debug` text names every field.)
fn plain(options: &BooleanOptions) -> bool {
    thread_local! {
        static DEFAULT: String = format!("{:?}", BooleanOptions::default());
    }
    options.tolerances.is_none()
        && options.keep_unmerged_name_substrs.is_empty()
        && options.seam_reseat_later_references.is_none()
        && options.seam_rejoin_later_references.is_none()
        && DEFAULT.with(|default| *default == format!("{options:?}"))
}

/// The operands by face carrier kind, for the census line.
fn signature(first: &BrepSolid, second: &BrepSolid) -> String {
    let kinds = |solid: &BrepSolid| {
        let mut counts = std::collections::BTreeMap::<&'static str, usize>::new();
        for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
            *counts.entry(carrier_kind(&face.surface)).or_default() += 1;
        }
        counts.iter().map(|(kind, count)| format!("{kind}{count}")).collect::<Vec<_>>().join("+")
    };
    format!("first=[{}] second=[{}]{}{}", kinds(first), kinds(second), straddled("first", first, second), straddled("second", second, first))
}

/// Census only: where `block` has six flat faces, how many of their planes
/// the other operand's control points lie on both sides of.
fn straddled(label: &str, block: &BrepSolid, other: &BrepSolid) -> String {
    let faces: Vec<_> = block.shells.iter().flat_map(|shell| &shell.faces).collect();
    if faces.len() != 6 {
        return String::new();
    }
    let points: Vec<Vec3> = other
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .flat_map(|face| face.surface.control_points.iter().flatten())
        .filter_map(|control| control.point().ok())
        .collect();
    let mut cutting = 0;
    for face in faces {
        let Some(crate::AnalyticSurface::Plane { origin, u_dir, v_dir, .. }) = face.surface.analytic() else { return String::new() };
        let normal = u_dir.cross(*v_dir);
        let sides = points.iter().map(|point| point.sub(*origin).dot(normal));
        let (low, high) = sides.fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), side| (low.min(side), high.max(side)));
        cutting += usize::from(low < 0.0 && high > 0.0);
    }
    format!(" {label}_block_planes_straddled={cutting}")
}

/// Number vertices, edges, faces, loops and coedges from 1 in the order a walk
/// over the faces first meets them, as the assembler numbers its results.
fn renumber(solid: &mut BrepSolid) {
    let ends: crate::topology::HashMap<u64, (u64, u64)> =
        solid.edges.iter().map(|edge| (edge.id, (edge.start_vertex_id, edge.end_vertex_id))).collect();
    let mut vertex_ids = crate::topology::HashMap::<u64, u64>::default();
    let mut edge_ids = crate::topology::HashMap::<u64, u64>::default();
    let (mut faces, mut loops, mut coedges) = (0, 0, 0);
    for face in solid.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
        faces += 1;
        face.id = faces;
        for ring in &mut face.loops {
            loops += 1;
            ring.id = loops;
            for coedge in &mut ring.coedges {
                coedges += 1;
                coedge.id = coedges;
                let (start, end) = ends.get(&coedge.edge_id).copied().unwrap_or((0, 0));
                for vertex in if coedge.forward { [start, end] } else { [end, start] } {
                    let next = vertex_ids.len() as u64 + 1;
                    vertex_ids.entry(vertex).or_insert(next);
                }
                let next = edge_ids.len() as u64 + 1;
                coedge.edge_id = *edge_ids.entry(coedge.edge_id).or_insert(next);
            }
        }
    }
    // Anything no face reaches keeps a number after the ones in use.
    for edge in &mut solid.edges {
        for vertex in [&mut edge.start_vertex_id, &mut edge.end_vertex_id] {
            let next = vertex_ids.len() as u64 + 1;
            *vertex = *vertex_ids.entry(*vertex).or_insert(next);
        }
        let next = edge_ids.len() as u64 + 1;
        edge.id = *edge_ids.entry(edge.id).or_insert(next);
    }
    for vertex in &mut solid.vertices {
        let next = vertex_ids.len() as u64 + 1;
        vertex.id = *vertex_ids.entry(vertex.id).or_insert(next);
    }
    solid.edges.sort_by_key(|edge| edge.id);
    solid.vertices.sort_by_key(|vertex| vertex.id);
}

pub(super) fn carrier_kind(surface: &crate::NurbsSurface) -> &'static str {
    use crate::AnalyticSurface as A;
    match surface.analytic() {
        Some(A::Plane { .. }) => "plane",
        Some(A::RuledRevolution { rho0, rho1, .. }) => {
            if (rho0 - rho1).abs() <= 1e-12 * rho0.abs().max(rho1.abs()) { "cylinder" } else { "cone" }
        }
        Some(A::Sphere { .. }) => "sphere",
        Some(A::Torus { .. }) => "torus",
        Some(A::Revolution { .. }) => "revolution",
        None => "nurbs",
    }
}