ferravex_graphics/
camera.rs1use crate::{Bounds, Mat4, Vec3, Vec4};
2#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3pub enum ClipDepth {
4 NegativeOneToOne,
5 ZeroToOne,
6}
7#[derive(Clone, Copy, Debug)]
8pub struct Camera {
9 pub view_projection: Mat4,
10 pub position: Vec3,
11 pub clip_depth: ClipDepth,
12}
13impl Camera {
14 pub fn perspective(
15 eye: Vec3,
16 target: Vec3,
17 up: Vec3,
18 fov_y: f32,
19 aspect: f32,
20 near: f32,
21 far: f32,
22 ) -> Self {
23 Self {
24 view_projection: Mat4::perspective_rh(fov_y, aspect, near, far)
25 * Mat4::look_at_rh(eye, target, up),
26 position: eye,
27 clip_depth: ClipDepth::ZeroToOne,
28 }
29 }
30 pub fn frustum(self) -> Option<Frustum> {
31 Frustum::from_matrix(self.view_projection, self.clip_depth)
32 }
33
34 pub fn prepare_projector(
59 self,
60 viewport: ferravex_math::projection::Viewport,
61 y_axis: ferravex_math::projection::ScreenYAxis,
62 far_plane: ferravex_math::projection::FarPlane,
63 ) -> Result<
64 ferravex_math::projection::PreparedProjector3D,
65 ferravex_math::projection::ProjectionError,
66 > {
67 use ferravex_math::projection::{NdcDepth, PreparedProjector3D};
68 let depth = match self.clip_depth {
69 ClipDepth::NegativeOneToOne => NdcDepth::NegativeOneToOne,
70 ClipDepth::ZeroToOne => NdcDepth::ZeroToOne,
71 };
72 PreparedProjector3D::try_new(self.view_projection, viewport, y_axis, depth, far_plane)
73 }
74}
75#[derive(Clone, Copy, Debug)]
76pub struct Frustum {
77 planes: [Vec4; 6],
78}
79impl Frustum {
80 pub fn from_matrix(matrix: Mat4, depth: ClipDepth) -> Option<Self> {
81 if !matrix.is_finite() {
82 return None;
83 }
84 let r0 = matrix.row(0);
85 let r1 = matrix.row(1);
86 let r2 = matrix.row(2);
87 let r3 = matrix.row(3);
88 let mut planes = [
89 r3 + r0,
90 r3 - r0,
91 r3 + r1,
92 r3 - r1,
93 if depth == ClipDepth::ZeroToOne {
94 r2
95 } else {
96 r3 + r2
97 },
98 r3 - r2,
99 ];
100 for plane in &mut planes {
101 let length = plane.truncate().length();
102 if !length.is_finite() {
103 return None;
104 }
105 if length > 0.0 {
106 *plane /= length;
107 }
108 }
109 Some(Self { planes })
110 }
111 pub fn intersects_bounds(self, bounds: Bounds, transform: Mat4) -> bool {
113 let center = transform.transform_point3(bounds.center());
114 let half = bounds.half_extents();
115 self.planes.into_iter().all(|plane| {
116 let normal = plane.truncate();
117 let radius = normal.dot(transform.x_axis.truncate()).abs() * half.x
118 + normal.dot(transform.y_axis.truncate()).abs() * half.y
119 + normal.dot(transform.z_axis.truncate()).abs() * half.z;
120 normal.dot(center) + plane.w + radius >= 0.0
121 })
122 }
123 pub fn contains_point(self, point: Vec3) -> bool {
124 self.planes
125 .into_iter()
126 .all(|plane| plane.truncate().dot(point) + plane.w >= 0.0)
127 }
128}