use super::StarFace;
use super::collapse::{Collapse, ErrorRule};
use super::constraint::{Bound, Constraint, ErrorBound};
use crate::Point3;
use crate::common::barycentric::{barycentric_point, closest_barycentric};
use alum::Handle;
pub(super) struct AffineFaceMap;
impl ErrorRule for AffineFaceMap {
fn bound(&self, cx: &Collapse<'_>) -> ErrorBound {
match radius(cx) {
Some(v) => ErrorBound::Bound(v),
None => ErrorBound::Unsatisfiable,
}
}
}
fn radius(cx: &Collapse<'_>) -> Option<f64> {
let Collapse {
star, new, v1, v2, ..
} = *cx;
let mut lower = 0.0f64;
for (i, face) in star.iter().enumerate() {
if face.vanishing {
let third = face.v.iter().position(|v| *v != v1 && *v != v2);
let Some(third) = third else {
continue; };
let c = face.v[third];
let mut best: Option<f64> = None;
for (j, host) in star.iter().enumerate() {
if host.vanishing || !host.v.contains(&c) {
continue;
}
let bound = face_bound(cx, face, &new[j], host)?;
if best.is_none_or(|b| bound < b) {
best = Some(bound);
}
}
lower = lower.max(best?);
} else {
lower = lower.max(face_bound(cx, face, &new[i], face)?);
lower = lower.max(reach_bound(cx, face));
}
}
Some(lower.max(0.0))
}
fn face_bound(
cx: &Collapse<'_>,
face: &StarFace,
target: &[Point3; 3],
host: &StarFace,
) -> Option<f64> {
let Collapse { v1, v2, e, .. } = *cx;
let mut bound = Bound::new();
for k in 0..3 {
let u = face.v[k];
if u != v1 && u != v2 {
continue;
}
let bary = closest_barycentric(&target[0], &target[1], &target[2], &face.p[k]);
let at = barycentric_point(&target[0], &target[1], &target[2], bary);
let need = (at - face.p[k]).norm() + e[u.index() as usize];
let parts = cx.landing_parts(&host.v, &bary);
if !bound.add(Constraint::from_landing(need, parts)) {
return None;
}
}
Some(bound.finish())
}
fn reach_bound(cx: &Collapse<'_>, face: &StarFace) -> f64 {
let Collapse { p0, e, .. } = *cx;
let bary = closest_barycentric(&face.p[0], &face.p[1], &face.p[2], &Point3::from(p0));
let at = barycentric_point(&face.p[0], &face.p[1], &face.p[2], bary);
let mut reach = (at - Point3::from(p0)).norm();
for k in 0..3 {
reach += bary[k] * e[face.v[k].index() as usize];
}
reach
}