use super::StarFace;
use crate::{Point3, Vector3};
use alum::VH;
#[derive(Debug, Clone, Copy)]
pub(super) struct Chain {
pub(super) v: [VH; 4],
pub(super) p: [Point3; 4],
pub(super) len: usize,
}
impl Chain {
pub(super) fn iter(&self) -> impl Iterator<Item = (VH, Point3)> + '_ {
(0..self.len).map(|i| (self.v[i], self.p[i]))
}
pub(super) fn moves_under(&self, p0: Vector3) -> bool {
self.iter()
.skip(1)
.take(self.len - 2)
.any(|(_, q)| q != Point3::from(p0))
}
}
#[derive(Debug, Clone, Copy)]
pub(super) enum Outline {
Closed,
Open(Chain),
Unsupported,
}
impl Outline {
pub(super) fn parts_regions(&self, p0: Vector3) -> bool {
match self {
Outline::Closed => false,
Outline::Open(chain) => chain.moves_under(p0),
Outline::Unsupported => true,
}
}
}
pub(super) fn boundary_chain(star: &[StarFace], v1: VH, v2: VH) -> Outline {
let mut edges: Vec<(VH, VH, usize)> = Vec::with_capacity(8);
for f in star.iter() {
for k in 0..3 {
let (hk, hj) = (f.v[k], f.v[(k + 1) % 3]);
if !(hk == v1 || hk == v2 || hj == v1 || hj == v2) {
continue;
}
match edges
.iter_mut()
.find(|(a, b, _)| (*a == hk && *b == hj) || (*a == hj && *b == hk))
{
Some((_, _, n)) => *n += 1,
None => edges.push((hk, hj, 1)),
}
}
}
edges.retain(|(_, _, n)| *n == 1);
if edges.is_empty() {
return Outline::Closed;
}
if edges.len() > 3 {
return Outline::Unsupported;
}
let mut all: Vec<VH> = Vec::with_capacity(4);
for (a, b, _) in edges.iter() {
for v in [*a, *b] {
if !all.contains(&v) {
all.push(v);
}
}
}
let mut ends: Vec<VH> = Vec::with_capacity(2);
for v in all.iter() {
let d = edges.iter().filter(|(a, b, _)| a == v || b == v).count();
match d {
1 => ends.push(*v),
2 if *v == v1 || *v == v2 => {}
_ => return Outline::Unsupported,
}
}
if ends.len() != 2 {
return Outline::Unsupported;
}
let mut chain = Chain {
v: [VH::from(0u32); 4],
p: [Point3::origin(); 4],
len: 0,
};
let mut used = vec![false; edges.len()];
let mut at = ends[0];
loop {
let Some(p) = star_position(star, at) else {
return Outline::Unsupported;
};
chain.v[chain.len] = at;
chain.p[chain.len] = p;
chain.len += 1;
let step = edges.iter().enumerate().find_map(|(i, (a, b, _))| {
match (used[i], *a == at, *b == at) {
(false, true, _) => Some((i, *b)),
(false, _, true) => Some((i, *a)),
_ => None,
}
});
match step {
Some((i, next)) => {
used[i] = true;
at = next;
}
None => break,
}
}
if chain.len != all.len() || used.iter().any(|u| !u) {
return Outline::Unsupported;
}
Outline::Open(chain)
}
fn star_position(star: &[StarFace], v: VH) -> Option<Point3> {
star.iter()
.find_map(|f| f.v.iter().position(|h| *h == v).map(|k| f.p[k]))
}