use glam::{DMat3, DQuat, DVec3};
use super::TriangleMesh;
use super::geometry::{
Cuboid, box_triangle_axes, closest_on_triangle, ray_triangle, segment_triangle,
sweep_into_triangle,
};
use crate::broadphase::{BvhHit, Ray, Segment};
use crate::collider::{Aabb, Capsule, Sphere};
use crate::components::Transform;
use crate::contact::shape::ContactShape;
use crate::query::{
AcceleratedPath, ArcHit, OverlapHit, Penetration, ShapeHit, contact_where, support,
};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MeshHit {
pub triangle: u32,
pub barycentric: DVec3,
pub hit: ShapeHit,
}
#[derive(Debug, Default)]
pub(crate) struct MeshScratch {
stack: Vec<u32>,
found: Vec<u32>,
hits: Vec<BvhHit>,
}
impl TriangleMesh {
#[must_use]
pub fn cast_ray(&self, ray: &Ray) -> Option<MeshHit> {
self.cast_ray_with(ray, &mut MeshScratch::default())
}
pub(crate) fn cast_ray_with(&self, ray: &Ray, scratch: &mut MeshScratch) -> Option<MeshHit> {
self.bvh()
.traverse_ray_into(ray, &mut scratch.stack, &mut scratch.hits);
let mut best: Option<(f64, u32, DVec3)> = None;
for leaf in &scratch.hits {
if best.is_some_and(|(t, _, _)| leaf.t > t) {
continue;
}
let index = leaf.element_id;
let Some((t, weights)) =
ray_triangle(ray.origin, ray.dir, &self.corners(index as usize))
else {
continue;
};
if t < ray.t_min || t > ray.t_max {
continue;
}
if best.is_none_or(|(bt, bi, _)| t < bt || (t == bt && index < bi)) {
best = Some((t, index, weights));
}
}
let (t, triangle, barycentric) = best?;
let n = self.normal(triangle as usize);
Some(MeshHit {
triangle,
barycentric,
hit: ShapeHit {
t,
point: ray.origin + ray.dir * t,
normal: if ray.dir.dot(n) <= 0.0 { n } else { -n },
started_inside: false,
part: 0,
},
})
}
#[must_use]
pub fn sweep_sphere(&self, segment: &Segment, radius: f64) -> Option<MeshHit> {
self.sweep_with(segment, radius, DVec3::ZERO, &mut MeshScratch::default())
}
#[must_use]
pub fn sweep_capsule(
&self,
segment: &Segment,
radius: f64,
half_height: f64,
) -> Option<MeshHit> {
self.sweep_with(
segment,
radius,
DVec3::Y * half_height,
&mut MeshScratch::default(),
)
}
pub(crate) fn sweep_with(
&self,
segment: &Segment,
radius: f64,
half: DVec3,
scratch: &mut MeshScratch,
) -> Option<MeshHit> {
self.sweep_where_with(segment, radius, half, scratch, |_| true)
}
fn sweep_where_with(
&self,
segment: &Segment,
radius: f64,
half: DVec3,
scratch: &mut MeshScratch,
accept: impl Fn(&ShapeHit) -> bool,
) -> Option<MeshHit> {
let (start, dir) = (segment.start, segment.end - segment.start);
let reach = DVec3::splat(radius) + half.abs();
let bounds = Aabb::new(
start.min(segment.end) - reach,
start.max(segment.end) + reach,
);
self.bvh()
.traverse_aabb_into(&bounds, &mut scratch.stack, &mut scratch.found);
let mut best: Option<MeshHit> = None;
for &index in &scratch.found {
let corners = self.corners(index as usize);
let normal = self.normal(index as usize);
let inside =
segment_triangle(start - half, start + half, &corners, normal).distance() <= radius;
let t = if inside {
Some(0.0)
} else {
sweep_into_triangle(start, dir, &corners, half, radius)
};
let Some(t) = t else { continue };
if !best.is_none_or(|hit| t < hit.hit.t || (t == hit.hit.t && index < hit.triangle)) {
continue;
}
let centre = start + dir * t;
let closest = segment_triangle(centre - half, centre + half, &corners, normal);
let away = closest.on_segment - closest.on_triangle.point;
let hit = ShapeHit {
t,
point: closest.on_triangle.point,
normal: facing(away, away.length(), normal, centre - corners[0]),
started_inside: inside,
part: 0,
};
if accept(&hit) {
best = Some(MeshHit {
triangle: index,
barycentric: closest.on_triangle.barycentric,
hit,
});
}
}
best
}
#[must_use]
pub fn overlaps_sphere(&self, sphere: &Sphere) -> bool {
self.overlaps_sphere_with(sphere, &mut MeshScratch::default())
}
pub(crate) fn overlaps_sphere_with(&self, sphere: &Sphere, scratch: &mut MeshScratch) -> bool {
self.bvh()
.traverse_aabb_into(&sphere.aabb(), &mut scratch.stack, &mut scratch.found);
scratch.found.iter().any(|&index| {
let corners = self.corners(index as usize);
(closest_on_triangle(sphere.centre, &corners).point - sphere.centre).length_squared()
<= sphere.radius * sphere.radius
})
}
#[must_use]
pub fn overlaps_aabb(&self, aabb: &Aabb) -> bool {
self.overlaps_box_with(
aabb.centre(),
DQuat::IDENTITY,
aabb.extents() * 0.5,
&mut MeshScratch::default(),
)
}
pub(crate) fn overlaps_box_with(
&self,
centre: DVec3,
rotation: DQuat,
half: DVec3,
scratch: &mut MeshScratch,
) -> bool {
let m = DMat3::from_quat(rotation);
let cuboid = Cuboid {
centre,
axes: [m.x_axis, m.y_axis, m.z_axis],
half,
};
let reach = DVec3::new(
cuboid.radius(DVec3::X),
cuboid.radius(DVec3::Y),
cuboid.radius(DVec3::Z),
);
self.bvh().traverse_aabb_into(
&Aabb::from_centre_half(centre, reach),
&mut scratch.stack,
&mut scratch.found,
);
scratch.found.iter().any(|&index| {
box_triangle_axes(
&cuboid,
&self.corners(index as usize),
self.normal(index as usize),
)
.into_iter()
.flatten()
.all(|axis| axis.separation <= 0.0)
})
}
#[must_use]
pub fn capsule_penetration(&self, capsule: &Capsule) -> Option<Penetration> {
self.capsule_penetration_with(
capsule.centre,
DVec3::Y * capsule.half_height,
capsule.radius,
&mut MeshScratch::default(),
)
}
pub(crate) fn capsule_penetration_with(
&self,
centre: DVec3,
half: DVec3,
radius: f64,
scratch: &mut MeshScratch,
) -> Option<Penetration> {
let reach = DVec3::splat(radius) + half.abs();
self.bvh().traverse_aabb_into(
&Aabb::new(centre - reach, centre + reach),
&mut scratch.stack,
&mut scratch.found,
);
let (p0, p1) = (centre - half, centre + half);
let mut deepest: Option<(f64, u32, DVec3)> = None;
for &index in &scratch.found {
let corners = self.corners(index as usize);
let normal = self.normal(index as usize);
let closest = segment_triangle(p0, p1, &corners, normal);
let away = closest.on_segment - closest.on_triangle.point;
let distance = away.length();
if distance >= radius {
continue;
}
let out = facing(away, distance, normal, centre - corners[0]);
let depth = if distance > 0.0 {
radius - distance
} else {
let behind = (-out.dot(p0 - corners[0]))
.max(-out.dot(p1 - corners[0]))
.max(0.0);
radius + behind
};
if deepest.is_none_or(|(d, i, _)| depth > d || (depth == d && index < i)) {
deepest = Some((depth, index, out));
}
}
deepest.map(|(depth, _, normal)| Penetration { normal, depth })
}
}
fn facing(away: DVec3, distance: f64, normal: DVec3, offset: DVec3) -> DVec3 {
if distance > 0.0 {
away / distance
} else if normal.dot(offset) >= 0.0 {
normal
} else {
-normal
}
}
#[derive(Debug, Clone)]
pub(crate) struct PlacedMesh {
pub(crate) mesh: TriangleMesh,
pub(crate) transform: Transform,
pub(crate) bounds: Aabb,
}
impl PlacedMesh {
pub(crate) fn new(mesh: TriangleMesh, transform: Transform) -> Self {
let local = mesh.bounds();
let m = DMat3::from_quat(transform.rotation);
let half = local.extents() * 0.5;
let reach = DVec3::new(
m.x_axis.x.abs() * half.x + m.y_axis.x.abs() * half.y + m.z_axis.x.abs() * half.z,
m.x_axis.y.abs() * half.x + m.y_axis.y.abs() * half.y + m.z_axis.y.abs() * half.z,
m.x_axis.z.abs() * half.x + m.y_axis.z.abs() * half.y + m.z_axis.z.abs() * half.z,
);
let bounds = Aabb::from_centre_half(to_world(&transform, local.centre()), reach);
Self {
mesh,
transform,
bounds,
}
}
fn to_local(&self, point: DVec3) -> DVec3 {
self.transform.rotation.inverse() * (point - self.transform.position)
}
fn hit_to_world(&self, hit: ShapeHit) -> ShapeHit {
ShapeHit {
point: to_world(&self.transform, hit.point),
normal: self.transform.rotation * hit.normal,
..hit
}
}
pub(crate) fn cast_ray(&self, ray: &Ray, scratch: &mut MeshScratch) -> Option<ShapeHit> {
let local = Ray {
origin: self.to_local(ray.origin),
dir: self.transform.rotation.inverse() * ray.dir,
..*ray
};
let hit = self.mesh.cast_ray_with(&local, scratch)?.hit;
Some(ShapeHit {
point: ray.origin + ray.dir * hit.t,
normal: self.transform.rotation * hit.normal,
..hit
})
}
pub(crate) fn sweep(
&self,
segment: &Segment,
radius: f64,
half: DVec3,
scratch: &mut MeshScratch,
) -> Option<ShapeHit> {
self.sweep_where(segment, radius, half, scratch, |_| true)
}
pub(crate) fn sweep_where(
&self,
segment: &Segment,
radius: f64,
half: DVec3,
scratch: &mut MeshScratch,
accept: impl Fn(&ShapeHit) -> bool,
) -> Option<ShapeHit> {
let local = Segment::new(self.to_local(segment.start), self.to_local(segment.end));
let half = self.transform.rotation.inverse() * half;
let hit = self
.mesh
.sweep_where_with(&local, radius, half, scratch, |hit| {
accept(&self.hit_to_world(*hit))
})?;
Some(self.hit_to_world(hit.hit))
}
pub(crate) fn sweep_arc_where(
&self,
path: &AcceleratedPath,
radius: f64,
half: DVec3,
scratch: &mut MeshScratch,
accept: impl Fn(&ArcHit) -> bool,
) -> Option<ArcHit> {
let turn = self.transform.rotation.inverse();
let local = path.in_frame(self.transform.position, turn);
let half = turn * half;
let reach = DVec3::splat(radius) + half.abs();
let bounds = local.bounds();
self.mesh.bvh().traverse_aabb_into(
&Aabb::new(bounds.min - reach, bounds.max + reach),
&mut scratch.stack,
&mut scratch.found,
);
let separation = |index: u32, p0: DVec3, p1: DVec3| {
let corners = self.mesh.corners(index as usize);
let normal = self.mesh.normal(index as usize);
let closest = segment_triangle(p0, p1, &corners, normal);
let away = closest.on_segment - closest.on_triangle.point;
let distance = away.length();
let centre = (p0 + p1) * 0.5;
(
distance - radius,
facing(away, distance, normal, centre - corners[0]),
closest.on_triangle.point,
)
};
let world_hit = |hit: ArcHit| ArcHit {
point: to_world(&self.transform, hit.point),
normal: self.transform.rotation * hit.normal,
..hit
};
let mut best: Option<(u32, ArcHit)> = None;
for &index in &scratch.found {
let triangle = ContactShape::Triangle {
corners: self.mesh.corners(index as usize),
normal: self.mesh.normal(index as usize),
active_edges: self.mesh.active_edges(index as usize),
};
let Some(hit) = contact_where(
&local,
half,
radius,
|direction| support(&triangle, direction),
|p0, p1| {
let (distance, normal, _) = separation(index, p0, p1);
(distance, normal)
},
|time, _| {
let centre = local.position_at(time);
separation(index, centre - half, centre + half).2
},
|hit| accept(&world_hit(*hit)),
) else {
continue;
};
let hit = world_hit(hit);
let time = hit.time;
if best.is_none_or(|(bi, bh)| time < bh.time || (time == bh.time && index < bi)) {
best = Some((index, hit));
}
}
best.map(|(_, hit)| hit)
}
pub(crate) fn sphere_overlap(
&self,
sphere: &Sphere,
scratch: &mut MeshScratch,
) -> Option<OverlapHit> {
let penetration =
self.turned_capsule_penetration(sphere.centre, DVec3::ZERO, sphere.radius, scratch)?;
Some(OverlapHit::from_penetration(sphere, penetration))
}
pub(crate) fn overlaps_aabb(&self, aabb: &Aabb, scratch: &mut MeshScratch) -> bool {
self.mesh.overlaps_box_with(
self.to_local(aabb.centre()),
self.transform.rotation.inverse(),
aabb.extents() * 0.5,
scratch,
)
}
pub(crate) fn capsule_penetration(
&self,
capsule: &Capsule,
scratch: &mut MeshScratch,
) -> Option<Penetration> {
self.turned_capsule_penetration(
capsule.centre,
DVec3::Y * capsule.half_height,
capsule.radius,
scratch,
)
}
pub(crate) fn turned_capsule_penetration(
&self,
centre: DVec3,
half: DVec3,
radius: f64,
scratch: &mut MeshScratch,
) -> Option<Penetration> {
let penetration = self.mesh.capsule_penetration_with(
self.to_local(centre),
self.transform.rotation.inverse() * half,
radius,
scratch,
)?;
Some(Penetration {
normal: self.transform.rotation * penetration.normal,
..penetration
})
}
}
fn to_world(transform: &Transform, local: DVec3) -> DVec3 {
transform.position + transform.rotation * local
}
#[cfg(test)]
mod tests {
use super::*;
fn two() -> TriangleMesh {
TriangleMesh::new(
&[
DVec3::new(0.0, 0.0, 0.0),
DVec3::new(0.0, 0.0, 1.0),
DVec3::new(1.0, 0.0, 0.0),
DVec3::new(2.0, 0.0, 0.0),
DVec3::new(2.0, 0.0, 1.0),
DVec3::new(3.0, 0.0, 0.0),
],
&[[0, 1, 2], [3, 4, 5]],
)
.unwrap()
}
fn close(a: DVec3, b: DVec3) -> bool {
(a - b).length() < 1e-12
}
#[test]
fn a_ray_names_the_triangle_and_the_point() {
let mesh = two();
let hit = mesh
.cast_ray(&Ray::new(DVec3::new(2.25, 3.0, 0.25), -DVec3::Y))
.unwrap();
assert_eq!(hit.triangle, 1);
assert!(
close(hit.barycentric, DVec3::new(0.5, 0.25, 0.25)),
"{hit:?}"
);
assert!((hit.hit.t - 3.0).abs() < 1e-15);
assert_eq!(hit.hit.normal, DVec3::Y);
let below = mesh
.cast_ray(&Ray::new(DVec3::new(0.25, -1.0, 0.25), DVec3::Y))
.unwrap();
assert_eq!(below.triangle, 0);
assert_eq!(below.hit.normal, -DVec3::Y);
assert!(
mesh.cast_ray(&Ray::new(DVec3::new(1.5, 3.0, 0.25), -DVec3::Y))
.is_none(),
"between the two"
);
}
#[test]
fn a_swept_sphere_lands_on_the_face_or_the_edge() {
let mesh = two();
let hit = mesh
.sweep_sphere(
&Segment::new(DVec3::new(2.25, 2.0, 0.25), DVec3::new(2.25, 0.0, 0.25)),
0.5,
)
.unwrap();
assert_eq!(hit.triangle, 1);
assert!((hit.hit.t - 0.75).abs() < 1e-12, "{hit:?}");
assert!(close(hit.hit.point, DVec3::new(2.25, 0.0, 0.25)), "{hit:?}");
assert!(close(hit.barycentric, DVec3::new(0.5, 0.25, 0.25)));
assert!(close(hit.hit.normal, DVec3::Y));
assert!(!hit.hit.started_inside);
let hit = mesh
.sweep_sphere(
&Segment::new(DVec3::new(0.75, 2.0, 0.75), DVec3::new(0.75, 0.0, 0.75)),
0.5,
)
.unwrap();
assert_eq!(hit.triangle, 0);
let height = 0.125f64.sqrt();
assert!((hit.hit.t - (2.0 - height) / 2.0).abs() < 1e-12, "{hit:?}");
assert!(close(hit.hit.point, DVec3::new(0.5, 0.0, 0.5)), "{hit:?}");
assert!(close(hit.barycentric, DVec3::new(0.0, 0.5, 0.5)), "{hit:?}");
}
#[test]
fn a_swept_capsule_meets_with_its_flank_or_starts_touching() {
let wall = TriangleMesh::new(
&[
DVec3::new(0.0, 0.0, 0.0),
DVec3::new(0.0, 2.0, 0.0),
DVec3::new(0.0, 2.0, 2.0),
DVec3::new(0.0, 0.0, 2.0),
],
&[[0, 2, 1], [0, 3, 2]],
)
.unwrap();
assert_eq!(wall.normal(0), -DVec3::X);
let hit = wall
.sweep_capsule(
&Segment::new(DVec3::new(-3.0, 1.0, 1.0), DVec3::new(1.0, 1.0, 1.0)),
0.5,
0.5,
)
.unwrap();
assert!((hit.hit.t - 0.625).abs() < 1e-12, "{hit:?}");
assert!(close(hit.hit.normal, -DVec3::X), "{hit:?}");
let touching = wall
.sweep_capsule(
&Segment::new(DVec3::new(-0.4, 1.0, 1.0), DVec3::new(-1.0, 1.0, 1.0)),
0.5,
0.5,
)
.unwrap();
assert_eq!(touching.hit.t, 0.0);
assert!(touching.hit.started_inside);
}
#[test]
fn overlaps_are_decided_by_the_triangles_not_their_bounds() {
let mesh = two();
let past_hypotenuse = Aabb::from_centre_half(DVec3::new(0.9, 0.0, 0.9), DVec3::splat(0.1));
assert!(!mesh.overlaps_aabb(&past_hypotenuse));
assert!(mesh.overlaps_aabb(&Aabb::from_centre_half(
DVec3::new(0.3, 0.05, 0.3),
DVec3::splat(0.1)
)));
assert!(!mesh.overlaps_sphere(&Sphere::new(DVec3::new(0.9, 0.0, 0.9), 0.1)));
assert!(mesh.overlaps_sphere(&Sphere::new(DVec3::new(0.3, 0.1, 0.3), 0.1)));
}
#[test]
fn a_sunk_capsule_is_pushed_out_along_the_normal() {
let mesh = two();
let capsule = Capsule::new(DVec3::new(0.3, 0.9, 0.3), 0.25, 0.75);
let penetration = mesh.capsule_penetration(&capsule).unwrap();
assert!(close(penetration.normal, DVec3::Y));
assert!((penetration.depth - 0.1).abs() < 1e-12, "{penetration:?}");
let turn = crate::rotation_from_scaled_axis(DVec3::X * core::f64::consts::FRAC_PI_2);
let placed = PlacedMesh::new(mesh, Transform::new(DVec3::new(5.0, 0.0, 0.0), turn));
let mut scratch = MeshScratch::default();
let hit = placed
.cast_ray(
&Ray::new(DVec3::new(5.25, -0.25, -3.0), DVec3::Z),
&mut scratch,
)
.unwrap();
assert!((hit.t - 3.0).abs() < 1e-12, "{hit:?}");
assert!(close(hit.normal, -DVec3::Z), "{hit:?}");
assert!(
placed
.bounds
.inflated(1e-12)
.contains(&Aabb::new(hit.point, hit.point))
);
}
}