Add aabb check for much fps!

main
Elijah C. Voigt 1 year ago
parent 41f51715ca
commit a73b97191d

@ -1,3 +1,5 @@
use bevy::{math::Vec3A, render::primitives::Aabb};
use crate::prelude::*;
/// Hit data for 3d objects in Global (not Local) space and the distance from the Camera
@ -49,10 +51,52 @@ impl Triangle {
}
}
pub(crate) fn intersects_aabb_3d(ray: &Ray3d, aabb: &Aabb, gt: &GlobalTransform) -> Option<Hit3d> {
let world_to_model = gt.compute_matrix().inverse();
let ray_dir: Vec3A = world_to_model.transform_vector3(*ray.direction).into();
let ray_origin: Vec3A = world_to_model.transform_point3(ray.origin).into();
let t0 = (aabb.min() - ray_origin) / ray_dir;
let t1 = (aabb.max() - ray_origin) / ray_dir;
let t_min = t0.min(t1);
let t_max = t0.max(t1);
let mut hit_near = t_min.x;
let mut hit_far = t_max.x;
if hit_near > t_max.y || t_min.y > hit_far {
return None;
}
if t_min.y > hit_near {
hit_near = t_min.y;
}
if t_max.y < hit_far {
hit_far = t_max.y;
}
if (hit_near > t_max.z) || (t_min.z > hit_far) {
return None;
}
if t_min.z > hit_near {
hit_near = t_min.z;
}
if t_max.z < hit_far {
hit_far = t_max.z;
}
Some(Hit3d { distance: (hit_near + hit_far) / 2.0 })
}
/// Heavily synthesized from these two resources:
/// * Textbook: https://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/ray-triangle-intersection-geometric-solution.html
/// * Example: https://github.com/aevyrie/bevy_mod_raycast/blob/435d8ef100738797161ac3a9b910ea346a4ed6e6/src/raycast.rs#L43
pub(crate) fn intersects3d(ray: &Ray3d, mesh: &Mesh, gt: &GlobalTransform) -> Option<Hit3d> {
// First do an Aabb intersection test
if let Some(aabb) = mesh.compute_aabb() {
// Do the Aabb test
if let Some(_) = intersects_aabb_3d(ray, &aabb, gt) {
// If it passes that do the real intersection test
let attr = MeshVertexAttribute::new("Vertex_Position", 0, VertexFormat::Float32x3);
if let Some(verts) = mesh.attribute(attr) {
if let Some(idxs) = mesh.indices() {
@ -114,4 +158,10 @@ pub(crate) fn intersects3d(ray: &Ray3d, mesh: &Mesh, gt: &GlobalTransform) -> Op
} else {
None
}
} else {
None
}
} else {
None
}
}

Loading…
Cancel
Save