Skip to main content

three_rs/cameras/
perspective_camera.rs

1//! Port of `three.js/src/cameras/PerspectiveCamera.js` + `Camera.js`
2//! (rung 1 subset).
3
4use crate::core::{Object3D, ObjectRef};
5use crate::math::math_utils::{js_max, js_min};
6use crate::math::{CoordinateSystem, Matrix4, Vector2, Vector3, Vector4, DEG2RAD, RAD2DEG};
7
8/// `Camera.view` — the frustum window specification set by
9/// [`PerspectiveCamera::set_view_offset`] and
10/// [`OrthographicCamera::set_view_offset`](super::OrthographicCamera::set_view_offset).
11#[derive(Clone, Copy, Debug, PartialEq)]
12pub struct CameraView {
13    /// Whether the offset is applied; [`clear_view_offset`](super::PerspectiveCamera::clear_view_offset) clears this and leaves the rest.
14    pub enabled: bool,
15    /// The full width of the multiview setup.
16    pub full_width: f64,
17    /// The full height of the multiview setup.
18    pub full_height: f64,
19    /// The horizontal offset of this sub-camera within the full frame.
20    pub offset_x: f64,
21    /// The vertical offset of this sub-camera within the full frame.
22    pub offset_y: f64,
23    /// The width of this sub-camera's window.
24    pub width: f64,
25    /// The height of this sub-camera's window.
26    pub height: f64,
27}
28
29/// three.js' `PerspectiveCamera`: a camera whose projection matches how the
30/// human eye and most cameras see, with distant objects appearing smaller.
31#[derive(Clone)]
32pub struct PerspectiveCamera {
33    /// The camera's own scene-graph node. `Camera` is an `Object3D` in three.js
34    /// and examples nest it (`scene.add( camera )`, `camera.add( light )`), so it
35    /// owns a [`ObjectRef`] rather than a bare `Object3D`.
36    pub node: ObjectRef,
37    /// The vertical field of view, from bottom to top of view, in degrees.
38    pub fov: f64,
39    /// The aspect ratio, usually the canvas width divided by its height.
40    pub aspect: f64,
41    /// The camera's near plane. Unlike [`OrthographicCamera`](super::OrthographicCamera)'s, `0.0` is not valid here.
42    pub near: f64,
43    /// The camera's far plane, greater than [`near`](Self::near).
44    pub far: f64,
45    /// The zoom factor of the camera.
46    pub zoom: f64,
47    /// Object distance used for stereoscopy and depth-of-field effects. Does not
48    /// influence the projection matrix.
49    pub focus: f64,
50    /// `Camera.view`, set by [`set_view_offset`](Self::set_view_offset).
51    pub view: Option<CameraView>,
52    /// Film size used for the larger axis, in millimetres. Only matters when
53    /// [`film_offset`](Self::film_offset) is nonzero.
54    pub film_gauge: f64,
55    /// Horizontal off-centre offset, in the same unit as [`film_gauge`](Self::film_gauge).
56    pub film_offset: f64,
57    /// The coordinate system [`update_projection_matrix`](Self::update_projection_matrix)
58    /// builds the projection for.
59    pub coordinate_system: CoordinateSystem,
60    /// `Camera.projectionMatrix`.
61    pub projection_matrix: Matrix4,
62    /// `Camera.projectionMatrixInverse`.
63    pub projection_matrix_inverse: Matrix4,
64    /// `Camera.matrixWorldInverse`.
65    pub matrix_world_inverse: Matrix4,
66    /// `camera.viewport` — not a `Camera` field in three.js until an
67    /// application sets one: an [`ArrayCamera`](super::ArrayCamera)'s
68    /// sub-camera's rectangle in CSS pixels, top-left origin, which the
69    /// backend turns into the draw's `setViewport()`.
70    pub viewport: Option<Vector4>,
71}
72
73impl PerspectiveCamera {
74    /// `new PerspectiveCamera( fov, aspect, near, far )`.
75    pub fn new(fov: f64, aspect: f64, near: f64, far: f64) -> Self {
76        // `Camera.isCamera` — `Object3D.lookAt()` branches on it.
77        let object = Object3D {
78            object_type: "PerspectiveCamera",
79            is_camera: true,
80            ..Default::default()
81        };
82
83        let mut camera = Self {
84            node: object.into_node(),
85            fov,
86            aspect,
87            near,
88            far,
89            zoom: 1.0,
90            focus: 10.0,
91            view: None,
92            film_gauge: 35.0,
93            film_offset: 0.0,
94            // `WebGPURenderer` sets `camera.coordinateSystem` to `WebGPUCoordinateSystem`.
95            coordinate_system: CoordinateSystem::WebGpu,
96            projection_matrix: Matrix4::identity(),
97            projection_matrix_inverse: Matrix4::identity(),
98            matrix_world_inverse: Matrix4::identity(),
99            viewport: None,
100        };
101        camera.update_projection_matrix();
102        camera
103    }
104
105    /// `PerspectiveCamera.setFocalLength()`.
106    pub fn set_focal_length(&mut self, focal_length: f64) {
107        // see http://www.bobatkins.com/photography/technical/field_of_view.html
108        let v_extent_slope = 0.5 * self.get_film_height() / focal_length;
109
110        self.fov = RAD2DEG * 2.0 * v_extent_slope.atan();
111        self.update_projection_matrix();
112    }
113
114    /// `PerspectiveCamera.getFocalLength()`.
115    pub fn get_focal_length(&self) -> f64 {
116        let v_extent_slope = (DEG2RAD * 0.5 * self.fov).tan();
117
118        0.5 * self.get_film_height() / v_extent_slope
119    }
120
121    /// `PerspectiveCamera.getEffectiveFOV()`.
122    pub fn get_effective_fov(&self) -> f64 {
123        RAD2DEG * 2.0 * ((DEG2RAD * 0.5 * self.fov).tan() / self.zoom).atan()
124    }
125
126    /// `PerspectiveCamera.getFilmWidth()`.
127    pub fn get_film_width(&self) -> f64 {
128        // film not completely covered in portrait format (aspect < 1)
129        self.film_gauge * js_min(self.aspect, 1.0)
130    }
131
132    /// `PerspectiveCamera.getFilmHeight()`.
133    pub fn get_film_height(&self) -> f64 {
134        // film not completely covered in landscape format (aspect > 1)
135        self.film_gauge / js_max(self.aspect, 1.0)
136    }
137
138    /// `PerspectiveCamera.getViewBounds()`.
139    pub fn get_view_bounds(
140        &self,
141        distance: f64,
142        min_target: &mut Vector2,
143        max_target: &mut Vector2,
144    ) {
145        let mut v3 = Vector3::new(-1.0, -1.0, 0.5);
146        v3.apply_matrix4(&self.projection_matrix_inverse);
147        min_target.set(v3.x, v3.y).multiply_scalar(-distance / v3.z);
148
149        let mut v3 = Vector3::new(1.0, 1.0, 0.5);
150        v3.apply_matrix4(&self.projection_matrix_inverse);
151        max_target.set(v3.x, v3.y).multiply_scalar(-distance / v3.z);
152    }
153
154    /// `PerspectiveCamera.getViewSize()`.
155    pub fn get_view_size(&self, distance: f64) -> Vector2 {
156        let mut min_target = Vector2::default();
157        let mut max_target = Vector2::default();
158        self.get_view_bounds(distance, &mut min_target, &mut max_target);
159
160        let mut target = Vector2::default();
161        target.sub_vectors(&max_target, &min_target);
162        target
163    }
164
165    /// `PerspectiveCamera.setViewOffset()`.
166    pub fn set_view_offset(
167        &mut self,
168        full_width: f64,
169        full_height: f64,
170        x: f64,
171        y: f64,
172        width: f64,
173        height: f64,
174    ) {
175        self.aspect = full_width / full_height;
176
177        self.view = Some(CameraView {
178            enabled: true,
179            full_width,
180            full_height,
181            offset_x: x,
182            offset_y: y,
183            width,
184            height,
185        });
186
187        self.update_projection_matrix();
188    }
189
190    /// `PerspectiveCamera.clearViewOffset()`.
191    pub fn clear_view_offset(&mut self) {
192        if let Some(view) = self.view.as_mut() {
193            view.enabled = false;
194        }
195
196        self.update_projection_matrix();
197    }
198
199    /// `PerspectiveCamera.updateProjectionMatrix()`.
200    pub fn update_projection_matrix(&mut self) {
201        let near = self.near;
202        let mut top = near * (DEG2RAD * 0.5 * self.fov).tan() / self.zoom;
203        let mut height = 2.0 * top;
204        let mut width = self.aspect * height;
205        let mut left = -0.5 * width;
206
207        if let Some(view) = self.view {
208            if view.enabled {
209                let full_width = view.full_width;
210                let full_height = view.full_height;
211
212                left += view.offset_x * width / full_width;
213                top -= view.offset_y * height / full_height;
214                width *= view.width / full_width;
215                height *= view.height / full_height;
216            }
217        }
218
219        let skew = self.film_offset;
220        if skew != 0.0 {
221            left += near * skew / self.get_film_width();
222        }
223
224        self.projection_matrix.make_perspective(
225            left,
226            left + width,
227            top,
228            top - height,
229            near,
230            self.far,
231            self.coordinate_system,
232        );
233
234        self.projection_matrix_inverse = self.projection_matrix;
235        self.projection_matrix_inverse.invert();
236    }
237
238    /// Move the camera along the direction it already looks in, until `box_`
239    /// fills the frame with `margin` of it left as slack (`0.0` is tight, `0.1`
240    /// leaves 10 % of the half-frame free on the tightest side). Not a three.js
241    /// method — see issue #51.
242    ///
243    /// The view *direction* is the camera's own, taken from `matrix_world`; only
244    /// the position moves, along that direction, and `near`/`far` are set to the
245    /// box's extent along it. `fov`, `aspect` and `zoom` are read, not written,
246    /// so the caller's framing choices survive the fit.
247    ///
248    /// The distance is the one that actually frames the box: a bounding sphere
249    /// wastes the corners, and so does taking the eight corners' *lateral*
250    /// extent, because a corner nearer the camera needs more distance than a far
251    /// one at the same offset. For each corner this asks what distance `d` puts
252    /// it exactly on a frustum plane — `|x| / tan_h - depth` horizontally,
253    /// `|y| / tan_v - depth` vertically, with `depth` the corner's offset along
254    /// the view direction from the box centre — and takes the largest of the
255    /// sixteen answers.
256    ///
257    /// A view offset ([`set_view_offset`](Self::set_view_offset)) is ignored;
258    /// the fit is to the full frustum.
259    pub fn fit(&mut self, box_: &crate::math::Box3, margin: f64) {
260        if box_.is_empty() {
261            return;
262        }
263
264        self.update_matrix_world();
265
266        let matrix_world = self.node.borrow().matrix_world;
267        let (right, up, forward) = super::view_basis(&matrix_world);
268        let offsets = super::corner_offsets(box_, &right, &up, &forward);
269
270        // The margin shrinks the half-angles, so the tightest corner lands at
271        // `1 - margin` in normalised device coordinates instead of at 1.
272        let slack = (1.0 - margin).clamp(f64::EPSILON, 1.0);
273        let tan_v = (DEG2RAD * 0.5 * self.fov).tan() / self.zoom * slack;
274        let tan_h = tan_v * self.aspect;
275
276        let mut distance = 0.0_f64;
277        let mut near_depth = f64::INFINITY;
278        let mut far_depth = f64::NEG_INFINITY;
279
280        for offset in &offsets {
281            distance = js_max(distance, offset.x.abs() / tan_h - offset.z);
282            distance = js_max(distance, offset.y.abs() / tan_v - offset.z);
283
284            near_depth = js_min(near_depth, offset.z);
285            far_depth = js_max(far_depth, offset.z);
286        }
287
288        // A box much deeper than it is wide can be framed from inside itself;
289        // hold it at the camera's current near plane instead.
290        let near_floor = js_max(self.near, f64::EPSILON);
291        distance = js_max(distance, near_floor - near_depth);
292
293        self.near = distance + near_depth;
294        self.far = distance + far_depth;
295        if self.far <= self.near {
296            // A box with no depth along the view direction.
297            self.far = self.near * 2.0;
298        }
299        self.update_projection_matrix();
300
301        // `position` is local; the direction and the centre are in world space.
302        let center = box_.get_center();
303        let mut position = Vector3::ZERO;
304        position
305            .copy(&forward)
306            .multiply_scalar(-distance)
307            .add(&center);
308
309        if let Some(parent) = self.node.parent() {
310            parent.update_world_matrix(true, false);
311            let mut inverse = parent.borrow().matrix_world;
312            inverse.invert();
313            position.apply_matrix4(&inverse);
314        }
315
316        self.node.borrow_mut().position = position;
317        self.update_matrix_world();
318    }
319
320    /// `Object3D.lookAt()` for a camera: the matrix looks *from* the camera
321    /// position *at* the target.
322    pub fn look_at(&mut self, target: &Vector3) {
323        let mut object = self.node.borrow_mut();
324        let mut m = Matrix4::identity();
325        m.look_at(&object.position, target, &object.up);
326        object.quaternion.set_from_rotation_matrix(&m);
327    }
328
329    /// `Camera.updateMatrixWorld()`.
330    pub fn update_matrix_world(&mut self) {
331        self.node.update_matrix_world(false);
332        self.matrix_world_inverse = self.node.borrow().matrix_world;
333        self.matrix_world_inverse.invert();
334    }
335}