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
//! A whole ball cut by one flat face of a block: `ball ∩ block` or
//! `ball − block`, where the block is a convex six-faced body, one of its
//! faces is square to the ball's pole axis and cuts it, and the ball is
//! clear of the block's other five planes on the inside by more than the
//! decline margin. The result is the ball's own face trimmed at one of its
//! own circles of latitude, closed by a disc on the block's face.
//!
//! Declined: a cut within the margin of a pole or of tangency, a cutting
//! plane not square to the pole axis (its circle is not a line in the ball's
//! parameters), a ball that reaches a second plane of the block, a block
//! that is not convex, and anything that is not a primitive ball.
use super::through_hole::{in_plane, unit_domain};
use super::{Built, Decline};
use crate::curve::parameter_line;
use crate::topology::{BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, VertexRecord};
use crate::{AnalyticSurface, KernelTolerances, NurbsCurve, Vec3, Vec4};

/// A ball as a primitive builds it: one face, a seam between two poles.
struct Ball<'a> {
    face: &'a FaceRecord,
    centre: Vec3,
    /// Unit, from the `v = 0` pole to the `v = 1` pole.
    axis: Vec3,
    radius: f64,
    /// The loop's coedges: the `v = 0` pole, the seam upward, the `v = 1`
    /// pole, the seam downward.
    low_pole: &'a CoedgeRecord,
    high_pole: &'a CoedgeRecord,
    seam: &'a EdgeRecord,
}

fn recognise(solid: &BrepSolid) -> Result<Ball<'_>, Decline> {
    const NOT: Decline = "the body is not a whole ball";
    let [shell] = solid.shells.as_slice() else { return Err(NOT) };
    let [face] = shell.faces.as_slice() else { return Err(NOT) };
    let Some(AnalyticSurface::Sphere { radius, .. }) = face.surface.analytic() else { return Err(NOT) };
    let surface = &face.surface;
    if !face.same_sense
        || solid.edges.len() != 3
        || solid.vertices.len() != 2
        || solid.genus != 0
        || !unit_domain(&surface.knots_u, surface.degree_u)
        || !unit_domain(&surface.knots_v, surface.degree_v)
    {
        return Err(NOT);
    }
    let [ring] = face.loops.as_slice() else { return Err(NOT) };
    let [low_pole, up, high_pole, down] = ring.coedges.as_slice() else { return Err(NOT) };
    let edge = |coedge: &CoedgeRecord| solid.edges.iter().find(|edge| edge.id == coedge.edge_id).ok_or(NOT);
    let (low_edge, seam, high_edge) = (edge(low_pole)?, edge(up)?, edge(high_pole)?);
    if !low_edge.degenerate
        || !high_edge.degenerate
        || seam.degenerate
        || down.edge_id != seam.id
        || !up.forward
        || down.forward
        || seam.t0 != 0.0
        || seam.t1 != 1.0
        || seam.start_vertex_id != low_edge.start_vertex_id
        || seam.end_vertex_id != high_edge.start_vertex_id
    {
        return Err(NOT);
    }
    let at = |u: f64, v: f64| surface.evaluate(u, v).map_err(|_| NOT);
    let (low, high) = (at(0.0, 0.0)?, at(0.0, 1.0)?);
    let centre = low.add(high).scale(0.5);
    let axis = high.sub(low).normalized().map_err(|_| NOT)?;
    let exact = 1e-10 * radius;
    if (high.sub(low).length() - 2.0 * radius).abs() > exact {
        return Err(NOT);
    }
    // The seam is the surface's `u = 0` meridian, parametrised by `v`, and
    // the poles are where the loop says.
    let point = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point).ok_or(NOT);
    if point(seam.start_vertex_id)?.sub(low).length() > exact || point(seam.end_vertex_id)?.sub(high).length() > exact {
        return Err(NOT);
    }
    for step in 0..=8 {
        let v = step as f64 / 8.0;
        if seam.curve.evaluate(v).map_err(|_| NOT)?.sub(at(0.0, v)?).length() > exact
            || (at(0.37, v)?.sub(centre).length() - radius).abs() > exact
        {
            return Err(NOT);
        }
    }
    Ok(Ball { face, centre, axis, radius: *radius, low_pole, high_pole, seam })
}

