use glam::Vec3;
use indicatrix::optics::raytracer::{Camera, Ray};
const NEAR_EPS: f32 = 1e-4;
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct ScreenPoint {
pub x: f32,
pub y: f32,
}
impl ScreenPoint {
#[must_use]
pub const fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
#[must_use]
pub const fn delta_to(self, other: Self) -> (f32, f32) {
(other.x - self.x, other.y - self.y)
}
#[must_use]
pub fn distance(self, other: Self) -> f32 {
let (dx, dy) = self.delta_to(other);
dx.hypot(dy)
}
#[must_use]
pub fn midpoint(self, other: Self) -> Self {
Self::new(
0.5_f32.mul_add(other.x - self.x, self.x),
0.5_f32.mul_add(other.y - self.y, self.y),
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct ScreenSize {
pub width: f32,
pub height: f32,
}
impl ScreenSize {
#[must_use]
pub const fn new(width: f32, height: f32) -> Self {
Self { width, height }
}
#[must_use]
pub const fn is_valid(self) -> bool {
self.width > 0.0 && self.height > 0.0
}
}
#[must_use]
pub fn project(camera: &Camera, p: Vec3, size: ScreenSize) -> Option<ScreenPoint> {
if !size.is_valid() {
return None;
}
let delta = p - camera.origin;
let depth = delta.dot(camera.forward);
if depth <= NEAR_EPS {
return None;
}
let right_comp = delta.dot(camera.right);
let up_comp = delta.dot(camera.up);
let u_ratio = right_comp / depth;
let v_ratio = up_comp / depth;
let aspect = size.width / size.height;
Some(ScreenPoint::new(
size.width * (0.5 + u_ratio / (2.0 * aspect * camera.fov_tan)),
size.height * (0.5 - v_ratio / (2.0 * camera.fov_tan)),
))
}
#[must_use]
pub fn unproject(camera: &Camera, p: ScreenPoint, size: ScreenSize) -> Ray {
camera.generate_ray(p.x, p.y, size.width, size.height, 0.0, 0.0)
}