use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use super::Context;
use super::bevel::{classify_bevel, proved_bevel_planes, transverse_corner};
use super::cylinders::CylinderEvidence;
use super::evidence::{self, EvidenceError, Occurrence};
use super::placed::{Grid, Placed};
use super::policy::AXIS_ALIGNED_COS;
use super::turned::{self, cone_rims};
use crate::kernel::brep::Part;
use crate::kernel::classify::material_at;
use crate::kernel::geom::{self, COORD_FLOOR, Surface, V3, dominant_axis};
use crate::kernel::py;
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct Chamfer {
pub axis: char,
pub leg1: f64,
pub leg2: f64,
pub angle: f64,
pub at: Placed<V3>,
pub turned: bool,
pub corner: Option<Placed<V3>>,
}
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct ChamferOptions {
pub tol: Option<f64>,
pub max_leg_frac: f64,
pub include_planar: bool,
}
impl Default for ChamferOptions {
fn default() -> Self {
ChamferOptions {
tol: None,
max_leg_frac: 0.45,
include_planar: true,
}
}
}
internal_entry! {
pub fn discover_verified(
ctx: &Context<'_>,
opts: &ChamferOptions,
) -> Result<Vec<Occurrence<Chamfer>>, EvidenceError> {
evidence::verified(ctx.part, discover(ctx, opts))
}
}
internal_entry! {
pub fn recognise_chamfers(part: &Part, opts: &ChamferOptions) -> Vec<Chamfer> {
discover(&Context::new(part), opts)
.into_iter()
.map(|o| o.record)
.collect()
}
}
fn below_minimum(value: f64, minimum: f64) -> bool {
value < minimum && (value - minimum).abs() > COORD_FLOOR
}
fn chamfer(
axis: usize,
leg_hi: f64,
leg_lo: f64,
at: V3,
turned: bool,
corner: Option<V3>,
) -> Chamfer {
Chamfer {
axis: ['x', 'y', 'z'][axis],
leg1: py::round_to3(leg_hi),
leg2: py::round_to3(leg_lo),
angle: py::round_to(leg_lo.atan2(leg_hi).to_degrees(), 2),
at: Placed::new(at, Grid::Decimals(3)),
turned,
corner: corner.map(|c| Placed::new(c, Grid::Decimals(3))),
}
}
internal_entry! {
pub fn discover(ctx: &Context<'_>, opts: &ChamferOptions) -> Vec<Occurrence<Chamfer>> {
let part = ctx.part;
let tol = opts.tol.unwrap_or(0.0);
let max_leg = opts.max_leg_frac * ctx.bounds().max_extent();
let mut out = Vec::new();
if opts.include_planar {
out.extend((0..part.faces.len()).filter_map(|f| {
planar(ctx, f, tol, max_leg).or_else(|| rolled_planar(ctx, f, tol, max_leg))
}));
}
prune_polygon_sides(part, &mut out);
let external = turned::external_cylinders(ctx);
out.extend((0..part.faces.len()).filter_map(|f| turned(part, f, tol, max_leg, &external)));
for o in &mut out {
if let Some(corner) = o.record.corner {
let r = &o.record;
o.record.corner = super::bevel::proved_published_corner(ctx, &o.defining,
match r.axis {'x'=>0,'y'=>1,_=>2}, *r.at.raw(), *corner.raw(),
[r.leg1,r.leg2], r.angle);
}
}
out.sort_by(|a, b| {
a.record
.axis
.cmp(&b.record.axis)
.then_with(|| py::tuple_order(&a.record.at[..], &b.record.at[..]))
});
let rims: Vec<Occurrence<Chamfer>> = (0..part.faces.len())
.filter(|f| !out.iter().any(|o| o.defining.contains(f)))
.filter_map(|f| cone_body_rim(part, f, tol, max_leg))
.collect();
out.extend(rims);
out
}
}
fn lateral_planes(part: &Part, face: usize, run: V3) -> Vec<usize> {
part.neighbours(face)
.into_iter()
.filter(|&n| matches!(part.faces[n].surface, Surface::Plane { .. }))
.filter(|&n| {
part.shared_edges(face, n).into_iter().any(|e| {
let edge = &part.edges[e];
let span = geom::sub(edge.end, edge.start);
matches!(edge.curve, geom::Curve::Line { .. })
&& geom::norm(geom::cross(span, run)) <= 1e-6 * geom::norm(span)
})
})
.collect()
}
fn closes_convexly(part: &Part, run: V3, start: usize, from: usize, via: usize) -> bool {
let convex = |a: usize, b: usize| part.arc(a, b) == Some(crate::kernel::brep::Arc::Convex);
let (mut previous, mut current) = (from, via);
for _ in 0..part.faces.len() {
if current == start {
return true;
}
if !convex(current, previous) {
return false;
}
let onward: Vec<usize> = lateral_planes(part, current, run)
.into_iter()
.filter(|&n| n != previous)
.collect();
let [next] = onward[..] else { return false };
(previous, current) = (current, next);
}
false
}
const POLYGON_SIDE_SHARE: f64 = 1. / 3.;
fn prune_polygon_sides(part: &Part, out: &mut Vec<Occurrence<Chamfer>>) {
loop {
let bevels: Vec<usize> = out
.iter()
.filter(|o| !o.record.turned)
.map(|o| o.defining[0])
.collect();
let before = out.len();
out.retain(|o| {
if o.record.turned {
return true;
}
let bevel = o.defining[0];
let mut run = [0.; 3];
run[match o.record.axis {
'x' => 0,
'y' => 1,
_ => 2,
}] = 1.;
let walls = lateral_planes(part, bevel, run)
.into_iter()
.filter(|&wall| part.arc(bevel, wall) == Some(crate::kernel::brep::Arc::Convex));
walls.into_iter().all(|wall| {
let Some(wall_normal) = super::planes::unit_plane_normal(part, wall) else {
return true;
};
let across = geom::cross(run, wall_normal);
let width = |face: usize| {
let (lo, hi) = part.extent_along(&[face], across);
hi - lo
};
if width(bevel) <= POLYGON_SIDE_SHARE * width(wall) {
return true;
}
lateral_planes(part, wall, run).into_iter().all(|far| {
far == bevel
|| bevels.contains(&far)
|| part.arc(wall, far) != Some(crate::kernel::brep::Arc::Convex)
|| super::planes::unit_plane_normal(part, far)
.is_none_or(|n| geom::dot(n, wall_normal).abs() <= 1e-6)
|| !closes_convexly(part, run, bevel, wall, far)
})
})
});
if out.len() == before {
return;
}
}
}
fn planar(ctx: &Context<'_>, face: usize, tol: f64, max_leg: f64) -> Option<Occurrence<Chamfer>> {
let part = ctx.part;
let bevel = classify_bevel(part, face).ok()?;
let centre = bevel.bounds.centre();
if below_minimum(bevel.leg_lo, tol) || bevel.leg_hi > max_leg {
return None;
}
let planes = proved_bevel_planes(ctx, face, centre, bevel.edge_axis)?;
let corner = [0, 1, 2].map(|i| {
if i == bevel.edge_axis {
centre[i]
} else {
planes[&i]
}
});
let at = part.face_centre(face)?;
Some(Occurrence {
record: chamfer(
bevel.edge_axis,
bevel.leg_hi,
bevel.leg_lo,
at,
false,
Some(corner),
),
defining: vec![face],
context: vec![],
})
}
fn rolled_planar(
ctx: &Context<'_>,
face: usize,
tol: f64,
max_leg: f64,
) -> Option<Occurrence<Chamfer>> {
use super::planes::unit_plane_normal;
use crate::kernel::geom::SMOOTH_ARC_GAP;
let part = ctx.part;
let Surface::Plane { .. } = part.faces[face].surface else {
return None;
};
let axis = classify_bevel(part, face).ok()?.edge_axis;
if !super::planes::linear_quad(part, face) {
return None;
}
let normal = unit_plane_normal(part, face)?;
let at = part.face_centre(face)?;
let mut run = [0.; 3];
run[axis] = 1.;
let corner = transverse_corner(part, face, at, run)?;
let area = part.face_mass(face)?[0];
if corner
.areas
.iter()
.any(|&support| !super::policy::clears_threshold(support, area))
{
return None;
}
let supports = corner.normals;
let corner = corner.point;
if supports
.iter()
.any(|&n| geom::dot(normal, n) <= SMOOTH_ARC_GAP)
|| geom::dot(geom::sub(at, corner), normal) >= -COORD_FLOOR
{
return None;
}
if !supports
.iter()
.any(|n| n.iter().all(|c| c.abs() < AXIS_ALIGNED_COS))
{
return None;
}
let distance = geom::dot(geom::sub(at, corner), normal).abs();
let legs = supports.map(|n| {
let tangent = geom::cross(run, n);
distance * geom::norm(tangent) / geom::dot(tangent, normal).abs()
});
let (leg_lo, leg_hi) = (legs[0].min(legs[1]), legs[0].max(legs[1]));
if below_minimum(leg_lo, tol) || leg_hi > max_leg || leg_lo <= COORD_FLOOR {
return None;
}
let near = geom::add(
corner,
geom::scale(geom::sub(at, corner), super::policy::INTERIOR_PROBE_FRAC),
);
if material_at(ctx.classifier(), near) {
return None;
}
Some(Occurrence {
record: chamfer(axis, leg_hi, leg_lo, at, false, Some(corner)),
defining: vec![face],
context: vec![],
})
}
fn turned(
part: &Part,
face: usize,
tol: f64,
max_leg: f64,
external: &BTreeMap<usize, &CylinderEvidence>,
) -> Option<Occurrence<Chamfer>> {
let Surface::Cone { frame, .. } = part.faces[face].surface else {
return None;
};
let ((minor_r, minor_c), (major_r, major_c), _) = cone_rims(part, face)?;
let d = frame.z;
let edge_axis = dominant_axis(d.map(f64::abs));
if d[edge_axis].abs() < AXIS_ALIGNED_COS {
return None;
}
let radial = major_r - minor_r;
let axial = geom::dot(geom::sub(major_c, minor_c), d).abs();
let (leg_hi, leg_lo) = (axial.max(radial), axial.min(radial));
if below_minimum(leg_lo, tol) || leg_hi > max_leg {
return None;
}
let neighbours = part.neighbours(face);
let coaxial = turned::coaxial_cylinders(&neighbours, external, frame.origin, d);
if coaxial.is_empty() {
return None;
}
let transverse = !turned::transverse_planes(part, &neighbours, d).is_empty();
if !transverse && !turned::bridges_two_bands(&coaxial) {
return None; }
let at = part.face_centre(face)?;
Some(Occurrence {
record: chamfer(edge_axis, leg_hi, leg_lo, at, true, None),
defining: vec![face],
context: vec![],
})
}
const CONE_RIM_EQUAL_LEGS: f64 = 0.0015;
fn cone_body_rim(part: &Part, face: usize, tol: f64, max_leg: f64) -> Option<Occurrence<Chamfer>> {
let Surface::Cone {
frame: band,
semi_angle: band_angle,
..
} = part.faces[face].surface
else {
return None;
};
let d = band.z;
let edge_axis = dominant_axis(d.map(f64::abs));
if d[edge_axis].abs() < AXIS_ALIGNED_COS {
return None;
}
let axial = |p: V3| geom::dot(geom::sub(p, band.origin), d);
let rim_with = |other: usize| {
part.shared_edges(face, other)
.into_iter()
.find_map(|e| match part.edges[e].curve {
geom::Curve::Circle { frame, radius } => Some((radius, axial(frame.origin))),
_ => None,
})
};
let slope = |frame: crate::kernel::geom::Frame, angle: f64| angle.tan() * geom::dot(frame.z, d);
let mut plane = None;
let mut body = None;
for n in part.neighbours(face) {
if part.arc(face, n) != Some(crate::kernel::brep::Arc::Convex) {
continue;
}
let surface = &part.faces[n].surface;
if let Surface::Plane { frame } = surface
&& geom::dot(frame.z, d).abs() > AXIS_ALIGNED_COS
{
if plane.replace((n, *frame)).is_some() {
return None;
}
} else if let Surface::Cone {
frame,
radius,
semi_angle,
} = surface
&& geom::dot(frame.z, d).abs() > 1. - 1e-9
&& geom::norm(geom::cross(geom::sub(frame.origin, band.origin), d)) <= COORD_FLOOR
&& (slope(*frame, *semi_angle) - slope(band, band_angle)).abs() > 1e-6
&& body.replace((n, *frame, *radius, *semi_angle)).is_some()
{
return None;
}
}
let ((plane_face, plane_frame), (body_face, body_frame, body_radius, body_angle)) =
(plane?, body?);
let (r_plane, z_plane) = rim_with(plane_face)?;
let (r_body, z_body) = rim_with(body_face)?;
let r_corner = body_radius
+ geom::dot(
geom::sub(plane_frame.origin, body_frame.origin),
body_frame.z,
) * body_angle.tan();
if r_plane <= 0. || r_body <= 0. || r_corner <= r_plane {
return None;
}
let leg_plane = r_corner - r_plane;
let leg_body = (r_corner - r_body).hypot(z_plane - z_body);
let slant = match turned::cone_rims(part, body_face) {
Some(((r0, c0), (r1, c1), _)) => (r1 - r0).hypot(geom::dot(geom::sub(c1, c0), d)),
None => r_body / body_angle.sin().abs(),
};
let (leg_hi, leg_lo) = (leg_plane.max(leg_body), leg_plane.min(leg_body));
if below_minimum(leg_lo, tol)
|| leg_hi > max_leg
|| leg_hi - leg_lo > CONE_RIM_EQUAL_LEGS
|| leg_body >= slant * (1. - 1e-9)
{
return None;
}
let at = part.face_centre(face)?;
Some(Occurrence {
record: chamfer(edge_axis, leg_hi, leg_lo, at, true, None),
defining: vec![face],
context: vec![],
})
}