use crate::aggregate::Aggregate;
use crate::atoms::{ElementType, NodeId};
use crate::containers::mesh::{Mesh, SubMesh};
use crate::coords::Coords;
use crate::error::{PyrucastError, Result};
use crate::store::{insert, read, Handle};
use std::collections::HashMap;
fn edge_key(u: NodeId, v: NodeId) -> (NodeId, NodeId) {
if u.0 <= v.0 {
(u, v)
} else {
(v, u)
}
}
pub fn border(mesh: &Mesh, angle_deg: Option<f64>) -> Result<Mesh> {
let coords = mesh.coords()?;
let mut counts: HashMap<(NodeId, NodeId), u32> = HashMap::new();
let mut any_surface = false;
for sm in mesh {
let (et, conn) = {
let s = read(sm)?;
(s.element_type(), s.connectivity().to_vec())
};
match et {
ElementType::POI1 => continue, ElementType::TRI3 | ElementType::QUA4 => {}
other => {
return Err(PyrucastError::Message(format!(
"border: only surface meshes (TRI3/QUA4) are supported, got {}",
other
)));
}
}
any_surface = true;
let npc = et.nodes_per_cell();
for cell in conn.chunks(npc) {
for i in 0..npc {
let key = edge_key(cell[i], cell[(i + 1) % npc]);
*counts.entry(key).or_insert(0) += 1;
}
}
}
if !any_surface {
return Err(PyrucastError::Message(
"border: mesh has no surface cells (TRI3/QUA4)".into(),
));
}
let mut adj: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
let mut order: Vec<NodeId> = Vec::new();
for sm in mesh {
let (et, conn) = {
let s = read(sm)?;
(s.element_type(), s.connectivity().to_vec())
};
if et == ElementType::POI1 {
continue;
}
let npc = et.nodes_per_cell();
for cell in conn.chunks(npc) {
for i in 0..npc {
let (u, v) = (cell[i], cell[(i + 1) % npc]);
if counts.get(&edge_key(u, v)) == Some(&1) {
adj.entry(u).or_default().push(v);
order.push(u);
}
}
}
}
let mut loops: Vec<Vec<NodeId>> = Vec::new();
for &start in &order {
if adj.get(&start).is_none_or(|outs| outs.is_empty()) {
continue;
}
let mut chain = Vec::new();
let mut current = start;
loop {
let outs = adj
.get_mut(¤t)
.filter(|o| !o.is_empty())
.ok_or_else(|| {
PyrucastError::Message(format!(
"border: boundary is not a closed loop (open or non-manifold at node {})",
current
))
})?;
let next = outs.remove(0);
chain.push(current);
if next == start {
break;
}
current = next;
}
loops.push(chain);
}
let mut result = Mesh::empty();
match angle_deg {
None => {
for chain in &loops {
emit_closed(&mut result, &coords, chain)?;
}
}
Some(a) => {
let cos_tol = a.to_radians().cos();
let mut pieces: Vec<(Vec<NodeId>, bool)> = Vec::new(); {
let c = read(&coords)?;
for chain in &loops {
let corners = corner_indices(&c, chain, cos_tol)?;
if corners.is_empty() {
pieces.push((chain.clone(), true)); } else {
for arc in split_at_corners(chain, &corners) {
pieces.push((arc, false));
}
}
}
}
for (nodes, closed) in &pieces {
if *closed {
emit_closed(&mut result, &coords, nodes)?;
} else {
emit_open(&mut result, &coords, nodes)?;
}
}
}
}
Ok(result)
}
fn emit_closed(result: &mut Mesh, coords: &Handle<Coords>, chain: &[NodeId]) -> Result<()> {
let mut sub = SubMesh::new(coords.clone(), ElementType::SEG2);
let n = chain.len();
for i in 0..n {
sub.add_cell(&[chain[i], chain[(i + 1) % n]])?;
}
result.add_sub(insert(sub))
}
fn emit_open(result: &mut Mesh, coords: &Handle<Coords>, arc: &[NodeId]) -> Result<()> {
let mut sub = SubMesh::new(coords.clone(), ElementType::SEG2);
for pair in arc.windows(2) {
sub.add_cell(pair)?;
}
result.add_sub(insert(sub))
}
fn corner_indices(c: &Coords, chain: &[NodeId], cos_tol: f64) -> Result<Vec<usize>> {
let k = chain.len();
let mut corners = Vec::new();
for i in 0..k {
let prev = c.position(chain[(i + k - 1) % k])?;
let cur = c.position(chain[i])?;
let next = c.position(chain[(i + 1) % k])?;
if let Some(cos_turn) = turn_cosine(prev, cur, next) {
if cos_turn < cos_tol {
corners.push(i);
}
}
}
Ok(corners)
}
fn turn_cosine(prev: &[f64], cur: &[f64], next: &[f64]) -> Option<f64> {
let din: Vec<f64> = cur.iter().zip(prev).map(|(a, b)| a - b).collect();
let dout: Vec<f64> = next.iter().zip(cur).map(|(a, b)| a - b).collect();
let dot: f64 = din.iter().zip(&dout).map(|(a, b)| a * b).sum();
let nin = din.iter().map(|x| x * x).sum::<f64>().sqrt();
let nout = dout.iter().map(|x| x * x).sum::<f64>().sqrt();
if nin == 0.0 || nout == 0.0 {
return None;
}
Some((dot / (nin * nout)).clamp(-1.0, 1.0))
}
fn split_at_corners(chain: &[NodeId], corners: &[usize]) -> Vec<Vec<NodeId>> {
let k = chain.len();
let m = corners.len();
let mut arcs = Vec::with_capacity(m);
for t in 0..m {
let a = corners[t];
let b = corners[(t + 1) % m];
let mut arc = vec![chain[a]];
let mut idx = a;
loop {
idx = (idx + 1) % k;
arc.push(chain[idx]);
if idx == b {
break;
}
}
arcs.push(arc);
}
arcs
}
#[cfg(test)]
mod tests {
use super::*;
use crate::atoms::Node;
use crate::coords::Coords;
use crate::store::insert;
fn signed_area(coords: &crate::store::Handle<Coords>, loop_ids: &[NodeId]) -> f64 {
let c = read(coords).unwrap();
let n = loop_ids.len();
let mut a = 0.0;
for i in 0..n {
let p = c.position(loop_ids[i]).unwrap();
let q = c.position(loop_ids[(i + 1) % n]).unwrap();
a += p[0] * q[1] - q[0] * p[1];
}
a / 2.0
}
fn loop_of(mesh: &Mesh, s: usize) -> Vec<NodeId> {
let sm = mesh.get(s).unwrap();
let conn = read(&sm).unwrap().connectivity().to_vec();
conn.chunks(2).map(|seg| seg[0]).collect()
}
#[test]
fn single_triangle_gives_one_triloop() {
let coords = insert(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
let c = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
m.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
let ct = border(&m, None).unwrap();
assert_eq!(ct.len(), 1);
assert_eq!(ct.element_types().unwrap(), vec![ElementType::SEG2]);
assert_eq!(ct.cell_counts().unwrap(), vec![3]);
assert!(signed_area(&coords, &loop_of(&ct, 0)) > 0.0);
}
#[test]
fn two_triangles_sharing_diagonal_give_one_quadloop() {
let coords = insert(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
let c = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
let d = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
m.add_cell(&[a.id(), b.id(), d.id()]).unwrap();
m.add_cell(&[b.id(), c.id(), d.id()]).unwrap();
let ct = border(&m, None).unwrap();
assert_eq!(ct.len(), 1);
assert_eq!(ct.cell_counts().unwrap(), vec![4]);
}
#[test]
fn square_split_by_angle_gives_four_open_aretes() {
let coords = insert(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
let c = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
let d = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::QUA4));
m.add_cell(&[a.id(), b.id(), c.id(), d.id()]).unwrap();
let ar = border(&m, Some(45.0)).unwrap();
assert_eq!(ar.len(), 4);
assert_eq!(ar.cell_counts().unwrap(), vec![1, 1, 1, 1]);
}
#[test]
fn collinear_boundary_segments_stay_in_one_arete() {
let coords = insert(Coords::new(2).unwrap());
let bl = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let bm = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
let br = Node::create_in(coords.clone(), &[2.0, 0.0]).unwrap();
let tr = Node::create_in(coords.clone(), &[2.0, 1.0]).unwrap();
let tm = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
let tl = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::QUA4));
m.add_cell(&[bl.id(), bm.id(), tm.id(), tl.id()]).unwrap();
m.add_cell(&[bm.id(), br.id(), tr.id(), tm.id()]).unwrap();
let ar = border(&m, Some(45.0)).unwrap();
assert_eq!(ar.len(), 4);
let mut sizes = ar.cell_counts().unwrap();
sizes.sort_unstable();
assert_eq!(sizes, vec![1, 1, 2, 2]);
}
#[test]
fn large_angle_keeps_a_triangle_boundary_closed() {
let coords = insert(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
let c = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
m.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
let closed = border(&m, Some(170.0)).unwrap();
assert_eq!(closed.len(), 1);
assert_eq!(closed.cell_counts().unwrap(), vec![3]);
let split = border(&m, Some(30.0)).unwrap();
assert_eq!(split.len(), 3);
assert_eq!(split.cell_counts().unwrap(), vec![1, 1, 1]);
}
#[test]
fn grid_with_hole_gives_two_loops() {
let coords = insert(Coords::new(2).unwrap());
let mut ids = Vec::new();
for j in 0..4 {
for i in 0..4 {
ids.push(
Node::create_in(coords.clone(), &[i as f64, j as f64])
.unwrap()
.id(),
);
}
}
let at = |i: usize, j: usize| ids[j * 4 + i];
let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::QUA4));
for j in 0..3 {
for i in 0..3 {
if i == 1 && j == 1 {
continue; }
m.add_cell(&[at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)])
.unwrap();
}
}
let ct = border(&m, None).unwrap();
assert_eq!(ct.len(), 2, "outer loop + hole loop");
let mut sizes = ct.cell_counts().unwrap();
sizes.sort_unstable();
assert_eq!(sizes, vec![4, 12]);
let areas: Vec<f64> = (0..2)
.map(|s| signed_area(&coords, &loop_of(&ct, s)))
.collect();
assert!(areas.iter().any(|&a| a > 0.0), "an outer (CCW) loop");
assert!(areas.iter().any(|&a| a < 0.0), "a hole (CW) loop");
}
#[test]
fn reuses_nodes_and_increfs() {
let coords = insert(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
let c = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
m.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
assert_eq!(read(&coords).unwrap().refcount(a.id()), 2);
let ct = border(&m, None).unwrap();
assert_eq!(read(&coords).unwrap().refcount(a.id()), 4);
drop(ct);
assert_eq!(read(&coords).unwrap().refcount(a.id()), 2);
}
#[test]
fn no_surface_cells_is_error() {
let coords = insert(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
m.add_cell(&[a.id()]).unwrap();
assert!(border(&m, None).is_err());
}
#[test]
fn volume_cells_are_rejected() {
let coords = insert(Coords::new(3).unwrap());
let ns: Vec<NodeId> = (0..4)
.map(|k| {
Node::create_in(coords.clone(), &[k as f64, 0.0, 0.0])
.unwrap()
.id()
})
.collect();
let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TET4));
m.add_cell(&ns).unwrap();
assert!(border(&m, None).is_err());
}
}