use crate::aggregate::Aggregate;
use crate::containers::mesh::{ElementType, Mesh, NodeId, SubMesh};
use crate::error::{PyrucastError, Result};
use crate::store::{insert, read};
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) -> 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 result = Mesh::empty();
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;
}
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))?;
}
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::containers::mesh::{Coords, Node};
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.coord(loop_ids[i]).unwrap();
let q = c.coord(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).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).unwrap();
assert_eq!(ct.len(), 1);
assert_eq!(ct.cell_counts().unwrap(), vec![4]);
}
#[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).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).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).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).is_err());
}
}