use std::collections::{HashMap, HashSet};
use crate::error::{PyrucastError, Result};
use crate::interrupt::Cancel;
use super::delaunay::TetMesh;
use super::envelope::Envelope;
use super::fill::{delaunay_fill, fill, Constraints, DEFAULT_BUDGET};
use super::flips::{flip23, relevant, remove_edge};
use super::intersect::{segment_hits_triangle, triangles_intersect};
use super::predicates::{orient2d, orient3d};
use super::surface::recut_flat_strip;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Effort {
pub max_region: usize,
pub flips: usize,
pub passes: usize,
}
impl Effort {
pub const THOROUGH: Effort = Effort {
max_region: 16,
flips: 512,
passes: 8,
};
pub const QUICK: Effort = Effort {
max_region: 0,
flips: 24,
passes: 2,
};
}
pub struct Protected<'a> {
facets: &'a [[u32; 3]],
by_key: HashSet<[u32; 3]>,
by_edge: HashMap<(u32, u32), Vec<[u32; 3]>>,
by_vertex: HashMap<u32, Vec<[u32; 3]>>,
}
impl<'a> Protected<'a> {
pub fn new(facets: &'a [[u32; 3]]) -> Protected<'a> {
let mut by_key = HashSet::with_capacity(facets.len());
let mut by_edge: HashMap<(u32, u32), Vec<[u32; 3]>> = HashMap::new();
let mut by_vertex: HashMap<u32, Vec<[u32; 3]>> = HashMap::new();
for f in facets {
by_key.insert(sorted(f));
for k in 0..3 {
let (a, b) = (f[k], f[(k + 1) % 3]);
by_edge
.entry(if a < b { (a, b) } else { (b, a) })
.or_default()
.push(*f);
by_vertex.entry(f[k]).or_default().push(*f);
}
}
Protected {
facets,
by_key,
by_edge,
by_vertex,
}
}
pub fn all(&self) -> &[[u32; 3]] {
self.facets
}
pub fn holds(&self, f: &[u32; 3]) -> bool {
self.by_key.contains(&sorted(f))
}
pub fn on_edge(&self, p: u32, q: u32) -> &[[u32; 3]] {
self.by_edge
.get(&if p < q { (p, q) } else { (q, p) })
.map_or(&[][..], |v| v.as_slice())
}
pub fn at(&self, v: u32) -> &[[u32; 3]] {
self.by_vertex.get(&v).map_or(&[][..], |v| v.as_slice())
}
}
fn sorted(f: &[u32; 3]) -> [u32; 3] {
let mut k = *f;
k.sort_unstable();
k
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stuck {
Edge(u32, u32),
Facet([u32; 3]),
}
pub fn recover(
mesh: &mut TetMesh,
envelope: &Envelope,
effort: Effort,
cancel: &dyn Cancel,
) -> Result<Vec<Stuck>> {
let mut edges: Vec<(u32, u32)> = Vec::with_capacity(3 * envelope.facets().len());
for f in envelope.facets() {
for k in 0..3 {
let (a, b) = (f[k], f[(k + 1) % 3]);
edges.push(if a < b { (a, b) } else { (b, a) });
}
}
edges.sort_unstable();
edges.dedup();
let protect = Protected::new(envelope.facets());
let mut previously_missing = usize::MAX;
for _ in 0..effort.passes {
for &(u, v) in &edges {
cancel.check()?;
if !mesh.has_edge(u, v) {
recover_edge(mesh, u, v, &protect, effort)?;
}
}
for f in envelope.facets() {
cancel.check()?;
if !mesh.has_face(f) {
recover_facet(mesh, f, &protect, effort)?;
}
}
let missing = envelope
.facets()
.iter()
.filter(|f| !mesh.has_face(f))
.count();
if missing == 0 {
return Ok(Vec::new());
}
if missing >= previously_missing {
break;
}
previously_missing = missing;
}
let mut stuck: Vec<Stuck> = edges
.iter()
.filter(|&&(u, v)| !mesh.has_edge(u, v))
.map(|&(u, v)| Stuck::Edge(u, v))
.collect();
stuck.extend(
envelope
.facets()
.iter()
.filter(|f| !mesh.has_face(f) && (0..3).all(|k| mesh.has_edge(f[k], f[(k + 1) % 3])))
.map(|f| Stuck::Facet(*f)),
);
Ok(stuck)
}
pub fn describe(mesh: &TetMesh, stuck: &Stuck) -> PyrucastError {
let (what, vertices) = match stuck {
Stuck::Edge(u, v) => ("edge", vec![*u, *v]),
Stuck::Facet(f) => ("facet", f.to_vec()),
};
let where_ = vertices
.iter()
.map(|&i| {
let p = mesh.points()[i as usize];
format!("({:.6}, {:.6}, {:.6})", p[0], p[1], p[2])
})
.collect::<Vec<_>>()
.join(" – ");
PyrucastError::Message(format!(
"triangulate_volume: cannot fit the envelope's {what} {where_} into the mesh without adding a \
node on the surface. Pass allow_surface_nodes to let the mesher subdivide the envelope \
there — its shape is kept, only its facets are cut finer — or refine the surface mesh \
yourself around that spot."
))
}
fn recover_edge(
mesh: &mut TetMesh,
u: u32,
v: u32,
protect: &Protected<'_>,
effort: Effort,
) -> Result<()> {
for _ in 0..effort.flips {
if mesh.has_edge(u, v) {
return Ok(());
}
if !clear_one_obstruction(mesh, u, v, protect, effort)?
&& !recut_flat_strip(mesh, u, v, protect, effort.max_region)?
&& !rebuild_along(mesh, u, v, protect, effort)?
{
return Ok(()); }
}
Ok(())
}
fn rebuild_along(
mesh: &mut TetMesh,
u: u32,
v: u32,
protect: &Protected<'_>,
effort: Effort,
) -> Result<bool> {
if effort.max_region == 0 {
return Ok(false);
}
let mut region = corridor(mesh, u, v);
if region.is_empty() {
return Ok(false);
}
loop {
let boundary = mesh.region_boundary(®ion);
let keep = relevant(mesh, ®ion, protect);
if let Some(cells) = fill(
mesh.points(),
&boundary,
Constraints {
with_faces: &keep,
with_edges: &[(u, v)],
..Default::default()
},
DEFAULT_BUDGET,
) {
if mesh
.replace_region(®ion, &cells, "an edge recovery")
.is_ok()
{
return Ok(true);
}
}
let wider = grow_region(mesh, ®ion);
if wider.len() == region.len() || wider.len() > effort.max_region {
return Ok(false);
}
region = wider;
}
}
fn clear_one_obstruction(
mesh: &mut TetMesh,
u: u32,
v: u32,
protect: &Protected<'_>,
effort: Effort,
) -> Result<bool> {
let corridor = corridor(mesh, u, v);
for &t in &corridor {
for i in 0..4 {
let f = mesh.face(t as usize, i);
if f.contains(&u) || f.contains(&v) {
continue;
}
if protect.holds(&f) {
continue;
}
if pierces_triangle_between(mesh, u, v, &f) && flip23(mesh, t as usize, i)?.is_some() {
return Ok(true);
}
}
}
for &t in &corridor {
let cell = mesh.tet(t as usize).expect("live corridor cell");
for a in 0..4 {
for b in a + 1..4 {
let (p, q) = (cell[a], cell[b]);
if p == u || q == u || p == v || q == v {
continue;
}
if segments_cross(mesh, u, v, p, q) {
let ok = retire_edge(mesh, p, q, protect, effort)?;
if ok {
return Ok(true);
}
}
}
}
}
Ok(false)
}
fn corridor(mesh: &TetMesh, u: u32, v: u32) -> Vec<u32> {
let touched = |t: u32| -> bool {
let cell = mesh.tet(t as usize).expect("live cell");
if cell.contains(&u) || cell.contains(&v) {
return true;
}
let pts = mesh.points();
(0..4).any(|i| {
let f = mesh.face(t as usize, i);
segment_hits_triangle(
&pts[u as usize],
&pts[v as usize],
&[
&pts[f[0] as usize],
&pts[f[1] as usize],
&pts[f[2] as usize],
],
)
})
};
let mut seen: HashSet<u32> = HashSet::new();
let mut out: Vec<u32> = Vec::new();
let mut stack: Vec<u32> = mesh
.tets_around_vertex(u)
.into_iter()
.filter(|&t| seen.insert(t))
.collect();
while let Some(t) = stack.pop() {
if !touched(t) {
continue;
}
out.push(t);
for i in 0..4 {
if let Some(n) = mesh.neighbour(t as usize, i) {
if seen.insert(n as u32) {
stack.push(n as u32);
}
}
}
}
out.sort_unstable();
out
}
fn retire_edge(
mesh: &mut TetMesh,
p: u32,
q: u32,
protect: &Protected<'_>,
effort: Effort,
) -> Result<bool> {
if protect.on_edge(p, q).iter().any(|g| mesh.has_face(g)) {
return Ok(false);
}
if remove_edge(mesh, p, q, protect, effort.max_region)?.is_some() {
return Ok(true);
}
for t in mesh.tets_with_edge(p, q) {
let cell = mesh.tet(t as usize).expect("live fan cell");
for i in 0..4 {
if cell[i] == p || cell[i] == q {
continue;
}
if protect.holds(&mesh.face(t as usize, i)) {
continue;
}
if flip23(mesh, t as usize, i)?.is_some() {
return Ok(true);
}
}
}
Ok(false)
}
fn recover_facet(
mesh: &mut TetMesh,
f: &[u32; 3],
envelope_facets: &Protected<'_>,
effort: Effort,
) -> Result<()> {
for _ in 0..effort.flips {
if mesh.has_face(f) {
return Ok(());
}
let Some((p, q)) = piercing_edge(mesh, f) else {
break;
};
if !retire_edge(mesh, p, q, envelope_facets, effort)? {
break;
}
}
if mesh.has_face(f) {
return Ok(());
}
rebuild_around(mesh, f, envelope_facets, effort)
}
fn rebuild_around(
mesh: &mut TetMesh,
f: &[u32; 3],
protect: &Protected<'_>,
effort: Effort,
) -> Result<()> {
if effort.max_region == 0 {
return Ok(());
}
let mut region = cells_meeting(mesh, f);
if region.is_empty() {
return Ok(());
}
loop {
let boundary = mesh.region_boundary(®ion);
let mut want = relevant(mesh, ®ion, protect);
if !want.contains(f) {
want.push(*f);
}
let mut split = boundary.clone();
split.push(*f);
split.push([f[0], f[2], f[1]]);
let outcome = delaunay_fill(
mesh.points(),
&split,
Constraints {
with_faces: &want,
..Default::default()
},
)
.or_else(|missing| {
fill(
mesh.points(),
&boundary,
Constraints {
with_faces: &want,
..Default::default()
},
DEFAULT_BUDGET,
)
.ok_or(missing)
});
let missing = match outcome {
Ok(cells) => {
if mesh
.replace_region(®ion, &cells, "a facet recovery")
.is_ok()
{
return Ok(());
}
Vec::new()
}
Err(missing) => missing,
};
let mut wider = region.clone();
if !grow_across(mesh, &mut wider, &missing) {
wider = grow_region(mesh, ®ion);
}
if wider.len() == region.len() || wider.len() > effort.max_region {
return Ok(()); }
region = wider;
}
}
fn grow_across(mesh: &TetMesh, region: &mut Vec<u32>, faces: &[[u32; 3]]) -> bool {
let mut held: HashSet<u32> = region.iter().copied().collect();
let mut grew = false;
for f in faces {
let Some(owners) = mesh.face_owners(f) else {
continue;
};
for (t, _) in owners {
if held.insert(t) {
region.push(t);
grew = true;
}
}
}
grew
}
fn cells_meeting(mesh: &TetMesh, f: &[u32; 3]) -> Vec<u32> {
let pts = mesh.points();
let tri = [
&pts[f[0] as usize],
&pts[f[1] as usize],
&pts[f[2] as usize],
];
let meets = |t: u32| -> bool {
let cell = mesh.tet(t as usize).expect("live cell");
if f.iter().any(|x| cell.contains(x)) {
return true;
}
(0..4).any(|i| {
let g = mesh.face(t as usize, i);
triangles_intersect(
&tri,
&[
&pts[g[0] as usize],
&pts[g[1] as usize],
&pts[g[2] as usize],
],
)
})
};
let mut seen: HashSet<u32> = HashSet::new();
let mut out: Vec<u32> = Vec::new();
let mut stack: Vec<u32> = f
.iter()
.flat_map(|&v| mesh.tets_around_vertex(v))
.filter(|&t| seen.insert(t))
.collect();
while let Some(t) = stack.pop() {
if !meets(t) {
continue;
}
out.push(t);
for i in 0..4 {
if let Some(n) = mesh.neighbour(t as usize, i) {
if seen.insert(n as u32) {
stack.push(n as u32);
}
}
}
}
out.sort_unstable();
out
}
fn grow_region(mesh: &TetMesh, region: &[u32]) -> Vec<u32> {
let mut out: Vec<u32> = region.to_vec();
for &t in region {
for i in 0..4 {
if let Some(n) = mesh.neighbour(t as usize, i) {
if !out.contains(&(n as u32)) {
out.push(n as u32);
}
}
}
}
out.sort_unstable();
out
}
fn piercing_edge(mesh: &TetMesh, f: &[u32; 3]) -> Option<(u32, u32)> {
let mut seen: HashSet<u32> = HashSet::new();
let mut candidates: Vec<u32> = Vec::new();
#[allow(clippy::needless_range_loop)]
for &v in f {
for t in mesh.tets_around_vertex(v) {
if seen.insert(t) {
candidates.push(t);
}
}
}
for i in 0..candidates.len() {
let t = candidates[i];
for k in 0..4 {
if let Some(n) = mesh.neighbour(t as usize, k) {
if seen.insert(n as u32) {
candidates.push(n as u32);
}
}
}
}
for &t in &candidates {
let cell = mesh.tet(t as usize)?;
for a in 0..4 {
for b in a + 1..4 {
let (p, q) = (cell[a], cell[b]);
if f.contains(&p) || f.contains(&q) {
continue;
}
if pierces_triangle_between(mesh, p, q, f) {
return Some((p, q));
}
}
}
}
for &t in &candidates {
let cell = mesh.tet(t as usize)?;
for a in 0..4 {
for b in a + 1..4 {
let (p, q) = (cell[a], cell[b]);
if f.contains(&p) && f.contains(&q) {
continue;
}
if crosses_in_plane(mesh, p, q, f) {
return Some((p, q));
}
}
}
}
None
}
fn pierces_triangle_between(mesh: &TetMesh, p: u32, q: u32, f: &[u32; 3]) -> bool {
let pts = mesh.points();
let side = |x: u32| {
orient3d(
&pts[f[0] as usize],
&pts[f[1] as usize],
&pts[f[2] as usize],
&pts[x as usize],
)
};
let (sp, sq) = (side(p), side(q));
if !((sp > 0.0 && sq < 0.0) || (sp < 0.0 && sq > 0.0)) {
return false;
}
line_through_triangle(mesh, p, q, f)
}
fn crosses_in_plane(mesh: &TetMesh, p: u32, q: u32, f: &[u32; 3]) -> bool {
let pts = mesh.points();
let side = |x: u32| {
orient3d(
&pts[f[0] as usize],
&pts[f[1] as usize],
&pts[f[2] as usize],
&pts[x as usize],
)
};
if side(p) != 0.0 || side(q) != 0.0 {
return false;
}
let at = |x: u32| pts[x as usize];
let (a, b, c) = (at(f[0]), at(f[1]), at(f[2]));
let e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
let e2 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
let n = [
e1[1] * e2[2] - e1[2] * e2[1],
e1[2] * e2[0] - e1[0] * e2[2],
e1[0] * e2[1] - e1[1] * e2[0],
];
let drop = (0..3)
.max_by(|&i, &j| n[i].abs().total_cmp(&n[j].abs()))
.expect("three axes");
let (i, j) = match drop {
0 => (1, 2),
1 => (2, 0),
_ => (0, 1),
};
let flat = |x: u32| [pts[x as usize][i], pts[x as usize][j]];
let tri = [flat(f[0]), flat(f[1]), flat(f[2])];
let (pp, qq) = (flat(p), flat(q));
let strictly_inside = |x: &[f64; 2]| {
let s = [
orient2d(&tri[0], &tri[1], x),
orient2d(&tri[1], &tri[2], x),
orient2d(&tri[2], &tri[0], x),
];
s.iter().all(|&v| v > 0.0) || s.iter().all(|&v| v < 0.0)
};
if strictly_inside(&pp) || strictly_inside(&qq) {
return true;
}
(0..3).any(|k| {
let (e0, e1) = (&tri[k], &tri[(k + 1) % 3]);
let (d0, d1) = (orient2d(e0, e1, &pp), orient2d(e0, e1, &qq));
let (d2, d3) = (orient2d(&pp, &qq, e0), orient2d(&pp, &qq, e1));
d0 * d1 < 0.0 && d2 * d3 < 0.0
})
}
fn line_through_triangle(mesh: &TetMesh, a: u32, b: u32, f: &[u32; 3]) -> bool {
let p = mesh.points();
let side = |i: usize, j: usize| {
orient3d(
&p[a as usize],
&p[b as usize],
&p[f[i] as usize],
&p[f[j] as usize],
)
};
let s = [side(0, 1), side(1, 2), side(2, 0)];
(s.iter().all(|&x| x > 0.0)) || (s.iter().all(|&x| x < 0.0))
}
fn segments_cross(mesh: &TetMesh, u: u32, v: u32, p: u32, q: u32) -> bool {
let pts = mesh.points();
let at = |x: u32| &pts[x as usize];
if orient3d(at(u), at(v), at(p), at(q)) != 0.0 {
return false;
}
let n = plane_probe(at(u), at(v), at(p));
let straddles = |a: u32, b: u32, c: u32, d: u32| {
let sc = orient3d(at(a), at(b), &n, at(c));
let sd = orient3d(at(a), at(b), &n, at(d));
(sc > 0.0 && sd < 0.0) || (sc < 0.0 && sd > 0.0)
};
straddles(u, v, p, q) && straddles(p, q, u, v)
}
fn plane_probe(a: &[f64; 3], b: &[f64; 3], c: &[f64; 3]) -> [f64; 3] {
let e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
let e2 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
let n = [
e1[1] * e2[2] - e1[2] * e2[1],
e1[2] * e2[0] - e1[0] * e2[2],
e1[0] * e2[1] - e1[1] * e2[0],
];
[a[0] + n[0], a[1] + n[1], a[2] + n[2]]
}