use crate::math::{Matrix4, DEG2RAD};
use super::PerspectiveCamera;
#[derive(Clone, Copy, Debug, PartialEq)]
struct Cache {
focus: f64,
fov: f64,
aspect: f64,
near: f64,
far: f64,
zoom: f64,
eye_sep: f64,
}
pub struct StereoCamera {
pub aspect: f64,
pub eye_sep: f64,
pub camera_l: PerspectiveCamera,
pub camera_r: PerspectiveCamera,
cache: Option<Cache>,
}
impl Default for StereoCamera {
fn default() -> Self {
Self::new()
}
}
impl StereoCamera {
pub const TYPE: &'static str = "StereoCamera";
pub fn new() -> Self {
let eye = |layer: u32| {
let camera = PerspectiveCamera::new(50.0, 1.0, 0.1, 2000.0);
{
let mut object = camera.node.borrow_mut();
object.layers.enable(layer);
object.matrix_auto_update = false;
}
camera
};
Self {
aspect: 1.0,
eye_sep: 0.064,
camera_l: eye(1),
camera_r: eye(2),
cache: None,
}
}
pub fn update(&mut self, camera: &PerspectiveCamera) {
let current = Cache {
focus: camera.focus,
fov: camera.fov,
aspect: camera.aspect * self.aspect,
near: camera.near,
far: camera.far,
zoom: camera.zoom,
eye_sep: self.eye_sep,
};
let needs_update = match self.cache {
None => true,
Some(cache) => {
cache.focus != current.focus
|| cache.fov != current.fov
|| cache.aspect != current.aspect
|| cache.near != current.near
|| cache.far != current.far
|| cache.zoom != current.zoom
|| cache.eye_sep != current.eye_sep
}
};
if needs_update {
self.cache = Some(current);
let cache = current;
let mut projection_matrix = camera.projection_matrix;
let eye_sep_half = cache.eye_sep / 2.0;
let eye_sep_on_projection = eye_sep_half * cache.near / cache.focus;
let ymax = (cache.near * (DEG2RAD * cache.fov * 0.5).tan()) / cache.zoom;
let xmin = -ymax * cache.aspect + eye_sep_on_projection;
let xmax = ymax * cache.aspect + eye_sep_on_projection;
projection_matrix.elements[0] = 2.0 * cache.near / (xmax - xmin);
projection_matrix.elements[8] = (xmax + xmin) / (xmax - xmin);
self.camera_l.projection_matrix = projection_matrix;
let xmin = -ymax * cache.aspect - eye_sep_on_projection;
let xmax = ymax * cache.aspect - eye_sep_on_projection;
projection_matrix.elements[0] = 2.0 * cache.near / (xmax - xmin);
projection_matrix.elements[8] = (xmax + xmin) / (xmax - xmin);
self.camera_r.projection_matrix = projection_matrix;
}
let eye_sep_half = self.cache.map_or(0.0, |cache| cache.eye_sep) / 2.0;
let mut eye_left = Matrix4::identity();
eye_left.elements[12] = -eye_sep_half;
let mut eye_right = Matrix4::identity();
eye_right.elements[12] = eye_sep_half;
let matrix_world = camera.node.borrow().matrix_world;
for (eye, offset) in [(&self.camera_l, &eye_left), (&self.camera_r, &eye_right)] {
let mut object = eye.node.borrow_mut();
object.matrix = matrix_world;
object.matrix.multiply(offset);
object.matrix_world_needs_update = true;
}
}
}