use crate::error::Result;
use super::delaunay::{Boundary, TetMesh};
use super::fill::{delaunay_fill, fill, Constraints, DEFAULT_BUDGET, EXHAUSTIVE_LIMIT};
use super::flips::{relevant, remove_edge};
use super::recovery::Protected;
const STAR_LIMIT: usize = 40;
const SHRINK_BUDGET: usize = 64;
const THINNING_REGION: usize = 8;
pub fn remove_vertex(
mesh: &mut TetMesh,
m: u32,
merged: &[[u32; 3]],
protect: &Protected<'_>,
) -> Result<bool> {
for _ in 0..SHRINK_BUDGET {
let star = mesh.tets_around_vertex(m);
if star.is_empty() {
return Ok(false);
}
if star.len() <= STAR_LIMIT && rebuild_star(mesh, m, &star, merged, protect)? {
return Ok(true);
}
if !thin_star(mesh, m, &star, protect)? {
return Ok(false);
}
}
Ok(false)
}
fn rebuild_star(
mesh: &mut TetMesh,
m: u32,
star: &[u32],
merged: &[[u32; 3]],
protect: &Protected<'_>,
) -> Result<bool> {
let mut boundary = mesh.region_boundary(star);
let surfaced: Vec<[u32; 3]> = boundary
.iter()
.filter(|f| f.contains(&m))
.copied()
.collect();
boundary.retain(|f| !f.contains(&m));
let mut required: Vec<[u32; 3]> = relevant(mesh, star, protect)
.into_iter()
.filter(|f| !f.contains(&m))
.collect();
let mut mode = Boundary::Preserved;
for w in merged {
let halves: Vec<&[u32; 3]> = surfaced
.iter()
.filter(|h| w.iter().filter(|x| h.contains(x)).count() == 2)
.collect();
if halves.is_empty() {
required.push(*w);
} else {
boundary.push(facing_like(w, &halves));
mode = Boundary::MayRecutHull;
}
}
let want = Constraints {
with_faces: &required,
..Default::default()
};
let Ok(cells) = delaunay_fill(mesh.points(), &boundary, want).or_else(|missing| {
(boundary.len() <= EXHAUSTIVE_LIMIT)
.then(|| fill(mesh.points(), &boundary, want, DEFAULT_BUDGET))
.flatten()
.ok_or(missing)
}) else {
return Ok(false);
};
if cells.iter().any(|c| c.contains(&m)) {
return Ok(false); }
match mesh.replace_region_with(star, &cells, "a vertex removal", mode) {
Ok(_) => Ok(true),
Err(_) => Ok(false),
}
}
fn thin_star(mesh: &mut TetMesh, m: u32, star: &[u32], protect: &Protected<'_>) -> Result<bool> {
let mut neighbours: Vec<u32> = star
.iter()
.filter_map(|&t| mesh.tet(t as usize))
.flatten()
.filter(|&x| x != m)
.collect();
neighbours.sort_unstable();
neighbours.dedup();
for x in neighbours {
if !protect.on_edge(m, x).is_empty() {
continue; }
if remove_edge(mesh, m, x, protect, THINNING_REGION)?.is_some() {
return Ok(true);
}
}
Ok(false)
}
fn facing_like(f: &[u32; 3], like: &[&[u32; 3]]) -> [u32; 3] {
for half in like {
for k in 0..3 {
let (a, b) = (f[k], f[(k + 1) % 3]);
for j in 0..3 {
if half[j] == a && half[(j + 1) % 3] == b {
return *f;
}
if half[j] == b && half[(j + 1) % 3] == a {
return [f[0], f[2], f[1]];
}
}
}
}
*f
}