use std::cmp::Ordering;
use std::collections::BTreeSet;
use serde::{Deserialize, Serialize};
use super::Context;
use super::body::BodyKey;
use super::evidence::{self, EvidenceError, Occurrence};
use super::placed::{Grid, Placed};
use super::policy::{AXIS_ALIGNED_COS, AXIS_ZERO_COS, clears_threshold, cluster_coordinates};
use crate::kernel::brep::Part;
use crate::kernel::geom::{Bounds, COORD_FLOOR, Surface};
use crate::kernel::py;
const TOL: f64 = 0.5;
const STEP_MIN_AREA_FRAC: f64 = 0.01;
const STRUCTURAL_RAMP_MIN_FRAC: f64 = 0.1;
const BOUNDED_RISER_AREA_FRAC: f64 = 0.5;
const STEP_LADDER_BOUNDARY_MARGIN: f64 = 0.6;
const END_MARGIN_MAX_FRAC: f64 = 0.25;
const AGGREGATE_RISER_MIN_AREA_FRAC: f64 = 0.15;
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct FaceLevel {
pub z: f64,
pub x_span: Option<(f64, f64)>,
pub y_span: Option<(f64, f64)>,
pub body_key: Option<BodyKey>,
#[serde(skip_serializing_if = "is_z")]
pub height_axis: char,
}
fn is_z(axis: &char) -> bool {
*axis == 'z'
}
fn axis_rank(axis: char) -> usize {
match axis {
'z' => 0,
'x' => 1,
_ => 2,
}
}
const LETTERS: [char; 3] = ['x', 'y', 'z'];
internal_entry! {
pub fn plane_axes(height: usize) -> [usize; 3] {
[(height + 1) % 3, (height + 2) % 3, height]
}
}
impl FaceLevel {
fn order(&self, other: &Self) -> Ordering {
let span = |s: &Option<(f64, f64)>| s.map(|(a, b)| vec![a, b]).unwrap_or_default();
axis_rank(self.height_axis)
.cmp(&axis_rank(other.height_axis))
.then(py::order(self.z, other.z))
.then(self.x_span.is_some().cmp(&other.x_span.is_some()))
.then_with(|| py::tuple_order(&span(&self.x_span), &span(&other.x_span)))
.then(self.y_span.is_some().cmp(&other.y_span.is_some()))
.then_with(|| py::tuple_order(&span(&self.y_span), &span(&other.y_span)))
.then(self.body_key.is_some().cmp(&other.body_key.is_some()))
.then_with(|| key_order(&self.body_key, &other.body_key))
}
}
fn values(positions: &[Placed<f64>]) -> Vec<f64> {
positions.iter().map(|p| **p).collect()
}
fn key_order(a: &Option<BodyKey>, b: &Option<BodyKey>) -> Ordering {
py::tuple_order(
a.as_ref().map_or(&[][..], |k| k.as_slice()),
b.as_ref().map_or(&[][..], |k| k.as_slice()),
)
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct RiserEvidence {
pub vertical: bool,
pub axis: char,
pub positions: Vec<Placed<f64>>,
pub other_axis: char,
pub other_positions: Vec<Placed<f64>>,
pub z_lo: f64,
pub z_hi: f64,
pub lo_at_envelope: bool,
pub hi_at_envelope: bool,
pub tol: f64,
pub body_levels: Vec<FaceLevel>,
pub body_key: Option<BodyKey>,
#[serde(skip_serializing_if = "is_z")]
pub height_axis: char,
}
impl RiserEvidence {
fn order(&self, other: &Self) -> Ordering {
axis_rank(self.height_axis)
.cmp(&axis_rank(other.height_axis))
.then(self.vertical.cmp(&other.vertical))
.then(self.axis.cmp(&other.axis))
.then_with(|| py::tuple_order(&values(&self.positions), &values(&other.positions)))
.then(self.other_axis.cmp(&other.other_axis))
.then_with(|| {
py::tuple_order(
&values(&self.other_positions),
&values(&other.other_positions),
)
})
.then(py::order(self.z_lo, other.z_lo))
.then(py::order(self.z_hi, other.z_hi))
.then(self.lo_at_envelope.cmp(&other.lo_at_envelope))
.then(self.hi_at_envelope.cmp(&other.hi_at_envelope))
.then(py::order(self.tol, other.tol))
.then_with(|| {
self.body_levels
.iter()
.zip(&other.body_levels)
.map(|(a, b)| a.order(b))
.find(|o| o.is_ne())
.unwrap_or(self.body_levels.len().cmp(&other.body_levels.len()))
})
.then(self.body_key.is_some().cmp(&other.body_key.is_some()))
.then_with(|| key_order(&self.body_key, &other.body_key))
}
}
#[derive(Clone, Copy, Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct FaceLevelOptions {
pub tol: Option<f64>,
pub min_area_frac: f64,
}
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct RiserOptions {
pub min_area_frac: f64,
pub tol: Option<f64>,
}
impl Default for RiserOptions {
fn default() -> Self {
RiserOptions {
min_area_frac: 0.15,
tol: None,
}
}
}
struct Scope {
faces: Vec<usize>,
bounds: Bounds,
key: Option<BodyKey>,
solid: Option<usize>,
}
fn scopes(ctx: &Context<'_>) -> Vec<Scope> {
let part = ctx.part;
if part.solids.is_empty() {
return vec![Scope {
faces: (0..part.faces.len()).collect(),
bounds: part.bounds(),
key: None,
solid: None,
}];
}
let keys = ctx.body_keys(true);
part.solids
.iter()
.enumerate()
.map(|(s, solid)| Scope {
faces: solid.faces.clone(),
bounds: part.solid_bounds(s),
key: keys[s].clone(),
solid: Some(s),
})
.collect()
}
fn level_proposals(
part: &Part,
scope: &Scope,
height: usize,
tol: f64,
min_area_frac: f64,
) -> Vec<(FaceLevel, Vec<usize>)> {
let [u, v, h] = plane_axes(height);
let mut zs = Vec::new();
let mut faces = Vec::new();
for &f in &scope.faces {
if let Surface::Plane { frame } = part.faces[f].surface
&& frame.z[h].abs() > AXIS_ALIGNED_COS
&& flat_along(part, f, h)
{
zs.push(frame.origin[h]);
faces.push(f);
}
}
let b = &scope.bounds;
let threshold = min_area_frac * (b.max[u] - b.min[u]) * (b.max[v] - b.min[v]);
let mut out = Vec::new();
for cluster in cluster_coordinates(&zs, tol) {
if min_area_frac > 0.0 {
let areas: Option<Vec<f64>> = cluster
.iter()
.map(|&i| part.face_mass(faces[i]).map(|m| m[0]))
.collect();
if !areas.is_some_and(|a| clears_threshold(py::sum(a), threshold)) {
continue;
}
}
let spans: Vec<Bounds> = cluster
.iter()
.map(|&i| part.face_bounds(faces[i]))
.collect();
let fold = |i: usize, max: bool| {
let pick = |b: &Bounds| if max { b.max[i] } else { b.min[i] };
let mut it = spans.iter().map(pick);
let first = it.next().unwrap();
it.fold(first, |a, x| {
let better = if max { x > a } else { x < a };
if better { x } else { a }
})
};
out.push((
FaceLevel {
z: zs[cluster[py::first_min(&cluster, |&i| zs[i])]],
x_span: Some((fold(u, false), fold(u, true))),
y_span: Some((fold(v, false), fold(v, true))),
body_key: scope.key.clone(),
height_axis: LETTERS[h],
},
cluster.iter().map(|&i| faces[i]).collect(),
));
}
out
}
internal_entry! {
pub fn recognise_face_levels(part: &Part, opts: &FaceLevelOptions) -> Vec<FaceLevel> {
face_levels_with_faces(part, opts)
.into_iter()
.map(|(level, _)| level)
.collect()
}
}
internal_entry! {
pub fn face_levels_with_faces(
part: &Part,
opts: &FaceLevelOptions,
) -> Vec<(FaceLevel, Vec<usize>)> {
let ctx = Context::new(part);
let tol = opts.tol.unwrap_or(TOL);
let mut out: Vec<(FaceLevel, Vec<usize>)> = scopes(&ctx)
.iter()
.flat_map(|scope| level_proposals(part, scope, 2, tol, opts.min_area_frac))
.collect();
out.sort_by(|a, b| a.0.order(&b.0));
out
}
}
fn interior_levels(
part: &Part,
scope: &Scope,
height: usize,
margin: f64,
) -> Vec<(FaceLevel, Vec<usize>)> {
let (lo, hi) = (scope.bounds.min[height], scope.bounds.max[height]);
level_proposals(part, scope, height, TOL, STEP_MIN_AREA_FRAC)
.into_iter()
.filter(|(level, _)| lo + margin < level.z && level.z < hi - margin)
.collect()
}
fn body_levels(part: &Part, scope: &Scope, tol: f64) -> Vec<FaceLevel> {
interior_levels(part, scope, 2, tol)
.into_iter()
.map(|(level, _)| level)
.collect()
}
internal_entry! {
pub fn bounded_end_margin(span: f64) -> f64 {
STEP_LADDER_BOUNDARY_MARGIN.min(span.max(0.0) * END_MARGIN_MAX_FRAC)
}
}
fn end_margin(scope: &Scope, height: usize, tol: Option<f64>) -> f64 {
tol.unwrap_or_else(|| bounded_end_margin(scope.bounds.max[height] - scope.bounds.min[height]))
}
internal_entry! {
pub fn step_level_records(part: &Part, tol: Option<f64>) -> Vec<FaceLevel> {
let ctx = Context::new(part);
let mut out: Vec<FaceLevel> = scopes(&ctx)
.iter()
.flat_map(|scope| interior_levels(part, scope, 2, end_margin(scope, 2, tol)))
.map(|(level, _)| level)
.collect();
out.sort_by(|a, b| a.order(b));
out
}
}
internal_entry! {
pub fn discover_step_levels(ctx: &Context<'_>) -> Vec<Occurrence<FaceLevel>> {
let mut out: Vec<Occurrence<FaceLevel>> = scopes(ctx)
.iter()
.flat_map(|scope| interior_levels(ctx.part, scope, 2, end_margin(scope, 2, None)))
.map(|(record, defining)| Occurrence {
record,
defining,
context: Vec::new(),
})
.collect();
out.sort_by(|a, b| a.record.order(&b.record));
out
}
}
internal_entry! {
pub fn discover_risers(
ctx: &Context<'_>,
levels: &[Occurrence<FaceLevel>],
) -> Vec<Occurrence<RiserEvidence>> {
let part = ctx.part;
let body = |o: &Occurrence<FaceLevel>| o.defining.first().and_then(|&f| part.faces[f].solid);
let mut out: Vec<Occurrence<RiserEvidence>> = Vec::new();
for scope in scopes(ctx) {
let own: Vec<FaceLevel> = levels
.iter()
.filter(|o| body(o) == scope.solid)
.map(|o| o.record.clone())
.collect();
for (mut record, defining) in
riser_proposals(part, &scope, 2, AGGREGATE_RISER_MIN_AREA_FRAC, TOL, vec![])
{
record.body_levels = own.clone();
out.push(Occurrence {
record,
defining,
context: Vec::new(),
});
}
}
out.sort_by(|a, b| a.record.order(&b.record));
out
}
}
internal_entry! {
pub fn proved<R>(
part: &Part,
found: Vec<Occurrence<R>>,
local_degradation: bool,
) -> Result<Vec<Occurrence<R>>, EvidenceError> {
if !local_degradation {
return evidence::verified(part, found);
}
Ok(found
.into_iter()
.filter(|o| evidence::locally_valid_solid(part, &o.defining).is_some())
.collect())
}
}
internal_entry! {
pub fn recognise_risers(part: &Part, opts: &RiserOptions) -> Vec<RiserEvidence> {
risers_with_faces(part, opts)
.into_iter()
.map(|(riser, _)| riser)
.collect()
}
}
internal_entry! {
pub fn risers_with_faces(part: &Part, opts: &RiserOptions) -> Vec<(RiserEvidence, Vec<usize>)> {
let ctx = Context::new(part);
let tol = opts.tol.unwrap_or(TOL);
let mut out: Vec<(RiserEvidence, Vec<usize>)> = scopes(&ctx)
.iter()
.flat_map(|scope| {
let levels = body_levels(part, scope, tol);
riser_proposals(part, scope, 2, opts.min_area_frac, tol, levels)
})
.collect();
out.sort_by(|a, b| a.0.order(&b.0));
out
}
}
fn riser_orientation(n: [f64; 3], height: usize) -> Option<(bool, usize)> {
let [u, v, h] = plane_axes(height);
let on_u = n[u].abs() > AXIS_ZERO_COS && n[v].abs() <= AXIS_ZERO_COS;
let on_v = n[v].abs() > AXIS_ZERO_COS && n[u].abs() <= AXIS_ZERO_COS;
if !(on_u || on_v) {
return None;
}
Some((n[h].abs() <= AXIS_ZERO_COS, if on_u { u } else { v }))
}
fn riser_proposals(
part: &Part,
scope: &Scope,
height: usize,
min_area_frac: f64,
tol: f64,
body_levels: Vec<FaceLevel>,
) -> Vec<(RiserEvidence, Vec<usize>)> {
let bb = &scope.bounds;
let ext = |i: usize| bb.max[i] - bb.min[i];
let [u, v, h] = plane_axes(height);
let mut found: Vec<(RiserEvidence, Vec<usize>)> = Vec::new();
for &f in &scope.faces {
let Surface::Plane { frame } = part.faces[f].surface else {
continue;
};
let Some(normal) = part.face_normal(f, 0.0, 0.0) else {
continue;
};
let Some((vertical, axis)) = riser_orientation(normal, height) else {
continue;
};
let fb = part.face_bounds(f);
let other = u + v - axis;
let (flo, fhi) = (fb.min[other], fb.max[other]);
let full_span = flo <= bb.min[other] + tol && fhi >= bb.max[other] - tol;
let interior = |i: usize, p: f64| {
p - bb.min[i] > tol + COORD_FLOOR && bb.max[i] - p > tol + COORD_FLOOR
};
let rise = fb.max[h] - fb.min[h];
let (positions, other_positions) = if vertical {
let pos = frame.origin[axis];
if !full_span || !interior(axis, pos) {
continue;
}
(vec![pos], vec![])
} else {
if tol >= rise {
continue;
}
let along = vec![fb.min[axis], fb.max[axis]];
if full_span {
(along, vec![])
} else if fhi - flo < STRUCTURAL_RAMP_MIN_FRAC * ext(other)
|| along[1] - along[0] < STRUCTURAL_RAMP_MIN_FRAC * ext(axis)
|| STRUCTURAL_RAMP_MIN_FRAC * ext(h) > rise
{
continue; } else {
(along, vec![flo, fhi])
}
};
let cross = ext(other) * ext(h);
let area_floor = if full_span {
min_area_frac * cross
} else {
BOUNDED_RISER_AREA_FRAC * ((fhi - flo) * rise)
};
let Some([area, _]) = part.face_mass(f) else {
continue;
};
if cross <= 0.0 || area < area_floor {
continue;
}
let at_envelope = |z: f64| (z - bb.min[h]).abs() < tol || (z - bb.max[h]).abs() < tol;
let record = RiserEvidence {
vertical,
axis: LETTERS[axis],
positions: positions
.into_iter()
.filter(|&p| interior(axis, p))
.map(|p| Placed::new(p, Grid::Decimals(3)))
.collect(),
other_axis: LETTERS[other],
other_positions: other_positions
.into_iter()
.filter(|&p| interior(other, p))
.map(|p| Placed::new(p, Grid::Decimals(3)))
.collect(),
z_lo: fb.min[h],
z_hi: fb.max[h],
lo_at_envelope: at_envelope(fb.min[h]),
hi_at_envelope: at_envelope(fb.max[h]),
tol,
body_levels: body_levels.clone(),
body_key: scope.key.clone(),
height_axis: LETTERS[h],
};
match found.iter_mut().find(|(r, _)| *r == record) {
Some((_, faces)) => faces.push(f),
None => found.push((record, vec![f])),
}
}
found.sort_by(|a, b| a.0.order(&b.0));
found
}
pub(crate) fn other_axes(
ctx: &Context<'_>,
occupied: &BTreeSet<usize>,
taken: &BTreeSet<usize>,
) -> (Vec<Occurrence<FaceLevel>>, Vec<Occurrence<RiserEvidence>>) {
let part = ctx.part;
let degraded = evidence::local_degradation();
let free = |faces: &[usize], used: &BTreeSet<usize>| {
faces
.iter()
.all(|f| !occupied.contains(f) && !taken.contains(f) && !used.contains(f))
&& (!degraded || evidence::locally_valid_solid(part, faces).is_some())
};
let none = BTreeSet::new();
let mut levels: Vec<Occurrence<FaceLevel>> = Vec::new();
let mut risers: Vec<Occurrence<RiserEvidence>> = Vec::new();
for scope in scopes(ctx) {
let found: Vec<Vec<(FaceLevel, Vec<usize>)>> = [0, 1]
.map(|height| {
interior_levels(part, &scope, height, end_margin(&scope, height, None))
.into_iter()
.filter(|(_, faces)| free(faces, &none))
.filter(|(_, faces)| {
!faces
.iter()
.any(|&f| opposed_wall(ctx, scope.solid, &scope.faces, f, height))
})
.collect()
})
.into();
let used: BTreeSet<usize> = found
.iter()
.flatten()
.flat_map(|(_, faces)| faces.iter().copied())
.collect();
let proposed: Vec<Vec<(RiserEvidence, Vec<usize>)>> = [0, 1]
.into_iter()
.zip(&found)
.map(|(height, own)| {
if own.is_empty() {
return Vec::new();
}
let own_levels: Vec<FaceLevel> = own.iter().map(|(l, _)| l.clone()).collect();
riser_proposals(
part,
&scope,
height,
AGGREGATE_RISER_MIN_AREA_FRAC,
TOL,
own_levels,
)
.into_iter()
.filter(|(_, defining)| free(defining, &used))
.collect()
})
.collect();
let faces_of = |k: usize| -> BTreeSet<usize> {
proposed[k]
.iter()
.flat_map(|(_, faces)| faces.iter().copied())
.collect()
};
let both: BTreeSet<usize> = faces_of(0).intersection(&faces_of(1)).copied().collect();
risers.extend(
proposed
.into_iter()
.flatten()
.filter(|(_, defining)| defining.iter().all(|f| !both.contains(f)))
.map(|(record, defining)| Occurrence {
record,
defining,
context: Vec::new(),
}),
);
levels.extend(
found
.into_iter()
.flatten()
.map(|(record, defining)| Occurrence {
record,
defining,
context: Vec::new(),
}),
);
}
levels.sort_by(|a, b| a.record.order(&b.record));
risers.sort_by(|a, b| a.record.order(&b.record));
(levels, risers)
}
internal_entry! {
pub fn flat_along(part: &Part, f: usize, h: usize) -> bool {
let b = part.face_bounds(f);
b.max[h] - b.min[h] <= TOL
}
}
internal_entry! {
pub fn opposed_wall(ctx: &Context<'_>, solid: Option<usize>, faces: &[usize], f: usize, h: usize) -> bool {
let part = ctx.part;
let [u, v, _] = plane_axes(h);
let (Surface::Plane { frame }, Some(n)) = (&part.faces[f].surface, part.face_normal(f, 0.0, 0.0))
else {
return false;
};
let extent = |b: &Bounds| b.max[h] - b.min[h];
let reach = match solid {
Some(s) => extent(&part.solid_bounds(s)),
None => extent(&part.bounds()),
};
let fb = part.face_bounds(f);
let sign = n[h].signum();
faces.iter().any(|&g| {
if g == f || !flat_along(part, g, h) {
return false;
}
let (Surface::Plane { frame: other }, Some(m)) =
(&part.faces[g].surface, part.face_normal(g, 0.0, 0.0))
else {
return false;
};
let gap = (other.origin[h] - frame.origin[h]) * sign;
if crate::kernel::geom::dot(n, m) >= -AXIS_ALIGNED_COS || gap <= TOL || gap >= reach {
return false;
}
let gb = part.face_bounds(g);
let overlap = |k: usize| (fb.min[k].max(gb.min[k]), fb.max[k].min(gb.max[k]));
let (ou, ov) = (overlap(u), overlap(v));
let (wu, wv) = (ou.1 - ou.0, ov.1 - ov.0);
if wu <= TOL || wv <= TOL {
return false;
}
let area = |b: &Bounds| (b.max[u] - b.min[u]) * (b.max[v] - b.min[v]);
if wu * wv < 0.5 * area(&fb) || wu * wv < 0.5 * area(&gb) || gap >= wu.max(wv) {
return false;
}
let classifier = match solid {
Some(s) => ctx.solid_classifier(s),
None => ctx.classifier(),
};
(1..10).all(|k| {
let mut p = [0.0; 3];
p[u] = 0.5 * (ou.0 + ou.1);
p[v] = 0.5 * (ov.0 + ov.1);
p[h] = frame.origin[h] + (other.origin[h] - frame.origin[h]) * f64::from(k) / 10.0;
classifier.classify(p) == crate::kernel::classify::State::Out
})
})
}
}