Skip to main content

peridot_math/
gaming.rs

1//! Peridot Extended Mathematics: Gaming Utils(Camera, ModelMatrix)
2
3use crate::{linarg::*, Ray3};
4use crate::{One, Zero};
5use std::ops::Range;
6
7/// How the camera will project vertices?
8#[derive(Debug, Clone)]
9pub enum ProjectionMethod {
10    /// The orthographic projection
11    Orthographic { size: f32 },
12    /// The perspective projection. requires fov(unit: radians)
13    Perspective { fov: f32 },
14    /// The perspective projection but computed from physically-based units(millimeters).
15    Physical {
16        focal_length: f32,
17        sensor_size: crate::Vector2F32,
18        screen_fitting: PhysicalScreenFitting,
19        lens_shift: crate::Vector2F32,
20    },
21    /// UI layouting optimized projection: (0, 0)-(design_width, design_height) will be mapped to (-1, -1)-(1, 1)
22    /// This projection ignores aspect ratio.
23    UI {
24        design_width: f32,
25        design_height: f32,
26    },
27}
28
29#[derive(Debug, Clone, Copy)]
30pub enum PhysicalScreenFitting {
31    // 縦のみ合わせる
32    Vertical,
33    // 横のみ合わせる
34    Horizontal,
35    // 画面からはみ出さないように調整
36    Shrink,
37    // 画面をすべて覆うように調整
38    Enlarge,
39}
40
41/// A camera
42/// ## Examples
43///
44/// ```
45/// # use peridot_math::*;
46/// let c = Camera {
47///     projection: Some(ProjectionMethod::Orthographic { size: 5.0 }),
48///     position: Vector3::ZERO, rotation: Quaternion::ONE,
49///     depth_range: 1.0 .. 9.0
50/// };
51/// let (mv, mp) = c.matrixes(1.0);
52/// assert_eq!(mv.clone() * Vector3(5.0, 0.0, 1.0), Vector4(5.0, 0.0, 1.0, 1.0));
53/// assert_eq!(mp * mv * Vector3(5.0, 0.0, 1.0), Vector4(1.0, 0.0, 0.0, 1.0));
54/// ```
55#[derive(Clone)]
56pub struct Camera {
57    /// Projection method of the camera. `None` indicates no projection(only adjust aspect ratio)
58    pub projection: Option<ProjectionMethod>,
59    /// Eye position of the camera.
60    pub position: Vector3F32,
61    /// Eye direction of the camera.
62    pub rotation: QuaternionF32,
63    /// Z range to be rendered.
64    pub depth_range: Range<f32>,
65}
66
67impl Camera {
68    /// calculates the camera projection matrix
69    pub fn projection_matrix(&self, aspect_wh: f32) -> Matrix4F32 {
70        match self.projection {
71            Some(ProjectionMethod::Perspective { fov }) => {
72                let scaling_tan = (fov / 2.0).tan();
73                let zdiff = self.depth_range.end - self.depth_range.start;
74                let zscale = (
75                    self.depth_range.end / zdiff,
76                    -(self.depth_range.end * self.depth_range.start) / zdiff,
77                );
78
79                Matrix4(
80                    [(aspect_wh * scaling_tan).recip(), 0.0, 0.0, 0.0],
81                    [0.0, -scaling_tan.recip(), 0.0, 0.0],
82                    [0.0, 0.0, zscale.0, zscale.1],
83                    [0.0, 0.0, 1.0, 0.0],
84                )
85            }
86            Some(ProjectionMethod::Orthographic { size }) => {
87                let zdiff = self.depth_range.end - self.depth_range.start;
88                let t = Matrix4::translation(Vector3(0.0, 0.0, -self.depth_range.start));
89                let s = Matrix4::scale(Vector4(
90                    (aspect_wh * size).recip(),
91                    -size.recip(),
92                    zdiff.recip(),
93                    1.0,
94                ));
95
96                s * t
97            }
98            Some(ProjectionMethod::Physical {
99                focal_length,
100                sensor_size,
101                screen_fitting,
102                lens_shift,
103            }) => {
104                let focal_length_meters = focal_length / 1000.0;
105                let sensor_width_meters = sensor_size.0 / 1000.0;
106                let sensor_height_meters = sensor_size.1 / 1000.0;
107                let zd = self.depth_range.end - self.depth_range.start;
108
109                let (scaling_x, scaling_y);
110                match screen_fitting {
111                    PhysicalScreenFitting::Vertical => {
112                        // let scaling_tan = sensor_height_meters / focal_length_meters;
113
114                        // scaling_x = (aspect_wh * scaling_tan).recip();
115                        scaling_x = focal_length_meters / (aspect_wh * sensor_height_meters);
116                        // scaling_y = scaling_tan.recip();
117                        scaling_y = focal_length_meters / sensor_height_meters;
118                    }
119                    PhysicalScreenFitting::Horizontal => {
120                        // let scaling_tan = sensor_width_meters / focal_length_meters;
121
122                        // scaling_x = scaling_tan.recip();
123                        scaling_x = focal_length_meters / sensor_width_meters;
124                        // scaling_y = (scaling_tan / aspect_wh).recip();
125                        scaling_y = (focal_length_meters * aspect_wh) / sensor_width_meters;
126                    }
127                    PhysicalScreenFitting::Shrink => {
128                        if sensor_size.aspect_wh() < aspect_wh {
129                            // let scaling_tan = sensor_height_meters / focal_length_meters;
130
131                            // scaling_x = (aspect_wh * scaling_tan).recip();
132                            scaling_x = focal_length_meters / (aspect_wh * sensor_height_meters);
133                            // scaling_y = scaling_tan.recip();
134                            scaling_y = focal_length_meters / sensor_height_meters;
135                        } else {
136                            // let scaling_tan = sensor_width_meters / focal_length_meters;
137
138                            // scaling_x = scaling_tan.recip();
139                            scaling_x = focal_length_meters / sensor_width_meters;
140                            // scaling_y = (scaling_tan / aspect_wh).recip();
141                            scaling_y = (focal_length_meters * aspect_wh) / sensor_width_meters;
142                        }
143                    }
144                    PhysicalScreenFitting::Enlarge => {
145                        if sensor_size.aspect_wh() > aspect_wh {
146                            // let scaling_tan = sensor_height_meters / focal_length_meters;
147
148                            // scaling_x = (aspect_wh * scaling_tan).recip();
149                            scaling_x = focal_length_meters / (aspect_wh * sensor_height_meters);
150                            // scaling_y = scaling_tan.recip();
151                            scaling_y = focal_length_meters / sensor_height_meters;
152                        } else {
153                            // let scaling_tan = sensor_width_meters / focal_length_meters;
154
155                            // scaling_x = scaling_tan.recip();
156                            scaling_x = focal_length_meters / sensor_width_meters;
157                            // scaling_y = (scaling_tan / aspect_wh).recip();
158                            scaling_y = (focal_length_meters * aspect_wh) / sensor_width_meters;
159                        }
160                    }
161                }
162
163                // z = (z - znear) / (zfar - znear) = z / (zfar - znear) - znear / (zfar - znear)
164
165                let projection = Matrix4(
166                    [scaling_x, 0.0, 0.0, 0.0],
167                    [0.0, -scaling_y, 0.0, 0.0],
168                    [0.0, 0.0, zd.recip(), -self.depth_range.start / zd],
169                    [0.0, 0.0, 1.0, 0.0],
170                );
171                let lens_shift = Matrix4::translation(lens_shift.with_z(0.0));
172
173                lens_shift * projection
174            }
175            Some(ProjectionMethod::UI {
176                design_width,
177                design_height,
178            }) => {
179                let zdiff = self.depth_range.end - self.depth_range.start;
180                let t = Matrix4::translation(Vector3(-1.0, -1.0, 0.0));
181                let s = Matrix4::scale(Vector4(
182                    2.0 / design_width,
183                    2.0 / design_height,
184                    zdiff.recip(),
185                    1.0,
186                ));
187
188                t * s
189            }
190            None => Matrix4::scale(Vector4(aspect_wh.recip(), 1.0, 1.0, 1.0)),
191        }
192    }
193    /// calculates the camera view matrix
194    pub fn view_matrix(&self) -> Matrix4F32 {
195        Matrix4F32::from(-self.rotation) * Matrix4F32::translation(-self.position)
196    }
197    /// calculates the camera transform(view and projection) matrix
198    pub fn view_projection_matrix(&self, aspect_wh: f32) -> Matrix4F32 {
199        let (v, p) = self.matrixes(aspect_wh);
200        p * v
201    }
202    /// calculates the camera view matrix and the projection matrix(returns in this order)
203    pub fn matrixes(&self, aspect_wh: f32) -> (Matrix4F32, Matrix4F32) {
204        (self.view_matrix(), self.projection_matrix(aspect_wh))
205    }
206
207    #[inline(always)]
208    /// Right direction of the camera
209    pub fn right(&self) -> Vector3F32 {
210        Matrix3::from(self.rotation) * Vector3F32::right()
211    }
212
213    #[inline(always)]
214    /// Up direction of the camera
215    pub fn up(&self) -> Vector3F32 {
216        Matrix3::from(self.rotation) * Vector3F32::up()
217    }
218
219    #[inline(always)]
220    /// Forward direction of the camera
221    pub fn forward(&self) -> Vector3F32 {
222        Matrix3::from(self.rotation) * Vector3F32::forward()
223    }
224
225    /// Sets rotation of the camera to look at a point
226    pub fn look_at(&mut self, target: Vector3F32, upvec: Option<Vector3F32>) {
227        self.rotation = match upvec {
228            None => {
229                // upfree rotation
230                let eyedir = (target - self.position).normalize();
231                let basedir = Vector3(0.0f32, 0.0, 1.0);
232
233                let axis = basedir.cross(&eyedir);
234                if axis.len2() == 0.0 {
235                    // same direction as basedir
236                    self.rotation = Quaternion::<f32>::ONE;
237                    return;
238                }
239                let angle = basedir.dot(eyedir).acos();
240                Quaternion::<f32>::new(-angle, axis.normalize())
241            }
242            Some(up) => {
243                // upfixed rotation(traditional)
244                let forward = (target - self.position).normalize();
245                let right = up.cross(&forward);
246                let up = forward.cross(&right);
247                let m = Matrix3(
248                    [right.0, right.1, right.2],
249                    [up.0, up.1, up.2],
250                    [forward.0, forward.1, forward.2],
251                );
252
253                // mat -> quat: https://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/
254                let trace = m.0[0] + m.1[1] + m.2[2];
255                if trace > 0.0 {
256                    let s = (trace + 1.0).sqrt() * 2.0;
257                    Quaternion(
258                        (m.2[1] - m.1[2]) / s,
259                        (m.0[2] - m.2[0]) / s,
260                        (m.1[0] - m.0[1]) / s,
261                        0.25 * s,
262                    )
263                } else if m.0[0] > m.1[1] && m.0[0] > m.2[2] {
264                    let s = (1.0f32 + m.0[0] - m.1[1] - m.2[2]).sqrt() * 2.0;
265                    Quaternion(
266                        0.25 * s,
267                        (m.0[1] + m.1[0]) / s,
268                        (m.0[2] + m.2[0]) / s,
269                        (m.2[1] - m.1[2]) / s,
270                    )
271                } else if m.1[1] > m.2[2] {
272                    let s = (1.0f32 + m.1[1] - m.0[0] - m.2[2]).sqrt() * 2.0;
273                    Quaternion(
274                        (m.0[1] + m.1[0]) / s,
275                        0.25 * s,
276                        (m.1[2] + m.2[1]) / s,
277                        (m.0[2] - m.2[0]) / s,
278                    )
279                } else {
280                    let s = (1.0f32 + m.2[2] - m.0[0] - m.1[1]).sqrt() * 2.0;
281                    Quaternion(
282                        (m.0[2] + m.2[0]) / s,
283                        (m.1[2] + m.2[1]) / s,
284                        0.25 * s,
285                        (m.1[0] - m.0[1]) / s,
286                    )
287                }
288            }
289        };
290    }
291
292    /// Converts a viewport point to a world point.
293    ///
294    /// `viewport_point` is in normalized viewport coordinates(`(0, 0)` for left-top of the viewport, `(1, 1)` for right-bottom)
295    pub fn viewport_point_to_world_point(
296        &self,
297        viewport_point: Vector2<f32>,
298        viewport_aspect_wh: f32,
299    ) -> Vector3<f32> {
300        let pos_clip = Vector3(
301            2.0 * viewport_point.0 - 1.0,
302            2.0 * viewport_point.1 - 1.0,
303            0.0,
304        );
305
306        let vp_inv = self
307            .view_projection_matrix(viewport_aspect_wh)
308            .inverse()
309            .expect("cannot inverse?");
310        Vector3::from(vp_inv.clone() * pos_clip)
311    }
312
313    /// Converts a viewport point to a world ray.
314    ///
315    /// `viewport_point` is in normalized viewport coordinates(`(0, 0)` for left-top of the viewport, `(1, 1)` for right-bottom)
316    pub fn viewport_point_to_world_ray(
317        &self,
318        viewport_point: Vector2<f32>,
319        viewport_aspect_wh: f32,
320    ) -> Ray3<f32> {
321        let pos_clip_near = Vector3(
322            2.0 * viewport_point.0 - 1.0,
323            2.0 * viewport_point.1 - 1.0,
324            1.0,
325        );
326        let pos_clip_far = Vector3(
327            2.0 * viewport_point.0 - 1.0,
328            2.0 * viewport_point.1 - 1.0,
329            -1.0,
330        );
331
332        let vp_inv = self
333            .view_projection_matrix(viewport_aspect_wh)
334            .inverse()
335            .expect("cannot inverse?");
336        let pos_world_near = Vector3::from(vp_inv.clone() * pos_clip_near);
337        let pos_world_far = Vector3::from(vp_inv * pos_clip_far);
338
339        Ray3::from_origin_to(pos_world_near, pos_world_far)
340    }
341}
342impl Default for Camera {
343    /// Default value of the Camera, that has identity view transform and Perspective projection with fov=60deg.
344    fn default() -> Self {
345        Camera {
346            projection: Some(ProjectionMethod::Perspective {
347                fov: 60.0f32.to_radians(),
348            }),
349            position: Vector3::ZERO,
350            rotation: Quaternion::ONE,
351            depth_range: 0.0..1.0,
352        }
353    }
354}