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};
struct Ball<'a> {
face: &'a FaceRecord,
centre: Vec3,
axis: Vec3,
radius: f64,
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);
}
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 })
}
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) };
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")
}
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")
}
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) };
let level = origin.sub(ball.centre).dot(ball.axis);
let keep_high = (along > 0.0) != inside;
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");
}
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();
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 },
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,
name: match (&ball.face.name, &tool_face.name) {
(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() };
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 })
}