ferravex_graphics/
camera.rs

1use 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    /// Cache projection and picking using this camera's actual clip-depth convention.
35    ///
36    /// Coordinates share the viewport's units (normally logical pixels). Rays
37    /// start at the near plane; callers declare finite/infinite far intent because
38    /// it cannot reliably be recovered from the composed matrix. Infinite far is
39    /// currently rejected. Camera position and rendering remain unchanged.
40    ///
41    /// ```
42    /// use ferravex_graphics::{Camera, Vec3, vec2, vec3};
43    /// use ferravex_math::projection::{FarPlane, ScreenYAxis, Viewport};
44    /// let camera = Camera::perspective(
45    ///     vec3(0., 0., 5.), Vec3::ZERO, Vec3::Y, 1., 2., 0.5, 50.,
46    /// );
47    /// let projector = camera.prepare_projector(
48    ///     Viewport { origin: vec2(20., 80.), size: vec2(800., 400.) },
49    ///     ScreenYAxis::Down, FarPlane::Finite,
50    /// )?;
51    /// let anchor = projector.project(Vec3::ZERO)?;
52    /// assert!(anchor.screen.abs_diff_eq(vec2(420., 280.), 0.001));
53    /// let ray = projector.pick_ray(anchor.screen)?;
54    /// assert!(ray.origin.abs_diff_eq(vec3(0., 0., 4.5), 0.001));
55    /// assert!(ray.direction.abs_diff_eq(Vec3::NEG_Z, 0.001));
56    /// # Ok::<(), ferravex_math::projection::ProjectionError>(())
57    /// ```
58    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    /// Exact transformed-box support test; conservative under nonuniform scale and shear.
112    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}