/// The block's face that cuts the ball, with its outward unit normal.
fn cutting_face<'a>(block: &'a BrepSolid, ball: &Ball, margin: f64) -> Result<(&'a FaceRecord, Vec3), Decline> {
    const NOT: Decline = "the tool is not a convex six-faced block";
    let [shell] = block.shells.as_slice() else { return Err(NOT) };
    if shell.faces.len() != 6 || block.vertices.len() != 8 || block.edges.len() != 12 || block.genus != 0 {
        return Err(NOT);
    }
    let scale = block.vertices.iter().map(|vertex| vertex.point.sub(ball.centre).length()).fold(ball.radius, f64::max);
    let mut cutting = None;
    for face in &shell.faces {
        let Some(AnalyticSurface::Plane { origin, u_dir, v_dir, .. }) = face.surface.analytic() else { return Err(NOT) };
        let natural = u_dir.cross(*v_dir).normalized().map_err(|_| NOT)?;
        let outward = if face.same_sense { natural } else { natural.scale(-1.0) };
        // Convex: no vertex of the block is outside any of its planes.
        if block.vertices.iter().any(|vertex| vertex.point.sub(*origin).dot(outward) > 1e-9 * scale) {
            return Err(NOT);
        }
        let height = ball.centre.sub(*origin).dot(outward);
        if height < -(ball.radius + margin) {
            continue;
        }
        if height > ball.radius - margin {
            return Err("the ball is outside or tangent to a face of the block");
        }
        if !(height.abs() < ball.radius - margin) || cutting.is_some() {
            return Err("more than one face of the block reaches the ball");
        }
        cutting = Some((face, outward));
    }
    cutting.ok_or("no face of the block cuts the ball")
}

/// A line in parameter space over the parameter range `[t0, t1]`.
fn ranged_line(from: (f64, f64), to: (f64, f64), t0: f64, t1: f64) -> Result<NurbsCurve, Decline> {
    let control = |(u, v): (f64, f64)| Vec4 { x: u, y: v, z: 0.0, w: 1.0 };
    NurbsCurve::new(1, vec![t0, t0, t1, t1], vec![control(from), control(to)]).map_err(|_| "a seam pcurve does not build")
}

