use crate::aggregate::Aggregate;
use crate::atoms::{ElementType, NodeId};
use crate::containers::mesh::{Mesh, SubMesh};
use crate::error::{PyrucastError, Result};
use crate::interrupt::{Cancel, NoCancel};
use super::tetrahedralization::classify;
use super::tetrahedralization::delaunay::TetMesh;
use super::tetrahedralization::envelope::Envelope;
use super::tetrahedralization::recovery;
use super::tetrahedralization::refine;
use super::tetrahedralization::simplify;
use super::tetrahedralization::smooth;
const VOLUME_TOLERANCE: f64 = 1e-9;
const MAX_SUBDIVISIONS: usize = 12;
const DEGENERATE_SHAPE: f64 = 1e-4;
pub fn triangulate_volume(
envelope: &Mesh,
target_size: Option<f64>,
allow_surface_nodes: bool,
) -> Result<Mesh> {
triangulate_volume_cancellable(envelope, target_size, allow_surface_nodes, &NoCancel)
}
pub fn triangulate_volume_cancellable(
envelope: &Mesh,
target_size: Option<f64>,
allow_surface_nodes: bool,
cancel: &dyn Cancel,
) -> Result<Mesh> {
if let Some(h) = target_size
&& h.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater)
{
return Err(PyrucastError::Message(format!(
"triangulate_volume: size must be > 0, got {h}"
)));
}
let mut env = Envelope::extract(envelope, cancel)?;
let mut unusable: Option<PyrucastError> = None;
for _ in 0..MAX_SUBDIVISIONS {
cancel.check()?;
let mut mesh = TetMesh::delaunay(env.points(), cancel)?;
let effort = if allow_surface_nodes {
recovery::Effort::QUICK
} else {
recovery::Effort::THOROUGH
};
let stuck = recovery::recover(&mut mesh, &env, effort, cancel)?;
if stuck.is_empty() {
cancel.check()?;
reclaim(&mut mesh, &mut env, cancel)?;
let walls = classify::walls_of(&env);
let mut inside = classify::interior_within(&mesh, &env, &walls, cancel)?;
let target = target_size.unwrap_or_else(|| env.mean_edge_length());
refine::refine(&mut mesh, &mut inside, &walls, target, cancel)?;
let inside = classify::interior_within(&mesh, &env, &walls, cancel)?;
let movable: Vec<bool> = (0..mesh.points().len())
.map(|i| i >= env.points().len())
.collect();
let protect = recovery::Protected::new(env.facets());
smooth::smooth(&mut mesh, &inside, &movable, &walls, &protect, cancel)?;
drop(protect);
let inside = classify::interior_within(&mesh, &env, &walls, cancel)?;
let stubborn = smooth::stubborn(&mesh, &inside, env.points().len(), DEGENERATE_SHAPE);
if !stubborn.is_empty() {
let complaint = degenerate(&mesh, &stubborn);
let Some(cuts) = facets_of(&stubborn, &walls, &env) else {
return Err(complaint);
};
if !allow_surface_nodes {
return Err(complaint);
}
unusable = Some(complaint);
env.subdivide(&cuts)?;
continue;
}
let cells = validate(&mesh, &env, &inside)?;
let added = warn_if_subdivided(&env, &cells);
return materialize(envelope, &env, mesh.points(), &cells, &added);
}
if !allow_surface_nodes {
return Err(recovery::describe(&mesh, &stuck[0]));
}
env.subdivide(&stuck)?;
}
Err(unusable.unwrap_or_else(|| {
PyrucastError::Message(format!(
"triangulate_volume: the envelope still would not fit after {MAX_SUBDIVISIONS} rounds of \
subdividing it — the surface is likely self-touching or extremely thin somewhere"
))
}))
}
fn facets_of(
stubborn: &[([u32; 4], f64)],
walls: &std::collections::HashSet<[u32; 3]>,
env: &Envelope,
) -> Option<Vec<recovery::Stuck>> {
let mut cuts: Vec<recovery::Stuck> = Vec::new();
for (v, _) in stubborn {
for f in super::tetrahedralization::delaunay::FACE_OF {
let face = [v[f[0]], v[f[1]], v[f[2]]];
let mut k = face;
k.sort_unstable();
if !walls.contains(&k) {
continue;
}
if let Some(&g) = env.facets().iter().find(|g| {
let mut s = **g;
s.sort_unstable();
s == k
}) {
cuts.push(recovery::Stuck::Facet(g));
}
}
}
cuts.sort_unstable_by_key(|s| match s {
recovery::Stuck::Facet(f) => *f,
recovery::Stuck::Edge(a, b) => [*a, *b, 0],
});
cuts.dedup();
(!cuts.is_empty()).then_some(cuts)
}
fn degenerate(mesh: &TetMesh, stubborn: &[([u32; 4], f64)]) -> PyrucastError {
let (v, quality) = stubborn
.iter()
.min_by(|a, b| a.1.total_cmp(&b.1))
.expect("the list is not empty");
let centre: Vec<String> = (0..3)
.map(|k| {
let mid: f64 = v.iter().map(|&i| mesh.points()[i as usize][k]).sum::<f64>() / 4.0;
format!("{mid:.6}")
})
.collect();
PyrucastError::Message(format!(
"triangulate_volume: the mesh has {} flat cell(s) that cannot be improved — the worst, around \
({}), has a shape of {quality:.2e} where 1 is a regular tetrahedron. Its four corners \
are all nodes of the envelope, so no node can be added to break it up and none of its \
own may be moved. Refine the surface mesh around that point, or pass \
allow_surface_nodes to let the mesher cut the envelope there itself.",
stubborn.len(),
centre.join(", ")
))
}
fn reclaim(mesh: &mut TetMesh, env: &mut Envelope, cancel: &dyn Cancel) -> Result<()> {
for (m, origin) in env.added_points() {
cancel.check()?;
let Some((dropped, merged)) = env.merge_around(m, origin) else {
continue;
};
let taken = {
let protect = recovery::Protected::new(env.facets());
simplify::remove_vertex(mesh, m, &merged, &protect)?
};
if taken {
env.unsplit(&dropped, &merged);
}
}
Ok(())
}
fn warn_if_subdivided(env: &Envelope, cells: &[[u32; 4]]) -> Vec<u32> {
let given = env.given_node_count() as u32;
let on_surface = env.points().len() as u32;
let mut kept: Vec<u32> = cells
.iter()
.flatten()
.copied()
.filter(|&i| i >= given && i < on_surface)
.collect();
kept.sort_unstable();
kept.dedup();
let added = kept.len();
if added == 0 {
return kept;
}
eprintln!(
"triangulate_volume: warning — the envelope would not fit as given, so {added} node(s) were \
added on it. Its shape is unchanged (each new node lies on the edge or facet it \
divides), but the skin of the result no longer matches the surface mesh passed in. \
The result therefore carries a SECOND SUBMESH, of POI1, naming those {added} node(s): \
its element types are [TET4, POI1] rather than [TET4] alone, so anything that walks \
the submeshes or counts cells must take the TET4 one and leave the markers out."
);
kept
}
fn validate(mesh: &TetMesh, env: &Envelope, inside: &[bool]) -> Result<Vec<[u32; 4]>> {
if let Some(defect) = mesh.find_defect() {
return Err(PyrucastError::Message(format!(
"triangulate_volume: {defect} (internal error)"
)));
}
let cells: Vec<[u32; 4]> = mesh
.iter()
.filter(|(t, _)| inside[*t])
.map(|(_, v)| v)
.collect();
if cells.is_empty() {
return Err(PyrucastError::Message(
"triangulate_volume: produced no cell".into(),
));
}
let volume: f64 = cells.iter().map(|v| mesh.orientation(v)).sum::<f64>() / 6.0;
let drift = (volume - env.volume()).abs();
if drift > VOLUME_TOLERANCE * env.volume() {
return Err(PyrucastError::Message(format!(
"triangulate_volume: the mesh fills {volume:.12e} but the envelope encloses {:.12e} \
(internal error)",
env.volume()
)));
}
let mut boundary: std::collections::HashSet<[u32; 3]> = std::collections::HashSet::new();
for v in &cells {
for f in super::tetrahedralization::delaunay::FACE_OF {
let mut key = [v[f[0]], v[f[1]], v[f[2]]];
key.sort_unstable();
if !boundary.remove(&key) {
boundary.insert(key);
}
}
}
for f in env.facets() {
let mut key = *f;
key.sort_unstable();
if !boundary.remove(&key) {
return Err(PyrucastError::Message(format!(
"triangulate_volume: an envelope facet at {:?} is not on the boundary of the mesh \
(internal error)",
env.points()[f[0] as usize]
)));
}
}
if !boundary.is_empty() {
return Err(PyrucastError::Message(format!(
"triangulate_volume: the mesh has {} boundary face(s) that are not envelope facets \
(internal error)",
boundary.len()
)));
}
Ok(cells)
}
fn materialize(
envelope: &Mesh,
env: &Envelope,
points: &[[f64; 3]],
cells: &[[u32; 4]],
added: &[u32],
) -> Result<Mesh> {
let coords = envelope.coords()?;
let given = env.given_node_count();
let mut ids: Vec<NodeId> = env.node_ids().to_vec();
ids.resize(points.len(), NodeId(u32::MAX));
let mut fresh: Vec<f64> = Vec::new();
let mut ranks: Vec<u32> = Vec::new();
for v in cells {
for &i in v {
if (i as usize) < given || ids[i as usize] != NodeId(u32::MAX) {
continue;
}
fresh.extend_from_slice(&points[i as usize]);
ids[i as usize] = NodeId(ranks.len() as u32);
ranks.push(i);
}
}
let first = coords.write().add_nodes(&fresh)?.start;
for &i in &ranks {
ids[i as usize] = NodeId(first + ids[i as usize].0);
}
let conn: Vec<NodeId> = cells
.iter()
.flat_map(|v| v.iter().map(|&i| ids[i as usize]))
.collect();
let sub = SubMesh::from_connectivity(coords.clone(), ElementType::TET4, conn)?;
let owned: Vec<NodeId> = (first..first + ranks.len() as u32).map(NodeId).collect();
coords.write().decref_all(&owned)?;
let mut out = Mesh::from_submesh(sub);
if !added.is_empty() {
let marks: Vec<NodeId> = added.iter().map(|&i| ids[i as usize]).collect();
out = out.union(&Mesh::from_submesh(SubMesh::poi1_from_node_ids(
coords, &marks,
)?))?;
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::atoms::Node;
use crate::coords::Coords;
use crate::handle::Handle;
fn box_nodes(coords: &Handle<Coords>, lo: [f64; 3], hi: [f64; 3]) -> Vec<NodeId> {
[
[lo[0], lo[1], lo[2]],
[hi[0], lo[1], lo[2]],
[hi[0], hi[1], lo[2]],
[lo[0], hi[1], lo[2]],
[lo[0], lo[1], hi[2]],
[hi[0], lo[1], hi[2]],
[hi[0], hi[1], hi[2]],
[lo[0], hi[1], hi[2]],
]
.iter()
.map(|p| Node::create_in(coords.clone(), p).unwrap().id())
.collect()
}
const BOX_FACETS: [[usize; 3]; 12] = [
[0, 3, 2],
[0, 2, 1], [4, 5, 7],
[5, 6, 7], [0, 1, 5],
[0, 5, 4], [1, 2, 5],
[2, 6, 5], [2, 3, 7],
[2, 7, 6], [3, 0, 7],
[0, 4, 7], ];
fn surface(coords: &Handle<Coords>, nodes: &[NodeId], facets: &[[usize; 3]]) -> Mesh {
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
for f in facets {
sm.add_cell(&[nodes[f[0]], nodes[f[1]], nodes[f[2]]])
.unwrap();
}
Mesh::from_submesh(sm)
}
fn tet_count(mesh: &Mesh) -> usize {
mesh.cell_counts().unwrap()[0]
}
fn volume_of(mesh: &Mesh) -> f64 {
let mut total = 0.0;
for (si, &n) in mesh.cell_counts().unwrap().iter().enumerate() {
if mesh.element_types().unwrap()[si] != ElementType::TET4 {
continue;
}
for ci in 0..n {
let p: Vec<Vec<f64>> = (0..4)
.map(|k| mesh.node(si, ci, k).unwrap().position().unwrap())
.collect();
let e = |i: usize, k: usize| p[i][k] - p[0][k];
total += (e(1, 0) * (e(2, 1) * e(3, 2) - e(2, 2) * e(3, 1))
- e(1, 1) * (e(2, 0) * e(3, 2) - e(2, 2) * e(3, 0))
+ e(1, 2) * (e(2, 0) * e(3, 1) - e(2, 1) * e(3, 0)))
/ 6.0;
}
}
total
}
#[test]
fn meshes_a_box_and_keeps_its_volume() {
let coords = Handle::new(Coords::new(3).unwrap());
let nodes = box_nodes(&coords, [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]);
let mesh = triangulate_volume(&surface(&coords, &nodes, &BOX_FACETS), None, false).unwrap();
assert_eq!(mesh.element_types().unwrap(), vec![ElementType::TET4]);
assert!(mesh.cell_count() >= 5);
let v = volume_of(&mesh);
assert!((v - 1.0).abs() < 1e-12, "volume {v}");
}
#[test]
fn the_envelope_nodes_are_reused_and_none_is_added_on_it() {
let coords = Handle::new(Coords::new(3).unwrap());
let nodes = box_nodes(&coords, [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]);
let envelope = surface(&coords, &nodes, &BOX_FACETS);
let mesh = triangulate_volume(&envelope, None, false).unwrap();
let mut used: Vec<NodeId> = Vec::new();
for ci in 0..mesh.cell_count() {
for k in 0..4 {
let id = mesh.node(0, ci, k).unwrap().id();
if !used.contains(&id) {
used.push(id);
}
}
}
assert!(
nodes.iter().all(|n| used.contains(n)),
"an envelope node went missing"
);
let peeled = super::super::skin(&mesh, crate::ops::mesh::skin::DEFAULT_ANGLE_DEG).unwrap();
assert_eq!(peeled.cell_count(), 12);
}
#[test]
fn the_skin_of_the_result_is_the_envelope() {
let coords = Handle::new(Coords::new(3).unwrap());
let nodes = box_nodes(&coords, [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]);
let env = surface(&coords, &nodes, &BOX_FACETS);
let mesh = triangulate_volume(&env, None, false).unwrap();
let peeled = super::super::skin(&mesh, crate::ops::mesh::skin::DEFAULT_ANGLE_DEG).unwrap();
assert_eq!(peeled.cell_count(), 12);
}
#[test]
fn refuses_a_box_whose_faces_cannot_be_filled() {
const UNFILLABLE: [[usize; 3]; 12] = [
[0, 3, 2],
[0, 2, 1],
[4, 5, 6],
[4, 6, 7],
[0, 1, 5],
[0, 5, 4],
[1, 2, 6],
[1, 6, 5],
[2, 3, 7],
[2, 7, 6],
[3, 0, 4],
[3, 4, 7],
];
let coords = Handle::new(Coords::new(3).unwrap());
let nodes = box_nodes(&coords, [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]);
let err =
triangulate_volume(&surface(&coords, &nodes, &UNFILLABLE), None, false).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("without adding a node on the surface"),
"{msg}"
);
assert!(msg.contains("1.000000"), "{msg}");
}
#[test]
fn meshes_a_single_tetrahedron_as_one_cell() {
let coords = Handle::new(Coords::new(3).unwrap());
let n: Vec<NodeId> = [
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
]
.iter()
.map(|p| Node::create_in(coords.clone(), p).unwrap().id())
.collect();
let facets = [[0, 2, 1], [0, 1, 3], [0, 3, 2], [1, 2, 3]];
let mesh = triangulate_volume(&surface(&coords, &n, &facets), None, false).unwrap();
assert_eq!(mesh.cell_count(), 1);
assert!((volume_of(&mesh) - 1.0 / 6.0).abs() < 1e-15);
}
#[test]
fn meshes_two_disjoint_bodies_at_once() {
let coords = Handle::new(Coords::new(3).unwrap());
let a = box_nodes(&coords, [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]);
let b = box_nodes(&coords, [5.0, 0.0, 0.0], [7.0, 1.0, 1.0]);
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
for nodes in [&a, &b] {
for f in &BOX_FACETS {
sm.add_cell(&[nodes[f[0]], nodes[f[1]], nodes[f[2]]])
.unwrap();
}
}
let mesh = triangulate_volume(&Mesh::from_submesh(sm), None, false).unwrap();
assert!((volume_of(&mesh) - 3.0).abs() < 1e-12);
}
#[test]
fn meshes_a_box_with_an_internal_cavity() {
let coords = Handle::new(Coords::new(3).unwrap());
let outer = box_nodes(&coords, [0.0, 0.0, 0.0], [3.0, 3.0, 3.0]);
let inner = box_nodes(&coords, [1.0, 1.0, 1.0], [2.0, 2.0, 2.0]);
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
for f in &BOX_FACETS {
sm.add_cell(&[outer[f[0]], outer[f[1]], outer[f[2]]])
.unwrap();
}
for f in &BOX_FACETS {
sm.add_cell(&[inner[f[0]], inner[f[2]], inner[f[1]]])
.unwrap();
}
let mesh = triangulate_volume(&Mesh::from_submesh(sm), None, false).unwrap();
let v = volume_of(&mesh);
assert!((v - (27.0 - 1.0)).abs() < 1e-12, "volume {v}");
}
#[test]
fn meshes_a_concave_solid() {
let coords = Handle::new(Coords::new(3).unwrap());
let base = [
[0.0, 0.0],
[2.0, 0.0],
[2.0, 1.0],
[1.0, 1.0],
[1.0, 2.0],
[0.0, 2.0],
];
let n: Vec<NodeId> = base
.iter()
.flat_map(|p| [[p[0], p[1], 0.0], [p[0], p[1], 1.0]])
.map(|p| Node::create_in(coords.clone(), &p).unwrap().id())
.collect();
let (b, t) = (|i: usize| 2 * i, |i: usize| 2 * i + 1);
let mut facets: Vec<[usize; 3]> = Vec::new();
for i in 1..5 {
facets.push([b(0), b(i + 1), b(i)]);
facets.push([t(0), t(i), t(i + 1)]);
}
for i in 0..6 {
let j = (i + 1) % 6;
facets.push([b(i), b(j), t(j)]);
facets.push([b(i), t(j), t(i)]);
}
let mesh = triangulate_volume(&surface(&coords, &n, &facets), None, true).unwrap();
let v = volume_of(&mesh);
assert!((v - 3.0).abs() < 1e-12, "volume {v}");
}
fn subdivided_blob(coords: &Handle<Coords>, n: usize) -> (Mesh, f64) {
let jitter = |i: usize, k: usize| {
let mut x = ((i * 3 + k) as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
x ^= x >> 29;
((x >> 11) as f64 / (1u64 << 53) as f64 - 0.5) * 0.02
};
let s = n as f64;
let mut pts: Vec<[f64; 3]> = Vec::new();
let mut at: std::collections::HashMap<(usize, usize, usize), usize> =
std::collections::HashMap::new();
for i in 0..=n {
for j in 0..=n {
for k in 0..=n {
if i == 0 || i == n || j == 0 || j == n || k == 0 || k == n {
at.insert((i, j, k), pts.len());
pts.push([i as f64 / s, j as f64 / s, k as f64 / s]);
}
}
}
}
for (m, p) in pts.iter_mut().enumerate() {
for k in 0..3 {
p[k] += jitter(m, k);
}
}
let mut facets: Vec<[usize; 3]> = Vec::new();
let mut quad = |a, b, c, d| {
facets.push([a, b, c]);
facets.push([a, c, d]);
};
for i in 0..n {
for j in 0..n {
quad(
at[&(i, j, 0)],
at[&(i, j + 1, 0)],
at[&(i + 1, j + 1, 0)],
at[&(i + 1, j, 0)],
);
quad(
at[&(i, j, n)],
at[&(i + 1, j, n)],
at[&(i + 1, j + 1, n)],
at[&(i, j + 1, n)],
);
quad(
at[&(i, 0, j)],
at[&(i + 1, 0, j)],
at[&(i + 1, 0, j + 1)],
at[&(i, 0, j + 1)],
);
quad(
at[&(i, n, j)],
at[&(i, n, j + 1)],
at[&(i + 1, n, j + 1)],
at[&(i + 1, n, j)],
);
quad(
at[&(0, i, j)],
at[&(0, i, j + 1)],
at[&(0, i + 1, j + 1)],
at[&(0, i + 1, j)],
);
quad(
at[&(n, i, j)],
at[&(n, i + 1, j)],
at[&(n, i + 1, j + 1)],
at[&(n, i, j + 1)],
);
}
}
let ids: Vec<NodeId> = pts
.iter()
.map(|p| Node::create_in(coords.clone(), p).unwrap().id())
.collect();
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
for f in &facets {
sm.add_cell(&[ids[f[0]], ids[f[1]], ids[f[2]]]).unwrap();
}
let v6: f64 = facets
.iter()
.map(|f| {
let (a, b, c) = (pts[f[0]], pts[f[1]], pts[f[2]]);
a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0])
+ a[2] * (b[0] * c[1] - b[1] * c[0])
})
.sum();
(Mesh::from_submesh(sm), v6 / 6.0)
}
fn extruded_plate(coords: &Handle<Coords>, n: usize, size: f64) -> Mesh {
let mut pts: Vec<[f64; 3]> = Vec::new();
for i in 0..n {
pts.push([i as f64 / n as f64, 0.0, 0.0]);
}
for i in 0..n {
pts.push([1.0, 0.0, i as f64 / n as f64]);
}
for i in 0..n {
pts.push([1.0 - i as f64 / n as f64, 0.0, 1.0]);
}
for i in 0..n {
pts.push([0.0, 0.0, 1.0 - i as f64 / n as f64]);
}
let ids: Vec<NodeId> = pts
.iter()
.map(|p| Node::create_in(coords.clone(), p).unwrap().id())
.collect();
let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
for i in 0..ids.len() {
sm.add_cell(&[ids[i], ids[(i + 1) % ids.len()]]).unwrap();
}
let contour = Mesh::from_submesh(sm);
let plate =
super::super::triangulate_surface(&contour, ElementType::TRI3, Some(size)).unwrap();
let solid = super::super::extrude(&plate, &[0.0, 0.4, 0.0], 1).unwrap();
let skin = super::super::skin(&solid, crate::ops::mesh::skin::DEFAULT_ANGLE_DEG).unwrap();
let skin = super::super::convert(&skin, ElementType::TRI3).unwrap();
super::super::invert(&skin).unwrap()
}
#[test]
fn meshes_a_realistic_closed_surface() {
let coords = Handle::new(Coords::new(3).unwrap());
let envelope = extruded_plate(&coords, 8, 0.15);
let mesh = triangulate_volume(&envelope, None, true).unwrap();
assert_eq!(
mesh.element_types().unwrap(),
vec![ElementType::TET4, ElementType::POI1]
);
assert!(tet_count(&mesh) > 2000, "{}", tet_count(&mesh));
let v = volume_of(&mesh);
assert!((v - 0.4).abs() < 1e-12, "volume {v}");
}
#[test]
fn the_nodes_it_adds_on_the_envelope_come_back_as_a_poi1_submesh() {
let coords = Handle::new(Coords::new(3).unwrap());
let envelope = extruded_plate(&coords, 5, 0.25);
let given: Vec<Vec<f64>> = {
let c = coords.read();
c.iter_live()
.map(|id| c.position(id).unwrap().to_vec())
.collect()
};
let mesh = triangulate_volume(&envelope, None, true).unwrap();
let types = mesh.element_types().unwrap();
assert_eq!(types, vec![ElementType::TET4, ElementType::POI1]);
let marks = mesh.cell_counts().unwrap()[1];
assert!(marks > 0, "the submesh is there, so it must name something");
for ci in 0..marks {
let p = mesh.node(1, ci, 0).unwrap().position().unwrap();
assert!(
!given.iter().any(|q| q == &p),
"{p:?} was the caller's node all along"
);
let id = mesh.node(1, ci, 0).unwrap().id();
let used = (0..tet_count(&mesh))
.any(|t| (0..4).any(|k| mesh.node(0, t, k).unwrap().id() == id));
assert!(used, "{p:?} is named but no cell uses it");
}
}
#[test]
fn a_mesh_that_needed_no_extra_node_has_no_poi1_submesh() {
let coords = Handle::new(Coords::new(3).unwrap());
let nodes = box_nodes(&coords, [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]);
let mesh = triangulate_volume(&surface(&coords, &nodes, &BOX_FACETS), None, true).unwrap();
assert_eq!(mesh.element_types().unwrap(), vec![ElementType::TET4]);
}
#[test]
fn meshes_the_envelope_of_an_extruded_plate() {
let coords = Handle::new(Coords::new(3).unwrap());
let envelope = extruded_plate(&coords, 2, 0.5);
let mesh = triangulate_volume(&envelope, None, false).unwrap();
assert_eq!(mesh.element_types().unwrap(), vec![ElementType::TET4]);
let v = volume_of(&mesh);
assert!((v - 0.4).abs() < 1e-12, "volume {v}");
}
#[test]
fn meshes_a_finer_extruded_plate_without_touching_its_skin() {
let coords = Handle::new(Coords::new(3).unwrap());
let envelope = extruded_plate(&coords, 3, 0.35);
let mesh = triangulate_volume(&envelope, None, false).unwrap();
let v = volume_of(&mesh);
assert!((v - 0.4).abs() < 1e-12, "volume {v}");
let peeled = super::super::skin(&mesh, crate::ops::mesh::skin::DEFAULT_ANGLE_DEG).unwrap();
assert_eq!(
peeled.cell_count(),
envelope.cell_count(),
"the skin is the envelope, facet for facet"
);
}
#[test]
fn every_node_it_puts_on_the_skin_lies_on_the_envelope() {
let coords = Handle::new(Coords::new(3).unwrap());
let envelope = extruded_plate(&coords, 5, 0.25);
let given: Vec<Vec<f64>> = {
let c = coords.read();
c.iter_live()
.map(|id| c.position(id).unwrap().to_vec())
.collect()
};
let mesh = triangulate_volume(&envelope, None, true).unwrap();
assert!((volume_of(&mesh) - 0.4).abs() < 1e-12);
let dist = |a: &[f64], b: &[f64]| -> f64 {
a.iter()
.zip(b)
.map(|(x, y)| (x - y) * (x - y))
.sum::<f64>()
.sqrt()
};
let peeled = super::super::skin(&mesh, crate::ops::mesh::skin::DEFAULT_ANGLE_DEG).unwrap();
let mut checked = 0;
for (si, &n) in peeled.cell_counts().unwrap().iter().enumerate() {
for ci in 0..n {
for k in 0..3 {
let p = peeled.node(si, ci, k).unwrap().position().unwrap();
if given.iter().any(|q| q == &p) {
continue; }
let on_a_segment = given.iter().enumerate().any(|(i, a)| {
given[i + 1..].iter().any(|b| {
let len = dist(a, b);
len > 0.0 && (dist(a, &p) + dist(&p, b) - len).abs() < 1e-12 * len
})
});
assert!(on_a_segment, "skin node {p:?} is off the envelope");
checked += 1;
}
}
}
assert!(checked > 0, "nothing was added, so nothing was checked");
}
fn shape_of(p: &[Vec<f64>; 4]) -> (f64, f64) {
const EDGES: [(usize, usize, usize, usize); 6] = [
(0, 1, 2, 3),
(0, 2, 1, 3),
(0, 3, 1, 2),
(1, 2, 0, 3),
(1, 3, 0, 2),
(2, 3, 0, 1),
];
let sub = |a: &[f64], b: &[f64]| [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
let cross = |a: [f64; 3], b: [f64; 3]| {
[
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
};
let volume = dot(
sub(&p[1], &p[0]),
cross(sub(&p[2], &p[0]), sub(&p[3], &p[0])),
)
.abs()
/ 6.0;
let mut worst = f64::INFINITY;
for (a, b, c, d) in EDGES {
let e = sub(&p[b], &p[a]);
let len = dot(e, e).sqrt();
let unit = [e[0] / len, e[1] / len, e[2] / len];
let flatten = |x: &[f64]| {
let w = sub(x, &p[a]);
let along = dot(w, unit);
[
w[0] - along * unit[0],
w[1] - along * unit[1],
w[2] - along * unit[2],
]
};
let (u, w) = (flatten(&p[c]), flatten(&p[d]));
let cos = (dot(u, w) / (dot(u, u).sqrt() * dot(w, w).sqrt())).clamp(-1.0, 1.0);
worst = worst.min(cos.acos().to_degrees());
}
(worst, volume)
}
#[test]
fn the_cells_are_shaped_well_enough_to_compute_with() {
let coords = Handle::new(Coords::new(3).unwrap());
let envelope = extruded_plate(&coords, 6, 0.2);
let mesh = triangulate_volume(&envelope, None, true).unwrap();
let n = tet_count(&mesh);
let mut angles = Vec::with_capacity(n);
let mut volumes = Vec::with_capacity(n);
for ci in 0..n {
let p: [Vec<f64>; 4] =
std::array::from_fn(|k| mesh.node(0, ci, k).unwrap().position().unwrap());
let (angle, volume) = shape_of(&p);
angles.push(angle);
volumes.push(volume);
}
angles.sort_by(|a, b| a.partial_cmp(b).unwrap());
let median = angles[n / 2];
assert!(median > 30.0, "median dihedral angle is only {median:.1}°");
let pinched = angles.iter().filter(|&&a| a < 10.0).count();
assert!(
100 * pinched < 6 * n,
"{pinched} of {n} cells are under 10°"
);
let mean: f64 = volumes.iter().sum::<f64>() / n as f64;
let flattest = volumes.iter().cloned().fold(f64::INFINITY, f64::min) / mean;
assert!(
flattest > 1e-12,
"flattest cell is {flattest:.2e} of the mean"
);
}
#[test]
fn a_flat_cell_nothing_can_reach_is_named_rather_than_returned() {
let coords = Handle::new(Coords::new(3).unwrap());
let (envelope, _) = subdivided_blob(&coords, 3);
let env = Envelope::extract(&envelope, &NoCancel).unwrap();
let mesh = TetMesh::delaunay(env.points(), &NoCancel).unwrap();
let inside = vec![true; mesh.slot_count()];
let (_, v) = mesh.iter().next().expect("a non-empty triangulation");
let msg = degenerate(&mesh, &[(v, 1e-9)]).to_string();
assert!(msg.contains("flat cell"), "{msg}");
assert!(msg.contains("Refine the surface mesh"), "{msg}");
assert!(msg.contains("around ("), "{msg}");
let flagged = smooth::stubborn(&mesh, &inside, env.points().len(), DEGENERATE_SHAPE);
assert!(
flagged.is_empty(),
"{} sound cell(s) were called degenerate",
flagged.len()
);
}
#[test]
fn the_blob_that_used_to_carry_a_hopeless_cell_now_meshes_strictly() {
let coords = Handle::new(Coords::new(3).unwrap());
let (envelope, volume) = subdivided_blob(&coords, 3);
let mesh = triangulate_volume(&envelope, None, false).unwrap();
let v = volume_of(&mesh);
assert!((v - volume).abs() < 1e-9 * volume, "volume {v} vs {volume}");
}
#[test]
fn rejects_a_bad_size() {
let coords = Handle::new(Coords::new(3).unwrap());
let nodes = box_nodes(&coords, [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]);
let err = triangulate_volume(&surface(&coords, &nodes, &BOX_FACETS), Some(0.0), false)
.unwrap_err();
assert!(err.to_string().contains("size must be > 0"), "{err}");
}
#[test]
fn stops_on_a_preset_cancellation_flag() {
use std::sync::atomic::AtomicBool;
let coords = Handle::new(Coords::new(3).unwrap());
let nodes = box_nodes(&coords, [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]);
let flag = AtomicBool::new(true);
let err = triangulate_volume_cancellable(
&surface(&coords, &nodes, &BOX_FACETS),
None,
false,
&flag,
)
.unwrap_err();
assert!(matches!(err, PyrucastError::Interrupted));
}
}