Fixed frustum culling

This commit is contained in:
Thomas Forgione 2018-07-19 14:24:54 +02:00
parent 3172a0c58e
commit 674b49430f
No known key found for this signature in database
GPG Key ID: 203DAEA747F48F41
6 changed files with 179 additions and 85 deletions

View File

@ -1,8 +1,9 @@
//! This module contains everything to deal with cameras.
use nalgebra::Matrix4;
use nalgebra::Vector4;
use math::vector::Vector3;
use math::vector::{Vector2, Vector3};
use math::frustum::Frustum;
/// The trait that a render camera should implement.
@ -11,76 +12,87 @@ use math::frustum::Frustum;
pub trait RenderCamera {
/// Returns the view matrix of the camera.
fn get_view_matrix(&self) -> Matrix4<f32>;
fn view(&self) -> Matrix4<f32>;
/// Returns the perspective matrix of the camera.
fn get_perspective_matrix(&self) -> Matrix4<f32>;
fn perspective(&self) -> Matrix4<f32>;
/// Returns the product of the perspective matrix and the view matrix.
fn get_model_view_matrix(&self) -> Matrix4<f32> {
self.get_perspective_matrix() * self.get_view_matrix().try_inverse().unwrap()
fn model_view(&self) -> Matrix4<f32> {
self.perspective() * self.view()
}
/// Returns the frustum of the camera.
fn frustum(&self) -> Frustum {
Frustum::from_matrix(&self.get_model_view_matrix())
panic!();
}
}
/// Creates the pose matrix, inverse of the look at matrix.
pub fn pose(position: Vector3<f32>, target: Vector3<f32>, up: Vector3<f32>) -> Matrix4<f32> {
// This is the right way to do things
let e3 = (position - target).normalized();
// Well, ok, maybe this is not the right way, but it works
let e1 = up.cross_product(e3).normalized();
let e2 = e3.cross_product(e1);
[
[e1[0], e1[1], e1[2], 0.0],
[e2[0], e2[1], e2[2], 0.0],
[e3[0], e3[1], e3[2], 0.0],
[position[0], position[1], position[2], 1.0],
].into()
}
/// Creates a look at matrix from the center, the target pointed by the camera and the up vector.
pub fn look_at_matrix(position: [f32; 3], target: [f32; 3], up: [f32; 3]) -> Matrix4<f32> {
let f = {
let f = [
target[0] - position[0],
target[1] - position[1],
target[2] - position[2],
];
let len = f[0] * f[0] + f[1] * f[1] + f[2] * f[2];
let len = len.sqrt();
[f[0] / len, f[1] / len, f[2] / len]
};
let s = [up[1] * f[2] - up[2] * f[1],
up[2] * f[0] - up[0] * f[2],
up[0] * f[1] - up[1] * f[0]];
let s_norm = {
let len = s[0] * s[0] + s[1] * s[1] + s[2] * s[2];
let len = len.sqrt();
[s[0] / len, s[1] / len, s[2] / len]
};
let u = [f[1] * s_norm[2] - f[2] * s_norm[1],
f[2] * s_norm[0] - f[0] * s_norm[2],
f[0] * s_norm[1] - f[1] * s_norm[0]];
let p = [-position[0] * s_norm[0] - position[1] * s_norm[1] - position[2] * s_norm[2],
-position[0] * u[0] - position[1] * u[1] - position[2] * u[2],
-position[0] * f[0] - position[1] * f[1] - position[2] * f[2]];
[
[-s_norm[0], u[0], f[0], 0.0],
[-s_norm[1], u[1], f[1], 0.0],
[-s_norm[2], u[2], f[2], 0.0],
[-p[0], p[1], p[2], 1.0],
].into()
pub fn look_at(position: Vector3<f32>, target: Vector3<f32>, up: Vector3<f32>) -> Matrix4<f32> {
pose(position, target, up).try_inverse().unwrap()
}
/// Creates a perspective matrix of a camera.
pub fn perspective_matrix(aspect_ratio: f32, z_near: f32, z_far: f32) -> Matrix4<f32> {
let fov = 3.141592 / 3.0;
pub fn perspective(fov: f32, aspect_ratio: f32, z_near: f32, z_far: f32) -> Matrix4<f32> {
use num::Float;
let f = 1.0 / (fov / 2.0).tan();
let top = z_near * (fov / 2.0).tan();
let height = 2.0 * top;
let width = aspect_ratio * height;
let x = 2.0 * z_near / width;
let y = 2.0 * z_near / height;
let c = - (z_far + z_near) / (z_far - z_near);
let d = - 2.0 * z_far * z_near / (z_far - z_near);
Matrix4::new(
x, 0.0, 0.0, 0.0,
0.0, y, 0.0, 0.0,
0.0, 0.0, c, d,
0.0, 0.0, -1.0, 0.0,
)
}
/// Returns the inverse of the perspective matrix.
pub fn perspective_inverse(fov: f32, aspect_ratio: f32, z_near: f32, z_far: f32) -> Matrix4<f32> {
let top = z_near * (fov / 2.0).tan();
let height = 2.0 * top;
let width = aspect_ratio * height;
let x = 2.0 * z_near / width;
let y = 2.0 * z_near / height;
let c = - (z_far + z_near) / (z_far - z_near);
let d = - 2.0 * z_far * z_near / (z_far - z_near);
Matrix4::new(
1.0 / x, 0.0, 0.0, 0.0,
0.0, 1.0 / y, 0.0, 0.0,
0.0, 0.0, 0.0, -1.0,
0.0, 0.0, 1.0 / d, c / d,
)
[
[f / aspect_ratio , 0.0, 0.0 , 0.0],
[ 0.0 , f , 0.0 , 0.0],
[ 0.0 , 0.0, (z_far+z_near)/(z_far-z_near) , 1.0],
[ 0.0 , 0.0, -(2.0*z_far*z_near)/(z_far-z_near), 0.0],
].into()
}
/// A simple camera with its position, target and up vector.
@ -95,6 +107,9 @@ pub struct Camera {
/// The up vector of the camera.
pub up: Vector3<f32>,
/// The field of view of the camera.
pub fov: f32,
/// The minimum depth for visible things.
pub z_near: f32,
@ -109,29 +124,62 @@ pub struct Camera {
impl Camera {
/// Creates a new camera from its attributes.
pub fn new(position: Vector3<f32>, target: Vector3<f32>, up: Vector3<f32>) -> Camera {
use std::f32::consts::PI;
Camera {
position: position,
target: target,
up: up,
z_near: 0.0001,
z_far: 1000.0,
aspect_ratio: 16.0 / 9.0
aspect_ratio: 16.0 / 9.0,
fov: PI / 3.0,
}
}
/// Returns the pose matrix of the camera.
pub fn pose(&self) -> Matrix4<f32> {
pose(self.position, self.target, self.up)
}
/// Returns the view matrix of the camera, inverse of the pose.
pub fn view(&self) -> Matrix4<f32> {
look_at(self.position, self.target, self.up)
}
/// Returns the perspective matrix of the camera.
pub fn perspective(&self) -> Matrix4<f32> {
perspective(self.fov, self.aspect_ratio, self.z_near, self.z_far)
}
/// Returns the inverse of the perspective matrix of the camera.
pub fn perspective_inverse(&self) -> Matrix4<f32> {
perspective_inverse(self.fov, self.aspect_ratio, self.z_near, self.z_far)
}
/// Returns the frustum of the camera.
pub fn frustum(&self) -> Frustum {
RenderCamera::frustum(self)
Frustum::from_matrix(&(self.perspective() * self.view()))
}
/// Unprojects a 2D point (x, y) in the 3D world.
///
/// The coordinates must be in [-1.0, 1.0]
pub fn unproject(&self, point: Vector2<f32>) -> Vector3<f32> {
let point = Vector4::new(point[0], point[1], 0.5, 1.0);
let v = self.pose() * self.perspective_inverse() * point;
Vector3::new(v[0] / v[3], v[1] / v[3], v[2] / v[3])
}
}
impl RenderCamera for Camera {
fn get_view_matrix(&self) -> Matrix4<f32> {
look_at_matrix(self.position.into(), self.target.into(), self.up.into())
fn view(&self) -> Matrix4<f32> {
self.view()
}
fn get_perspective_matrix(&self) -> Matrix4<f32> {
perspective_matrix(self.aspect_ratio, self.z_near, self.z_far)
fn perspective(&self) -> Matrix4<f32> {
self.perspective()
}
}

View File

@ -95,6 +95,16 @@ macro_rules! make_bounding_box {
ret
}
/// Returns true if the point is inside the bounding box.
pub fn contains_point(&self, point: $vector<T>) -> bool {
for i in 0 .. $size {
if self.min()[i] > point[i] || point[i] > self.max()[i] {
return false;
}
}
true
}
}
}
@ -183,4 +193,21 @@ mod tests {
let bb2 = b2.intersection(&b1);
assert_eq!(bb1, bb2);
}
#[test]
fn contains_point() {
let b1 = BoundingBox3::new(
Vector3::new(0.0, 0.0, 0.0),
Vector3::new(2.0, 2.0, 2.0),
);
assert_eq!(b1.contains_point(Vector3::new(1.0, 1.0, 1.0)), true);
assert_eq!(b1.contains_point(Vector3::new(1.5, 0.5, 1.0)), true);
assert_eq!(b1.contains_point(Vector3::new(1.5, -0.5, 1.0)), false);
assert_eq!(b1.contains_point(Vector3::new(1.5, 0.5, -1.0)), false);
assert_eq!(b1.contains_point(Vector3::new(-0.5, 0.5, 1.0)), false);
assert_eq!(b1.contains_point(Vector3::new(2.5, 0.5, 1.0)), false);
assert_eq!(b1.contains_point(Vector3::new(0.5, 2.5, 1.0)), false);
}
}

View File

@ -17,15 +17,27 @@ pub struct Frustum {
}
impl Frustum {
/// Creates a frustum from the matrix of a camera.
///
/// This is *ahem...* slightly inspired from THREE.js Frustum
/// Creates a frustum from its four planes.
pub fn new(planes: [Plane; 6]) -> Frustum {
Frustum {
planes: planes,
}
}
/// Creates a frustum for a camera matrix.
pub fn from_matrix(m: &Matrix4<f32>) -> Frustum {
let m0 = m[(0, 0)]; let m1 = m[(0, 1)]; let m2 = m[(0, 2)]; let m3 = m[(0, 3)];
let m4 = m[(1, 0)]; let m5 = m[(1, 1)]; let m6 = m[(1, 2)]; let m7 = m[(1, 3)];
let m8 = m[(2, 0)]; let m9 = m[(2, 1)]; let m10 = m[(2, 2)]; let m11 = m[(2, 3)];
let m12 = m[(3, 0)]; let m13 = m[(3, 1)]; let m14 = m[(3, 2)]; let m15 = m[(3, 3)];
// let m0 = m[(0, 0)]; let m1 = m[(0, 1)]; let m2 = m[(0, 2)]; let m3 = m[(0, 3)];
// let m4 = m[(1, 0)]; let m5 = m[(1, 1)]; let m6 = m[(1, 2)]; let m7 = m[(1, 3)];
// let m8 = m[(2, 0)]; let m9 = m[(2, 1)]; let m10 = m[(2, 2)]; let m11 = m[(2, 3)];
// let m12 = m[(3, 0)]; let m13 = m[(3, 1)]; let m14 = m[(3, 2)]; let m15 = m[(3, 3)];
// Swapped version...
let m0 = m[(0, 0)]; let m1 = m[(1, 0)]; let m2 = m[(2, 0)]; let m3 = m[(3, 0)];
let m4 = m[(0, 1)]; let m5 = m[(1, 1)]; let m6 = m[(2, 1)]; let m7 = m[(3, 1)];
let m8 = m[(0, 2)]; let m9 = m[(1, 2)]; let m10 = m[(2, 2)]; let m11 = m[(3, 2)];
let m12 = m[(0, 3)]; let m13 = m[(1, 3)]; let m14 = m[(2, 3)]; let m15 = m[(3, 3)];
Frustum {
planes: [
@ -44,22 +56,15 @@ impl Frustum {
use num::Zero;
let mut p1 = Vector3::<f32>::zero();
let mut p2 = Vector3::<f32>::zero();
let mut p = Vector3::<f32>::zero();
for plane in &self.planes {
p1[0] = if plane.normal().x() > 0.0 { bbox.min().x() } else { bbox.max().x() };
p2[0] = if plane.normal().x() > 0.0 { bbox.max().x() } else { bbox.min().x() };
p1[1] = if plane.normal().y() > 0.0 { bbox.min().y() } else { bbox.max().y() };
p2[1] = if plane.normal().y() > 0.0 { bbox.max().y() } else { bbox.min().y() };
p1[2] = if plane.normal().z() > 0.0 { bbox.min().z() } else { bbox.max().z() };
p2[2] = if plane.normal().z() > 0.0 { bbox.max().z() } else { bbox.min().z() };
p[0] = if plane.normal().x() > 0.0 { bbox.max().x() } else { bbox.min().x() };
p[1] = if plane.normal().y() > 0.0 { bbox.max().y() } else { bbox.min().y() };
p[2] = if plane.normal().z() > 0.0 { bbox.max().z() } else { bbox.min().z() };
let d1 = plane.distance_to_point(p1);
let d2 = plane.distance_to_point(p2);
if d1 < 0.0 && d2 < 2.0 {
if plane.distance_to_point(p) < 0.0 {
return false;
}
}

View File

@ -39,6 +39,14 @@ macro_rules! make_vector {
}
}
impl<T> From<[T; $number]> for $name<T> {
fn from(data: [T; $number]) -> $name<T> {
$name {
data: data,
}
}
}
impl<T: Copy + Clone> Into<($( $t ) ,* )> for $name<T> {
fn into(self) -> ($( $t ) ,* ) {
( $( self.data[$y] ), *)

View File

@ -3,6 +3,7 @@ extern crate glium;
#[macro_use]
extern crate verbose_log;
extern crate model_converter;
extern crate nalgebra as na;
use std::process::exit;
use std::time::{Instant, Duration};
@ -97,7 +98,7 @@ fn main() {
for (name, mut model) in models {
log!("Scaling model {}...", name);
model.center_and_scale_from_box(&bbox);
// model.center_and_scale_from_box(&bbox);
log!("\nBuilding textures for model {}...", name);
@ -119,19 +120,21 @@ fn main() {
let mut closed = false;
let mut camera = Camera::new(
Vector3::new( 0.0, 0.0, 0.0),
Vector3::new(1.0, 0.0, 0.0),
Vector3::new(0.0, 0.0, 0.0),
Vector3::new(0.0, 1.0, 0.0),
);
camera.z_near = 0.0001;
use model_converter::camera::RenderCamera;
let mut controls: Box<Controls> = if matches.is_present("first person") {
Box::new(FirstPersonControls::new())
} else {
Box::new(OrbitControls::new(
Vector3::new(0.0, 0.0, 0.0),
1.0,
2.0,
&mut camera
))
};
@ -175,11 +178,11 @@ fn main() {
} => {
// Go back in world coordinates
let position = camera.position * size as f32;
let position = position + center;
let position = camera.position;
// let position = position + center;
let target = camera.target * size as f32;
let target = target + center;
let target = camera.target;
// let target = target + center;
let up = camera.up;
@ -191,12 +194,15 @@ fn main() {
target.x(), target.y(), target.z());
println!("\tUp: ({}, {}, {})",
up.x(), up.y(), up.z());
}
_ => (),
}
});
controls.update(&mut camera, &renderer);
renderer.render(&scene, &camera);
let elapsed = as_millis(Instant::now().duration_since(before));

View File

@ -124,8 +124,8 @@ impl Renderer {
let mut target = self.draw();
target.clear_color_srgb_and_depth(self.clear_color, 1.0);
let perspective = camera.get_perspective_matrix();
let view = camera.get_view_matrix();
let perspective = camera.perspective();
let view = camera.view();
let params = DrawParameters {
depth: Depth {