/// `ball ∩ block` (`inside`) or `ball − block`.
pub(super) fn cut(ball_solid: &BrepSolid, block: &BrepSolid, inside: bool, policy: &KernelTolerances) -> Result<Built, Decline> {
    let radius = recognise(ball_solid)?.radius;
    let margin = (1e3 * policy.sew_search).max(1e-3 * radius);
    cutting_face(block, &recognise(ball_solid)?, margin)?;
    let (ball_owned, block_owned) =
        super::super::prepared_operands(ball_solid, block, policy).map_err(|_| "operand preparation refuses")?;
    let ball = recognise(&ball_owned)?;
    let (tool_face, outward) = cutting_face(&block_owned, &ball, margin)?;
    const BUILD: Decline = "the cut's geometry does not build";
    let along = outward.dot(ball.axis);
    if along.abs() < 1.0 - 1e-12 {
        return Err("the cutting plane is not square to the ball's pole axis");
    }
    let Some(AnalyticSurface::Plane { origin, u_dir, v_dir, .. }) = tool_face.surface.analytic() else { return Err(BUILD) };
    // The plane's level along the pole axis from the centre, and the side
    // kept: inside the block is against `outward`.
    let level = origin.sub(ball.centre).dot(ball.axis);
    let keep_high = (along > 0.0) != inside;
    // The latitude parameter of that level: the axis coordinate rises with v.
    let surface = &ball.face.surface;
    let height = |v: f64| surface.evaluate(0.0, v).map(|point| point.sub(ball.centre).dot(ball.axis)).map_err(|_| BUILD);
    let (mut below, mut above) = (0.0_f64, 1.0_f64);
    for _ in 0..80 {
        let middle = 0.5 * (below + above);
        if height(middle)? < level { below = middle } else { above = middle }
    }
    let v = 0.5 * (below + above);
    if !(v > 1e-6 && v < 1.0 - 1e-6) || (height(v)? - level).abs() > 1e-12 * ball.radius {
        return Err("the cut is at a pole");
    }
    // The surface's own circle of latitude. Off the equator its weights
    // carry the meridian's weight at `v` as a common factor; divided out, it
    // is the same curve with a circle's usual weights (which is what lets a
    // reader of the curve alone see a circle).
    let circle = surface.iso_curve_v(v).map_err(|_| BUILD)?;
    let common = circle.control_points.first().map(|control| control.w).filter(|weight| *weight > 0.0).ok_or(BUILD)?;
    let controls = circle
        .control_points
        .iter()
        .map(|control| Vec4 { x: control.x / common, y: control.y / common, z: control.z / common, w: control.w / common })
        .collect();
    let circle = NurbsCurve::new(circle.degree, circle.knots.clone(), controls).map_err(|_| BUILD)?;
    let start = surface.evaluate(0.0, v).map_err(|_| BUILD)?;
    let quarter = surface.evaluate(0.25, v).map_err(|_| BUILD)?;
    let middle = ball.centre.add(ball.axis.scale(level));
    let anticlockwise = start.sub(middle).cross(quarter.sub(middle)).dot(ball.axis) > 0.0;
    let line = |u0: f64, v0: f64, u1: f64, v1: f64| parameter_line(u0, v0, u1, v1).map_err(|_| BUILD);

    let pole_vertex = if keep_high { ball.seam.end_vertex_id } else { ball.seam.start_vertex_id };
    let pole_point = ball_owned.vertices.iter().find(|vertex| vertex.id == pole_vertex).ok_or(BUILD)?.point;
    let rim_vertex = ball_owned.vertices.iter().map(|vertex| vertex.id).max().unwrap_or(0) + 1;
    let rim_edge = ball_owned.edges.iter().map(|edge| edge.id).max().unwrap_or(0) + 1;
    let pole = if keep_high { ball.high_pole } else { ball.low_pole };
    let pole_edge = ball_owned.edges.iter().find(|edge| edge.id == pole.edge_id).ok_or(BUILD)?.clone();
    // The kept piece of the seam: the seam's own curve over its range.
    let (t0, t1) = if keep_high { (v, 1.0) } else { (0.0, v) };
    let seam = EdgeRecord {
        t0,
        t1,
        start_vertex_id: if keep_high { rim_vertex } else { pole_vertex },
        end_vertex_id: if keep_high { pole_vertex } else { rim_vertex },
        // Pieces of one edge after the first are numbered.
        name: ball.seam.name.as_ref().map(|name| if keep_high { format!("{name}_1") } else { name.clone() }),
        ..ball.seam.clone()
    };
    let seam_up = CoedgeRecord { id: 0, edge_id: seam.id, forward: true, pcurve: ranged_line((1.0, t0), (1.0, t1), t0, t1)? };
    let seam_down = CoedgeRecord {
        id: 0,
        edge_id: seam.id,
        forward: false,
        pcurve: ranged_line((0.0, t0), (0.0, t1), t0, t1)?.reversed().map_err(|_| BUILD)?,
    };
    let rim = EdgeRecord {
        id: rim_edge,
        curve: circle.clone(),
        t0: 0.0,
        t1: 1.0,
        start_vertex_id: rim_vertex,
        end_vertex_id: rim_vertex,
        degenerate: false,
        // A section edge is named after the two faces it is between.
        name: match (&ball.face.name, &tool_face.name) {
            // (in the order the two names sort).
                (Some(a), Some(b)) => Some(if a <= b { format!("{a}|{b}") } else { format!("{b}|{a}") }),
            _ => None,
        },
    };
    let coedges = if keep_high {
        vec![seam_up, pole.clone(), seam_down, CoedgeRecord { id: 0, edge_id: rim_edge, forward: true, pcurve: line(0.0, v, 1.0, v)? }]
    } else {
        vec![pole.clone(), seam_up, CoedgeRecord { id: 0, edge_id: rim_edge, forward: false, pcurve: line(1.0, v, 0.0, v)? }, seam_down]
    };
    let dome = FaceRecord { loops: vec![LoopRecord { id: 0, coedges }], ..ball.face.clone() };
    // The disc: the block's face, facing out of the kept piece, its one loop
    // anticlockwise about that normal.
    let normal_along_axis = !keep_high;
    let forward = anticlockwise == normal_along_axis;
    let flat = in_plane(&circle, *origin, *u_dir, *v_dir)?;
    let disc = FaceRecord {
        id: 0,
        surface: tool_face.surface.clone(),
        same_sense: tool_face.same_sense == inside,
        loops: vec![LoopRecord {
            id: 0,
            coedges: vec![CoedgeRecord { id: 0, edge_id: rim_edge, forward, pcurve: if forward { flat } else { flat.reversed().map_err(|_| BUILD)? } }],
        }],
        name: tool_face.name.clone(),
    };
    let mut result = ball_owned.clone();
    result.vertices = vec![VertexRecord { id: rim_vertex, point: start }, VertexRecord { id: pole_vertex, point: pole_point }];
    result.edges = vec![seam, pole_edge, rim];
    result.shells[0].faces = vec![dome, disc];
    super::renumber(&mut result);
    result.mass_properties_cache = Default::default();
    super::super::refresh_derived_genus(&mut result);
    let faces = &result.shells[0].faces;
    let touched = faces.iter().map(|face| face.id).collect();
    let operand_of = [(faces[0].id, 0), (faces[1].id, 1)].into_iter().collect();
    Ok(Built { solid: result, touched, operand_of })
}