pub(crate) mod geometry;
mod query;
use std::fmt;
use std::sync::Arc;
use glam::DVec3;
pub use self::query::MeshHit;
pub(crate) use self::query::{MeshScratch, PlacedMesh};
use crate::broadphase::Bvh;
use crate::collider::Aabb;
#[derive(Clone)]
pub struct TriangleMesh {
data: Arc<MeshData>,
}
#[derive(Clone)]
struct MeshData {
vertices: Vec<DVec3>,
triangles: Vec<[u32; 3]>,
normals: Vec<DVec3>,
active: Vec<u8>,
bvh: Bvh,
bounds: Aabb,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MeshError {
NoTriangles,
TooManyTriangles {
count: usize,
},
NonFiniteVertex {
index: usize,
},
IndexOutOfRange {
triangle: usize,
index: u32,
},
DegenerateTriangle {
triangle: usize,
},
}
impl fmt::Display for MeshError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoTriangles => write!(f, "a triangle mesh needs at least one triangle"),
Self::TooManyTriangles { count } => {
write!(
f,
"a triangle mesh has at most 2^32 - 1 triangles, not {count}"
)
}
Self::NonFiniteVertex { index } => {
write!(f, "mesh vertex {index} is not finite")
}
Self::IndexOutOfRange { triangle, index } => {
write!(
f,
"mesh triangle {triangle} names vertex {index}, which does not exist"
)
}
Self::DegenerateTriangle { triangle } => {
write!(f, "mesh triangle {triangle} is degenerate")
}
}
}
}
impl std::error::Error for MeshError {}
impl TriangleMesh {
pub const MIN_ASPECT: f64 = 1.0e-6;
pub const ACTIVE_EDGE_COSINE: f64 = 0.996_194_698_091_745_5;
const BACK_TO_BACK_COSINE: f64 = 0.999_847_695_156_391_2;
pub fn new(vertices: &[DVec3], triangles: &[[u32; 3]]) -> Result<Self, MeshError> {
if triangles.is_empty() {
return Err(MeshError::NoTriangles);
}
if u32::try_from(triangles.len()).is_err() {
return Err(MeshError::TooManyTriangles {
count: triangles.len(),
});
}
if let Some(index) = vertices.iter().position(|v| !v.is_finite()) {
return Err(MeshError::NonFiniteVertex { index });
}
let mut normals = Vec::with_capacity(triangles.len());
for (triangle, indices) in triangles.iter().enumerate() {
if let Some(&index) = indices.iter().find(|&&i| i as usize >= vertices.len()) {
return Err(MeshError::IndexOutOfRange { triangle, index });
}
let [a, b, c] = indices.map(|i| vertices[i as usize]);
let cross = (b - a).cross(c - a);
let longest = (b - a)
.length_squared()
.max((c - b).length_squared())
.max((a - c).length_squared());
let twice_area = cross.length();
if !twice_area.is_finite() || twice_area <= Self::MIN_ASPECT * longest {
return Err(MeshError::DegenerateTriangle { triangle });
}
normals.push(cross.normalize());
}
let active = active_edges(vertices, triangles, &normals);
let boxes: Vec<(Aabb, u32)> = triangles
.iter()
.enumerate()
.map(|(index, t)| {
(
triangle_bounds(&t.map(|i| vertices[i as usize])),
index as u32,
)
})
.collect();
let bounds = boxes
.iter()
.fold(Aabb::EMPTY, |bounds, (aabb, _)| bounds.union(*aabb));
Ok(Self {
data: Arc::new(MeshData {
vertices: vertices.to_vec(),
triangles: triangles.to_vec(),
normals,
active,
bvh: Bvh::build(boxes),
bounds,
}),
})
}
#[must_use]
pub fn collide_with_all_edges(mut self) -> Self {
Arc::make_mut(&mut self.data).active.fill(0b111);
self
}
#[must_use]
pub fn vertices(&self) -> &[DVec3] {
&self.data.vertices
}
#[must_use]
pub fn triangles(&self) -> &[[u32; 3]] {
&self.data.triangles
}
#[must_use]
pub fn triangle_count(&self) -> usize {
self.data.triangles.len()
}
#[must_use]
pub fn corners(&self, index: usize) -> [DVec3; 3] {
self.data.triangles[index].map(|i| self.data.vertices[i as usize])
}
#[must_use]
pub fn normal(&self, index: usize) -> DVec3 {
self.data.normals[index]
}
#[must_use]
pub fn active_edges(&self, index: usize) -> u8 {
self.data.active[index]
}
#[must_use]
pub fn bounds(&self) -> Aabb {
self.data.bounds
}
pub(crate) fn bvh(&self) -> &Bvh {
&self.data.bvh
}
}
impl PartialEq for TriangleMesh {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.data, &other.data)
|| (self.data.vertices == other.data.vertices
&& self.data.triangles == other.data.triangles
&& self.data.active == other.data.active)
}
}
impl fmt::Debug for TriangleMesh {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TriangleMesh")
.field("vertices", &self.data.vertices.len())
.field("triangles", &self.data.triangles.len())
.field("bounds", &self.data.bounds)
.finish()
}
}
pub(crate) fn triangle_bounds(corners: &[DVec3; 3]) -> Aabb {
Aabb::new(
corners[0].min(corners[1]).min(corners[2]),
corners[0].max(corners[1]).max(corners[2]),
)
}
fn active_edges(vertices: &[DVec3], triangles: &[[u32; 3]], normals: &[DVec3]) -> Vec<u8> {
let bits = |v: DVec3| v.to_array().map(|x| if x == 0.0 { 0 } else { x.to_bits() });
let mut order: Vec<u32> = (0..vertices.len() as u32).collect();
order.sort_unstable_by_key(|&i| (bits(vertices[i as usize]), i));
let mut welded = vec![0u32; vertices.len()];
let mut run = 0usize;
for k in 0..order.len() {
if bits(vertices[order[k] as usize]) != bits(vertices[order[run] as usize]) {
run = k;
}
welded[order[k] as usize] = order[run];
}
let mut edges: Vec<(u32, u32, u32, u8)> = Vec::with_capacity(triangles.len() * 3);
for (t, indices) in triangles.iter().enumerate() {
for e in 0..3u8 {
let p = welded[indices[e as usize] as usize];
let q = welded[indices[(e as usize + 1) % 3] as usize];
edges.push((p.min(q), p.max(q), t as u32, e));
}
}
edges.sort_unstable();
let mut active = vec![0u8; triangles.len()];
let mut start = 0;
while start < edges.len() {
let key = (edges[start].0, edges[start].1);
let mut end = start + 1;
while end < edges.len() && (edges[end].0, edges[end].1) == key {
end += 1;
}
let shared = &edges[start..end];
if let [(_, _, t1, e1), (_, _, t2, e2)] = *shared {
let direction = |t: u32, e: u8| {
let indices = triangles[t as usize];
vertices[indices[(e as usize + 1) % 3] as usize]
- vertices[indices[e as usize] as usize]
};
let (n1, n2) = (normals[t1 as usize], normals[t2 as usize]);
if is_edge_active(n1, n2, direction(t1, e1)) {
active[t1 as usize] |= 1 << e1;
}
if is_edge_active(n2, n1, direction(t2, e2)) {
active[t2 as usize] |= 1 << e2;
}
} else {
for &(_, _, t, e) in shared {
active[t as usize] |= 1 << e;
}
}
start = end;
}
active
}
fn is_edge_active(n1: DVec3, n2: DVec3, direction: DVec3) -> bool {
let cosine = n1.dot(n2);
if cosine < -TriangleMesh::BACK_TO_BACK_COSINE {
return true;
}
if n1.cross(n2).dot(direction) < 0.0 {
return false;
}
cosine < TriangleMesh::ACTIVE_EDGE_COSINE
}
#[cfg(test)]
mod tests {
use super::*;
fn quad() -> (Vec<DVec3>, Vec<[u32; 3]>) {
(
vec![
DVec3::new(-1.0, 0.0, -1.0),
DVec3::new(1.0, 0.0, -1.0),
DVec3::new(1.0, 0.0, 1.0),
DVec3::new(-1.0, 0.0, 1.0),
],
vec![[0, 3, 2], [0, 2, 1]],
)
}
#[test]
fn a_mesh_refuses_what_cannot_be_collided_with() {
let (vertices, triangles) = quad();
assert!(TriangleMesh::new(&vertices, &triangles).is_ok());
assert_eq!(
TriangleMesh::new(&vertices, &[]),
Err(MeshError::NoTriangles)
);
let mut poisoned = vertices.clone();
poisoned[2].y = f64::NAN;
assert_eq!(
TriangleMesh::new(&poisoned, &triangles),
Err(MeshError::NonFiniteVertex { index: 2 })
);
poisoned[2].y = f64::INFINITY;
assert_eq!(
TriangleMesh::new(&poisoned, &triangles),
Err(MeshError::NonFiniteVertex { index: 2 })
);
assert_eq!(
TriangleMesh::new(&vertices, &[[0, 3, 2], [0, 2, 4]]),
Err(MeshError::IndexOutOfRange {
triangle: 1,
index: 4
})
);
for bad in [[0, 0, 2], [0, 1, 1]] {
assert_eq!(
TriangleMesh::new(&vertices, &[[0, 3, 2], bad]),
Err(MeshError::DegenerateTriangle { triangle: 1 })
);
}
let line = [DVec3::ZERO, DVec3::X, DVec3::X * 2.0];
assert_eq!(
TriangleMesh::new(&line, &[[0, 1, 2]]),
Err(MeshError::DegenerateTriangle { triangle: 0 })
);
let sliver = [DVec3::ZERO, DVec3::X, DVec3::new(0.5, 1.0e-7, 0.0)];
assert_eq!(
TriangleMesh::new(&sliver, &[[0, 1, 2]]),
Err(MeshError::DegenerateTriangle { triangle: 0 })
);
let thin = [DVec3::ZERO, DVec3::X, DVec3::new(0.5, 1.0e-5, 0.0)];
assert!(TriangleMesh::new(&thin, &[[0, 1, 2]]).is_ok());
}
#[test]
fn a_flat_seam_is_inactive_and_the_outline_active() {
let (vertices, triangles) = quad();
let mesh = TriangleMesh::new(&vertices, &triangles).unwrap();
assert_eq!(mesh.active_edges(0), 0b011);
assert_eq!(mesh.active_edges(1), 0b110);
assert_eq!(mesh.normal(0), DVec3::Y);
let all = mesh.collide_with_all_edges();
assert_eq!((all.active_edges(0), all.active_edges(1)), (0b111, 0b111));
}
#[test]
fn repeated_corners_weld_into_one_seam() {
let (vertices, triangles) = quad();
let unshared: Vec<DVec3> = triangles
.iter()
.flat_map(|t| t.map(|i| vertices[i as usize]))
.collect();
let mesh = TriangleMesh::new(&unshared, &[[0, 1, 2], [3, 4, 5]]).unwrap();
assert_eq!(mesh.active_edges(0), 0b011);
assert_eq!(mesh.active_edges(1), 0b110);
}
#[test]
fn a_stairs_nose_is_active_and_its_crease_is_not() {
let vertices = [
DVec3::new(-1.0, 0.0, 0.0),
DVec3::new(-1.0, 0.0, 1.0),
DVec3::new(0.0, 0.0, 0.0),
DVec3::new(0.0, 0.0, 1.0),
DVec3::new(0.0, 1.0, 0.0),
DVec3::new(0.0, 1.0, 1.0),
DVec3::new(1.0, 1.0, 0.0),
DVec3::new(1.0, 1.0, 1.0),
];
let triangles = [
[0, 1, 3],
[0, 3, 2], [2, 3, 5],
[2, 5, 4], [4, 5, 7],
[4, 7, 6], ];
let mesh = TriangleMesh::new(&vertices, &triangles).unwrap();
assert_eq!(mesh.normal(0), DVec3::Y);
assert_eq!(mesh.normal(2), -DVec3::X);
assert_eq!(mesh.normal(4), DVec3::Y);
assert_eq!(mesh.active_edges(1) & 0b010, 0, "the crease");
assert_ne!(mesh.active_edges(3) & 0b010, 0, "the nose");
assert_eq!(mesh.active_edges(4) & 0b100, 0, "the tread's seam");
assert_eq!(mesh.active_edges(5) & 0b001, 0, "the tread's seam");
}
}