use std::collections::HashMap;
use crate::atoms::Point2;
use crate::error::Result;
use super::delaunay::{Boundary, TetMesh};
use super::fill::{delaunay_fill, fill, Constraints, DEFAULT_BUDGET, EXHAUSTIVE_LIMIT};
use super::predicates::{orient2d, orient3d};
use super::recovery::Protected;
use crate::ops::mesh::triangulation::{ear_clip_2d, signed_area};
const STRIP_LIMIT: usize = 256;
pub fn recut_flat_strip(
mesh: &mut TetMesh,
u: u32,
v: u32,
protect: &Protected<'_>,
max_region: usize,
) -> Result<bool> {
let Some(strip) = walk_strip(mesh, u, v) else {
return Ok(false);
};
let faces: Vec<[u32; 3]> = strip
.iter()
.map(|&(t, i)| mesh.face(t as usize, i))
.collect();
if faces.iter().any(|f| protect.holds(f)) {
return Ok(false);
}
let Some(loop_) = boundary_loop(&faces) else {
return Ok(false);
};
let Some(new_faces) = recut(mesh, &loop_, u, v, &strip) else {
return Ok(false);
};
let mut region: Vec<u32> = strip.iter().map(|&(t, _)| t).collect();
region.sort_unstable();
region.dedup();
let old: Vec<[u32; 3]> = faces.iter().map(sorted).collect();
loop {
let mut boundary = mesh.region_boundary(®ion);
boundary.retain(|f| !old.contains(&sorted(f)));
boundary.extend_from_slice(&new_faces);
let keep = super::flips::relevant(mesh, ®ion, protect);
let want = Constraints {
with_faces: &keep,
..Default::default()
};
let outcome = 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)
});
let missing = match outcome {
Ok(cells) => {
if mesh
.replace_region_with(
®ion,
&cells,
"a surface re-cut",
Boundary::MayRecutHull,
)
.is_ok()
{
return Ok(true);
}
Vec::new()
}
Err(missing) => missing,
};
let mut wider = region.clone();
if !grow_across(mesh, &mut wider, &missing) {
wider = widen(mesh, ®ion);
}
if wider.len() == region.len() || wider.len() > max_region {
return Ok(false);
}
region = wider;
}
}
fn grow_across(mesh: &TetMesh, region: &mut Vec<u32>, faces: &[[u32; 3]]) -> bool {
let mut held: std::collections::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 widen(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)
&& !out.contains(&(n as u32))
{
out.push(n as u32);
}
}
}
out.sort_unstable();
out
}
fn walk_strip(mesh: &TetMesh, u: u32, v: u32) -> Option<Vec<(u32, usize)>> {
let start = hull_faces_at(mesh, u)
.into_iter()
.find(|&(t, i)| coplanar_with(mesh, &mesh.face(t as usize, i), v))?;
let plane = Plane::of(mesh, &mesh.face(start.0 as usize, start.1))?;
let at = |x: u32| plane.project(&mesh.points()[x as usize]);
let mut current = hull_faces_at(mesh, u).into_iter().find(|&(t, i)| {
let f = mesh.face(t as usize, i);
coplanar_with(mesh, &f, v) && wedge_holds(&at, &f, u, v)
})?;
let mut strip = vec![current];
let f = mesh.face(current.0 as usize, current.1);
if f.contains(&v) {
return Some(strip); }
let mut entry: [u32; 2] = {
let rest: Vec<u32> = f.iter().copied().filter(|&x| x != u).collect();
[rest[0], rest[1]]
};
for _ in 0..STRIP_LIMIT {
let next = hull_faces_at(mesh, entry[0]).into_iter().find(|&(t, i)| {
(t, i) != current
&& !strip.contains(&(t, i))
&& mesh.face(t as usize, i).contains(&entry[1])
&& coplanar_with(mesh, &mesh.face(t as usize, i), v)
})?;
current = next;
strip.push(current);
let f = mesh.face(current.0 as usize, current.1);
let z = *f.iter().find(|&&x| x != entry[0] && x != entry[1])?;
if z == v {
return Some(strip);
}
let side = |x: u32| orient2d(&at(u), &at(v), &at(x));
let sz = side(z);
if sz == 0.0 {
return None; }
let keep = if side(entry[0]) * sz < 0.0 {
entry[0]
} else if side(entry[1]) * sz < 0.0 {
entry[1]
} else {
return None;
};
entry = [keep, z];
}
None
}
fn hull_faces_at(mesh: &TetMesh, v: u32) -> Vec<(u32, usize)> {
let mut out: Vec<(u32, usize)> = Vec::new();
for t in mesh.tets_around_vertex(v) {
for i in 0..4 {
if mesh.neighbour(t as usize, i).is_none() && mesh.face(t as usize, i).contains(&v) {
out.push((t, i));
}
}
}
out.sort_unstable();
out
}
fn coplanar_with(mesh: &TetMesh, f: &[u32; 3], x: u32) -> bool {
let p = mesh.points();
orient3d(
&p[f[0] as usize],
&p[f[1] as usize],
&p[f[2] as usize],
&p[x as usize],
) == 0.0
}
fn wedge_holds(at: &impl Fn(u32) -> [f64; 2], f: &[u32; 3], u: u32, v: u32) -> bool {
let rest: Vec<u32> = f.iter().copied().filter(|&x| x != u).collect();
if rest.len() != 2 {
return false;
}
let (x, y) = (rest[0], rest[1]);
let (pu, pv, px, py) = (at(u), at(v), at(x), at(y));
let a = orient2d(&pu, &px, &pv) * orient2d(&pu, &px, &py);
let b = orient2d(&pu, &py, &pv) * orient2d(&pu, &py, &px);
a > 0.0 && b > 0.0
}
fn boundary_loop(faces: &[[u32; 3]]) -> Option<Vec<u32>> {
let mut next: HashMap<u32, u32> = HashMap::new();
let mut seen: HashMap<(u32, u32), u32> = HashMap::new();
for f in faces {
for k in 0..3 {
let (a, b) = (f[k], f[(k + 1) % 3]);
let key = if a < b { (a, b) } else { (b, a) };
*seen.entry(key).or_default() += 1;
}
}
for f in faces {
for k in 0..3 {
let (a, b) = (f[k], f[(k + 1) % 3]);
let key = if a < b { (a, b) } else { (b, a) };
if seen[&key] == 1 && next.insert(a, b).is_some() {
return None; }
}
}
if next.is_empty() {
return None;
}
let start = *next.keys().min()?;
let mut loop_ = vec![start];
let mut cur = start;
while let Some(&n) = next.get(&cur) {
if n == start {
return (loop_.len() == next.len()).then_some(loop_);
}
loop_.push(n);
cur = n;
if loop_.len() > next.len() {
return None;
}
}
None
}
fn recut(
mesh: &TetMesh,
loop_: &[u32],
u: u32,
v: u32,
strip: &[(u32, usize)],
) -> Option<Vec<[u32; 3]>> {
let iu = loop_.iter().position(|&x| x == u)?;
let iv = loop_.iter().position(|&x| x == v)?;
let plane = Plane::of(mesh, &mesh.face(strip[0].0 as usize, strip[0].1))?;
let chain = |from: usize, to: usize| -> Vec<u32> {
let mut out = Vec::new();
let mut i = from;
loop {
out.push(loop_[i]);
if i == to {
return out;
}
i = (i + 1) % loop_.len();
}
};
let halves = [chain(iu, iv), chain(iv, iu)];
let anchor = mesh.tet(strip[0].0 as usize)?[strip[0].1];
let mut out: Vec<[u32; 3]> = Vec::new();
for half in &halves {
if half.len() < 3 {
return None;
}
let pts: Vec<Point2> = half
.iter()
.map(|&x| {
let q = plane.project(&mesh.points()[x as usize]);
Point2::new(q[0], q[1])
})
.collect();
if signed_area(&pts) == 0.0 {
return None;
}
for t in ear_clip_2d(&pts).ok()? {
out.push(facing_out(
mesh,
[half[t[0]], half[t[1]], half[t[2]]],
anchor,
));
}
}
Some(out)
}
fn facing_out(mesh: &TetMesh, f: [u32; 3], inside: u32) -> [u32; 3] {
let p = mesh.points();
if orient3d(
&p[f[0] as usize],
&p[f[1] as usize],
&p[f[2] as usize],
&p[inside as usize],
) < 0.0
{
f
} else {
[f[0], f[2], f[1]]
}
}
fn sorted(f: &[u32; 3]) -> [u32; 3] {
let mut k = *f;
k.sort_unstable();
k
}
struct Plane {
axes: (usize, usize),
}
impl Plane {
fn of(mesh: &TetMesh, f: &[u32; 3]) -> Option<Plane> {
let p = mesh.points();
let (a, b, c) = (p[f[0] as usize], p[f[1] as usize], p[f[2] as usize]);
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()))?;
Some(Plane {
axes: match drop {
0 => (1, 2),
1 => (2, 0),
_ => (0, 1),
},
})
}
fn project(&self, p: &[f64; 3]) -> [f64; 2] {
[p[self.axes.0], p[self.axes.1]]
}
}