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;
pub(super) type PipelineAnswer = Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal>;
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")
}
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}")],
};
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()));
}
}
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);
#[doc(hidden)]
pub fn check_disagreements() -> u64 {
DISAGREEMENTS.load(std::sync::atomic::Ordering::Relaxed)
}
pub(super) struct Built {
pub(super) solid: BrepSolid,
pub(super) touched: HashSet<u64>,
pub(super) operand_of: crate::topology::HashMap<u64, u8>,
}
struct Answer {
rule: &'static str,
solid: BrepSolid,
candidates: Option<HashSet<u64>>,
policy: KernelTolerances,
}
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();
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()
}
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")?;
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"),
};
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 });
}
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 })
}
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:?}"))
}
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))
}
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}")
}
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);
}
}
}
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",
}
}