retrofire_core/render/
cam.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
//! Cameras and camera transforms.

use core::ops::Range;

use crate::geom::{Tri, Vertex};
use crate::math::{
    angle::{spherical, turns, SphericalVec},
    mat::{orthographic, perspective, viewport, Mat4x4, RealToReal},
    space::Linear,
    vary::Vary,
    vec::{vec2, Vec3},
};
use crate::util::{rect::Rect, Dims};

#[cfg(feature = "fp")]
use crate::math::{
    angle::Angle,
    mat::{orient_z, translate},
    vec::vec3,
};

use super::{
    clip::ClipVec,
    ctx::Context,
    shader::{FragmentShader, VertexShader},
    target::Target,
    NdcToScreen, RealToProj, ViewToProj, World, WorldToView,
};

/// Camera movement mode.
///
/// TODO Rename to something more specific (e.g. `Motion`?)
pub trait Mode {
    /// Returns the current world-to-view matrix of this camera mode.
    fn world_to_view(&self) -> Mat4x4<WorldToView>;
}

/// Type to manage the world-to-viewport transformation.
#[derive(Copy, Clone, Debug, Default)]
pub struct Camera<M> {
    /// The movement mode of the camera.
    pub mode: M,
    /// Viewport width and height.
    pub dims: Dims,
    /// Projection matrix.
    pub project: Mat4x4<ViewToProj>,
    /// Viewport matrix.
    pub viewport: Mat4x4<NdcToScreen>,
}

/// First-person camera mode.
///
/// This is the familiar "FPS" movement mode, based on camera
/// position and heading (look-at vector).
#[derive(Copy, Clone, Debug)]
pub struct FirstPerson {
    /// Current position of the camera in world space.
    pub pos: Vec3,
    /// Current heading of the camera in world space.
    pub heading: SphericalVec,
}

//
// Inherent impls
//

impl Camera<()> {
    /// Creates a camera with the given resolution.
    pub fn new(dims: Dims) -> Self {
        Self {
            dims,
            viewport: viewport(vec2(0, 0)..vec2(dims.0, dims.1)),
            ..Default::default()
        }
    }

    pub fn mode<M: Mode>(self, mode: M) -> Camera<M> {
        let Self { dims, project, viewport, .. } = self;
        Camera { mode, dims, project, viewport }
    }
}

impl<M> Camera<M> {
    /// Sets the viewport bounds of this camera.
    pub fn viewport(self, bounds: impl Into<Rect<u32>>) -> Self {
        let (w, h) = self.dims;

        let Rect {
            left: Some(l),
            top: Some(t),
            right: Some(r),
            bottom: Some(b),
        } = bounds.into().intersect(&(0..w, 0..h).into())
        else {
            unreachable!("bounded ∩ bounded should be bounded")
        };

        Self {
            dims: (r.abs_diff(l), b.abs_diff(t)),
            viewport: viewport(vec2(l, t)..vec2(r, b)),
            ..self
        }
    }

    /// Sets up perspective projection.
    pub fn perspective(
        mut self,
        focal_ratio: f32,
        near_far: Range<f32>,
    ) -> Self {
        let aspect_ratio = self.dims.0 as f32 / self.dims.1 as f32;
        self.project = perspective(focal_ratio, aspect_ratio, near_far);
        self
    }

    /// Sets up orthographic projection.
    pub fn orthographic(mut self, bounds: Range<Vec3>) -> Self {
        self.project = orthographic(bounds.start, bounds.end);
        self
    }
}

impl<M: Mode> Camera<M> {
    /// Returns the composed camera and projection matrix.
    pub fn world_to_project(&self) -> Mat4x4<RealToProj<World>> {
        self.mode.world_to_view().then(&self.project)
    }

    /// Renders the given geometry from the viewpoint of this camera.
    pub fn render<B, Vtx: Clone, Var: Vary, Uni: Copy, Shd>(
        &self,
        tris: impl AsRef<[Tri<usize>]>,
        verts: impl AsRef<[Vtx]>,
        to_world: &Mat4x4<RealToReal<3, B, World>>,
        shader: &Shd,
        uniform: Uni,
        target: &mut impl Target,
        ctx: &Context,
    ) where
        Shd: for<'a> VertexShader<
                Vtx,
                (&'a Mat4x4<RealToProj<B>>, Uni),
                Output = Vertex<ClipVec, Var>,
            > + FragmentShader<Var>,
    {
        let tf = to_world.then(&self.world_to_project());

        super::render(
            tris.as_ref(),
            verts.as_ref(),
            shader,
            (&tf, uniform),
            self.viewport,
            target,
            ctx,
        );
    }
}

impl FirstPerson {
    /// Creates a first-person mode with position in the origin and heading
    /// in the direction of the positive x-axis.
    pub fn new() -> Self {
        Self {
            pos: Vec3::zero(),
            heading: spherical(1.0, turns(0.0), turns(0.0)),
        }
    }
}

#[cfg(feature = "fp")]
impl FirstPerson {
    pub fn look_at(&mut self, pt: Vec3) {
        self.heading = (pt - self.pos).into();
        self.heading[0] = 1.0;
    }

    pub fn rotate(&mut self, az: Angle, alt: Angle) {
        self.rotate_to(self.heading.az() + az, self.heading.alt() + alt);
    }

    pub fn rotate_to(&mut self, az: Angle, alt: Angle) {
        self.heading = spherical(
            1.0,
            az.wrap(turns(-0.5), turns(0.5)),
            alt.clamp(turns(-0.25), turns(0.25)),
        );
    }

    pub fn translate(&mut self, delta: Vec3) {
        // Zero azimuth means parallel to the x-axis
        let fwd = spherical(1.0, self.heading.az(), turns(0.0)).to_cart();
        let up = vec3(0.0, 1.0, 0.0);
        let right = up.cross(&fwd);

        // / rx ux fx \ / dx \     / rx ry rz \ T / dx \
        // | ry uy fy | | dy |  =  | ux uy uz |   | dy |
        // \ rz uz fz / \ dz /     \ fx fy fz /   \ dz /

        self.pos += Mat4x4::<RealToReal<3>>::from_basis(right, up, fwd)
            .transpose()
            .apply(&delta);
    }
}

//
// Local trait impls
//

#[cfg(feature = "fp")]
impl Mode for FirstPerson {
    fn world_to_view(&self) -> Mat4x4<WorldToView> {
        let &Self { pos, heading: dir, .. } = self;
        let fwd_move = spherical(1.0, dir.az(), turns(0.0));
        let fwd = self.heading;
        let right = vec3(0.0, 1.0, 0.0).cross(&fwd_move.to_cart());

        let transl = translate(-pos);
        let orient = orient_z(fwd.into(), right);

        transl.then(&orient).to()
    }
}

impl Mode for Mat4x4<WorldToView> {
    fn world_to_view(&self) -> Mat4x4<WorldToView> {
        *self
    }
}

//
// Foreign trait impls
//

#[cfg(feature = "fp")]
impl Default for FirstPerson {
    /// Returns [`FirstPerson::new`].
    fn default() -> Self {
        Self::new()
    }
}