use super::analyze::{edge_and_faces, face_plane_normal};
use super::edges::resolve_edge_by_point;
use crate::topology::{BrepSolid, FaceRecord};
use crate::{KernelRefusal, KernelStage, Vec3};
pub const PARALLEL_WALL_LIMIT_WHAT: &str = "fillet_wider_than_parallel_walls";
fn is_plane(face: &FaceRecord) -> bool {
let s = &face.surface;
if !(s.degree_u == 1 && s.degree_v == 1 && s.control_points.len() == 2 && s.control_points[0].len() == 2) {
return false;
}
let Some(c) = [s.control_points[0][0], s.control_points[0][1], s.control_points[1][0], s.control_points[1][1]]
.iter()
.map(|p| p.point().ok())
.collect::<Option<Vec<_>>>()
else {
return false;
};
let (a, b) = (c[1].sub(c[0]), c[2].sub(c[0]));
let Ok(n) = a.cross(b).normalized() else { return false };
let size = a.length().max(b.length()).max(c[3].sub(c[0]).length());
n.dot(c[3].sub(c[0])).abs() <= 1e-12 * size.max(1e-300)
}
pub fn pinch_refusal(solid: &BrepSolid, edge_points: &[Vec3], radius: f64) -> Option<KernelRefusal> {
if edge_points.len() < 2 || !(radius > 0.0) {
return None;
}
let mut edges = Vec::new();
for point in edge_points {
let id = resolve_edge_by_point(solid, *point).ok()?;
let (edge, faces) = edge_and_faces(solid, id).ok()?;
if edge.curve.degree != 1 || faces.len() != 2 || !faces.iter().all(|f| is_plane(f)) {
continue;
}
let (a, b) = (edge.curve.evaluate(edge.t0).ok()?, edge.curve.evaluate(edge.t1).ok()?);
let Ok(direction) = b.sub(a).normalized() else { continue };
let middle = a.add(b).scale(0.5);
edges.push((id, middle, direction, [faces[0].clone(), faces[1].clone()], [a, b]));
}
let (lo, hi) = solid.vertices.iter().fold(([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]), |(lo, hi), v| {
let p = [v.point.x, v.point.y, v.point.z];
([lo[0].min(p[0]), lo[1].min(p[1]), lo[2].min(p[2])], [hi[0].max(p[0]), hi[1].max(p[1]), hi[2].max(p[2])])
});
let scale = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt().max(1e-300);
for i in 0..edges.len() {
for j in i + 1..edges.len() {
let (ia, pa, da, fa, ends_a) = &edges[i];
let (ib, pb, db, fb, ends_b) = &edges[j];
if ia == ib || da.cross(*db).length() > 1e-9 {
continue;
}
let span = |ends: &[Vec3; 2]| {
let (s0, s1) = (ends[0].dot(*da), ends[1].dot(*da));
(s0.min(s1), s0.max(s1))
};
let ((a0, a1), (b0, b1)) = (span(ends_a), span(ends_b));
if !(a1.min(b1) - a0.max(b0) > 0.0) {
continue;
}
let Some((shared_a, shared_b)) = (0..2).flat_map(|x| (0..2).map(move |y| (x, y))).find(|&(x, y)| fa[x].id == fb[y].id) else { continue };
let (shared, wall_a, wall_b) = (&fa[shared_a], &fa[1 - shared_a], &fb[1 - shared_b]);
let (Ok((_, n_shared)), Ok((on_a, n_a)), Ok((on_b, n_b))) = (face_plane_normal(shared, *pa), face_plane_normal(wall_a, *pa), face_plane_normal(wall_b, *pb)) else { continue };
if !(n_a.dot(n_b) <= -1.0 + 1e-9) {
continue;
}
let setback = |n_wall: Vec3| -> Option<f64> {
let between = n_shared.dot(n_wall).clamp(-1.0, 1.0).acos();
let inside = std::f64::consts::PI - between;
(inside > 1e-9 && inside < std::f64::consts::PI - 1e-9).then(|| radius / (0.5 * inside).tan())
};
let (Some(sa), Some(sb)) = (setback(n_a), setback(n_b)) else { continue };
let midway = pa.add(pb.sub(*pa).scale(0.5));
let between = crate::project_point_to_surface(&shared.surface, midway)
.ok()
.filter(|q| q.distance <= 1e-9 * scale)
.and_then(|q| crate::parameter_point_in_face(shared, crate::Vec2 { x: q.u, y: q.v }, 1e-9).ok())
.is_some_and(|class| class == crate::PolygonClass::Inside);
if !between {
continue;
}
let across = pb.sub(*pa);
let width = across.sub(da.scale(across.dot(*da))).length();
let walls = on_b.sub(on_a).dot(n_a).abs();
if sa + sb <= width * (1.0 + 1e-9) + 1e-12 * scale {
continue;
}
if (2.0 * radius - walls).abs() <= 1e-9 * walls.max(1e-300) + 1e-12 * scale {
continue; }
return Some(KernelRefusal::input(
KernelStage::Collect,
PARALLEL_WALL_LIMIT_WHAT,
format!(
"fillet: no ball of radius {radius} fits: edges {ia} and {ib} lie {width:.9} apart on face {}, their blends would need {:.9} of it, and the walls beyond are parallel {walls:.9} apart, so a ball rolling on both needs radius {:.9}",
shared.id,
sa + sb,
0.5 * walls
),
));
}
}
None
}