use core::cmp::Ordering;
use serde::{Deserialize, Serialize};
use super::{Face, Node3, Strut, Vertex3};
pub const NEAR_EPS: f64 = 1e-6;
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Camera {
pub ry: f64,
pub rx: f64,
pub dist: f64,
pub fov: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Projected {
pub sx: f64,
pub sy: f64,
pub depth: f64,
pub scale: f64,
}
fn to_camera_space(v: &Vertex3, cam: &Camera) -> Vertex3 {
let (sy, cy) = cam.ry.sin_cos();
let x1 = v.x * cy + v.z * sy;
let y1 = v.y;
let z1 = -v.x * sy + v.z * cy;
let (sx, cx) = cam.rx.sin_cos();
let x2 = x1;
let y2 = y1 * cx - z1 * sx;
let z2 = y1 * sx + z1 * cx;
Vertex3 {
x: x2,
y: y2,
z: cam.dist - z2,
}
}
pub fn project(v: &Vertex3, cam: &Camera, cols: u16, rows: u16) -> Projected {
project_wh(v, cam, cols as f64 * 2.0, rows as f64 * 4.0)
}
pub(crate) fn project_wh(v: &Vertex3, cam: &Camera, width: f64, height: f64) -> Projected {
let cs = to_camera_space(v, cam);
let z = if cs.z <= NEAR_EPS { NEAR_EPS } else { cs.z };
let f = 1.0 / (cam.fov * core::f64::consts::PI / 360.0).tan();
let aspect = height / width;
let ndc_x = f * cs.x / z * aspect;
let ndc_y = f * cs.y / z;
let sx = (ndc_x + 1.0) / 2.0 * (width - 1.0);
let sy = (1.0 - ndc_y) / 2.0 * (height - 1.0);
Projected {
sx,
sy,
depth: cs.z,
scale: f / z * (height - 1.0) / 2.0,
}
}
fn is_clipped(v: &Vertex3, cam: &Camera) -> bool {
to_camera_space(v, cam).z <= NEAR_EPS
}
pub fn face_is_clipped(face: &Face, cam: &Camera) -> bool {
face.verts.iter().any(|v| is_clipped(v, cam))
}
pub fn strut_is_clipped(strut: &Strut, cam: &Camera) -> bool {
is_clipped(&strut.a, cam) || is_clipped(&strut.b, cam)
}
pub fn node_is_clipped(node: &Node3, cam: &Camera) -> bool {
is_clipped(&node.pos, cam)
}
fn nan_safe_cmp(a: f64, b: f64) -> Ordering {
a.partial_cmp(&b).unwrap_or(Ordering::Equal)
}
pub fn depth_sort(faces: &mut [Face], struts: &mut [Strut], cam: &Camera) {
faces.sort_by(|a, b| {
let da = face_centroid_depth(a, cam);
let db = face_centroid_depth(b, cam);
nan_safe_cmp(db, da)
});
struts.sort_by(|a, b| {
let da = strut_centroid_depth(a, cam);
let db = strut_centroid_depth(b, cam);
nan_safe_cmp(db, da)
});
}
pub fn depth_sort_nodes(nodes: &mut [Node3], cam: &Camera) {
nodes.sort_by(|a, b| {
let da = to_camera_space(&a.pos, cam).z;
let db = to_camera_space(&b.pos, cam).z;
nan_safe_cmp(db, da)
});
}
fn face_centroid_depth(face: &Face, cam: &Camera) -> f64 {
let cx = (face.verts[0].x + face.verts[1].x + face.verts[2].x) / 3.0;
let cy = (face.verts[0].y + face.verts[1].y + face.verts[2].y) / 3.0;
let cz = (face.verts[0].z + face.verts[1].z + face.verts[2].z) / 3.0;
to_camera_space(
&Vertex3 {
x: cx,
y: cy,
z: cz,
},
cam,
)
.z
}
fn strut_centroid_depth(strut: &Strut, cam: &Camera) -> f64 {
let cx = (strut.a.x + strut.b.x) / 2.0;
let cy = (strut.a.y + strut.b.y) / 2.0;
let cz = (strut.a.z + strut.b.z) / 2.0;
to_camera_space(
&Vertex3 {
x: cx,
y: cy,
z: cz,
},
cam,
)
.z
}