bevy/src/render/camera.rs

89 lines
2.1 KiB
Rust
Raw Normal View History

2019-12-04 08:11:14 +00:00
use crate::math::Mat4;
2019-12-02 04:03:04 +00:00
2020-01-09 03:17:11 +00:00
pub struct ActiveCamera;
pub struct ActiveCamera2d;
pub enum CameraType {
Projection {
fov: f32,
aspect_ratio: f32,
near: f32,
2020-01-11 10:11:27 +00:00
far: f32,
2020-01-09 03:17:11 +00:00
},
Orthographic {
left: f32,
right: f32,
bottom: f32,
top: f32,
near: f32,
far: f32,
},
}
pub struct Camera {
2019-12-04 08:11:14 +00:00
pub view_matrix: Mat4,
pub camera_type: CameraType,
}
2019-12-02 04:03:04 +00:00
impl Camera {
pub fn new(camera_type: CameraType) -> Self {
Camera {
2019-12-04 08:11:14 +00:00
view_matrix: Mat4::identity(),
camera_type,
}
}
pub fn update(&mut self, width: u32, height: u32) {
match &mut self.camera_type {
2020-01-11 10:11:27 +00:00
CameraType::Projection {
aspect_ratio,
fov,
near,
far,
} => {
2019-12-02 23:51:24 +00:00
*aspect_ratio = width as f32 / height as f32;
2020-01-11 10:11:27 +00:00
self.view_matrix =
get_perspective_projection_matrix(*fov, *aspect_ratio, *near, *far)
}
CameraType::Orthographic {
left,
right,
bottom,
top,
near,
far,
} => {
2020-01-09 03:17:11 +00:00
*right = width as f32;
*top = height as f32;
2020-01-11 10:11:27 +00:00
self.view_matrix =
get_orthographic_projection_matrix(*left, *right, *bottom, *top, *near, *far)
}
}
}
}
2020-01-09 03:17:11 +00:00
pub fn get_perspective_projection_matrix(fov: f32, aspect_ratio: f32, near: f32, far: f32) -> Mat4 {
2019-12-04 08:11:14 +00:00
let projection = Mat4::perspective_rh_gl(fov, aspect_ratio, near, far);
2019-12-02 04:03:04 +00:00
opengl_to_wgpu_matrix() * projection
2019-12-02 04:03:04 +00:00
}
2020-01-11 10:11:27 +00:00
pub fn get_orthographic_projection_matrix(
left: f32,
right: f32,
bottom: f32,
top: f32,
near: f32,
far: f32,
) -> Mat4 {
2020-01-09 03:17:11 +00:00
let projection = Mat4::orthographic_rh_gl(left, right, bottom, top, near, far);
opengl_to_wgpu_matrix() * projection
}
2019-12-04 08:11:14 +00:00
pub fn opengl_to_wgpu_matrix() -> Mat4 {
Mat4::from_cols_array(&[
2020-01-11 10:11:27 +00:00
1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.5, 1.0,
2019-12-04 08:11:14 +00:00
])
2020-01-11 10:11:27 +00:00
}