Skip to main content

three_rs/cameras/
mod.rs

1//! Ports of `three.js/src/cameras`.
2
3mod array_camera;
4mod cube_camera;
5mod orthographic_camera;
6mod perspective_camera;
7mod stereo_camera;
8
9pub use array_camera::ArrayCamera;
10pub use cube_camera::CubeCamera;
11pub use orthographic_camera::OrthographicCamera;
12pub use perspective_camera::{CameraView, PerspectiveCamera};
13pub use stereo_camera::StereoCamera;
14
15use crate::core::Layers;
16use crate::math::{Box3, CoordinateSystem, Matrix4, Vector3};
17
18mod sealed {
19    pub trait Sealed {}
20    impl Sealed for super::ArrayCamera {}
21    impl Sealed for super::OrthographicCamera {}
22    impl Sealed for super::PerspectiveCamera {}
23}
24
25/// A `&mut PerspectiveCamera` that is either plain or taken out of a
26/// `RefCell`.
27///
28/// An example whose `pass( scene, camera )` renders from `updateBefore()`
29/// shares its camera with the pass (`docs/nodes.md` §57), so it holds an
30/// `Rc<RefCell<PerspectiveCamera>>` and can only lend the camera as a
31/// `RefMut`. The viewer and the browser shell hand either kind to
32/// `OrbitControls`, which takes `&mut PerspectiveCamera`; this is what they
33/// hold in between.
34#[doc(hidden)]
35pub enum CameraMut<'a> {
36    /// A camera that is a plain field of the example.
37    Borrowed(&'a mut PerspectiveCamera),
38    /// A camera the example shares with its passes.
39    Shared(std::cell::RefMut<'a, PerspectiveCamera>),
40}
41
42impl std::ops::Deref for CameraMut<'_> {
43    type Target = PerspectiveCamera;
44
45    fn deref(&self) -> &PerspectiveCamera {
46        match self {
47            Self::Borrowed(camera) => camera,
48            Self::Shared(camera) => camera,
49        }
50    }
51}
52
53impl std::ops::DerefMut for CameraMut<'_> {
54    fn deref_mut(&mut self) -> &mut PerspectiveCamera {
55        match self {
56            Self::Borrowed(camera) => camera,
57            Self::Shared(camera) => camera,
58        }
59    }
60}
61
62impl<'a> From<&'a mut PerspectiveCamera> for CameraMut<'a> {
63    fn from(camera: &'a mut PerspectiveCamera) -> Self {
64        Self::Borrowed(camera)
65    }
66}
67
68impl<'a> From<std::cell::RefMut<'a, PerspectiveCamera>> for CameraMut<'a> {
69    fn from(camera: std::cell::RefMut<'a, PerspectiveCamera>) -> Self {
70        Self::Shared(camera)
71    }
72}
73
74/// The slice of `Camera` that `Renderer.render()` and `_projectObject()`
75/// actually read: `updateMatrixWorld()`, `projectionMatrix`,
76/// `matrixWorldInverse`, `matrixWorld`, `layers` and `coordinateSystem`.
77///
78/// `Vector3::project()`/`unproject()` read the same four matrix accessors, and
79/// `Raycaster.setFromCamera()` reads them and the type flags; nothing here is
80/// renderer-only.
81///
82/// three.js has a real `Camera extends Object3D` base class that both cameras
83/// extend; the port grew `PerspectiveCamera` first and kept them as separate
84/// structs, so this trait is the base class's render-facing surface rather than
85/// a new idea. It exists because lib3's SDF text page — and d33's, and three's
86/// own `QuadMesh` path — use an `OrthographicCamera`, and `render()` took a
87/// `&mut PerspectiveCamera` by name.
88///
89/// Sealed: it is implemented for `ArrayCamera`, `OrthographicCamera` and
90/// `PerspectiveCamera` only, which is what three.js' render path takes, so a
91/// method can be added to it without a break.
92pub trait RenderCamera: sealed::Sealed {
93    /// `camera.updateMatrixWorld()`, which also refreshes `matrixWorldInverse`.
94    fn update_matrix_world(&mut self);
95    /// `camera.projectionMatrix`.
96    fn projection_matrix(&self) -> Matrix4;
97    /// `camera.projectionMatrixInverse`, kept current by
98    /// `update_projection_matrix()` on both cameras.
99    fn projection_matrix_inverse(&self) -> Matrix4;
100    /// `camera.matrixWorldInverse` — the view matrix.
101    fn matrix_world_inverse(&self) -> Matrix4;
102    /// `camera.coordinateSystem`.
103    fn coordinate_system(&self) -> CoordinateSystem;
104    /// `camera.matrixWorld`.
105    fn matrix_world(&self) -> Matrix4;
106    /// `camera.layers`.
107    fn layers(&self) -> Layers;
108    /// `camera.id` — the key `ReflectorBaseNode`'s `virtualCameras` map is
109    /// held on.
110    fn id(&self) -> u32;
111    /// `camera.far` — the sort key scale `BatchedMesh`' custom sort uses.
112    fn far(&self) -> f64;
113    /// `camera.near` — `LineSegments2`' screen-space raycast clips to it.
114    fn near(&self) -> f64;
115    /// `camera.setViewOffset( fullWidth, fullHeight, x, y, width, height )`,
116    /// which both of three's cameras implement and `updateProjectionMatrix()`s
117    /// through. On the trait so a render-pipeline hook or a pass node can
118    /// jitter whichever camera it was handed (TRAA's
119    /// `OnBeforeRenderPipeline`, issue #154 decision 3).
120    fn set_view_offset(
121        &mut self,
122        full_width: f64,
123        full_height: f64,
124        x: f64,
125        y: f64,
126        width: f64,
127        height: f64,
128    );
129    /// `camera.clearViewOffset()`.
130    fn clear_view_offset(&mut self);
131    /// `camera.isPerspectiveCamera`.
132    fn is_perspective_camera(&self) -> bool {
133        false
134    }
135    /// `camera.isOrthographicCamera`.
136    fn is_orthographic_camera(&self) -> bool {
137        false
138    }
139    /// `camera.isArrayCamera ? camera.cameras : []` — the sub-cameras one
140    /// render draws through, each into its own viewport. Empty for every
141    /// camera but an [`ArrayCamera`].
142    fn sub_cameras(&self) -> &[PerspectiveCamera] {
143        &[]
144    }
145    /// The camera as a scene-graph object — `Camera extends Object3D` — for
146    /// what needs the object itself rather than a copy of its matrices
147    /// (`CameraHelper`'s `this.matrix = camera.matrixWorld`). `None` for a
148    /// camera the port keeps outside the graph (`OrthographicCamera`).
149    fn node(&self) -> Option<&crate::core::ObjectRef> {
150        None
151    }
152}
153
154impl RenderCamera for PerspectiveCamera {
155    fn node(&self) -> Option<&crate::core::ObjectRef> {
156        Some(&self.node)
157    }
158    fn set_view_offset(
159        &mut self,
160        full_width: f64,
161        full_height: f64,
162        x: f64,
163        y: f64,
164        width: f64,
165        height: f64,
166    ) {
167        self.set_view_offset(full_width, full_height, x, y, width, height);
168    }
169    fn clear_view_offset(&mut self) {
170        self.clear_view_offset();
171    }
172    fn far(&self) -> f64 {
173        self.far
174    }
175    fn near(&self) -> f64 {
176        self.near
177    }
178    fn is_perspective_camera(&self) -> bool {
179        true
180    }
181    fn update_matrix_world(&mut self) {
182        self.update_matrix_world();
183    }
184    fn projection_matrix(&self) -> Matrix4 {
185        self.projection_matrix
186    }
187    fn projection_matrix_inverse(&self) -> Matrix4 {
188        self.projection_matrix_inverse
189    }
190    fn matrix_world_inverse(&self) -> Matrix4 {
191        self.matrix_world_inverse
192    }
193    fn coordinate_system(&self) -> CoordinateSystem {
194        self.coordinate_system
195    }
196    fn matrix_world(&self) -> Matrix4 {
197        self.node.borrow().matrix_world
198    }
199    fn layers(&self) -> Layers {
200        self.node.borrow().layers
201    }
202    fn id(&self) -> u32 {
203        self.node.borrow().id
204    }
205}
206
207impl RenderCamera for OrthographicCamera {
208    fn set_view_offset(
209        &mut self,
210        full_width: f64,
211        full_height: f64,
212        x: f64,
213        y: f64,
214        width: f64,
215        height: f64,
216    ) {
217        self.set_view_offset(full_width, full_height, x, y, width, height);
218    }
219    fn clear_view_offset(&mut self) {
220        self.clear_view_offset();
221    }
222    fn far(&self) -> f64 {
223        self.far
224    }
225    fn near(&self) -> f64 {
226        self.near
227    }
228    fn is_orthographic_camera(&self) -> bool {
229        true
230    }
231    fn update_matrix_world(&mut self) {
232        self.update_matrix_world();
233    }
234    fn projection_matrix(&self) -> Matrix4 {
235        self.projection_matrix
236    }
237    fn projection_matrix_inverse(&self) -> Matrix4 {
238        self.projection_matrix_inverse
239    }
240    fn matrix_world_inverse(&self) -> Matrix4 {
241        self.matrix_world_inverse
242    }
243    fn coordinate_system(&self) -> CoordinateSystem {
244        self.coordinate_system
245    }
246    fn matrix_world(&self) -> Matrix4 {
247        self.object.matrix_world
248    }
249    fn layers(&self) -> Layers {
250        self.object.layers
251    }
252    fn id(&self) -> u32 {
253        self.object.id
254    }
255}
256
257/// The camera's world basis, for [`PerspectiveCamera::fit`] and
258/// [`OrthographicCamera::fit`]: the x and y columns of `matrix_world`, and
259/// *minus* its z column, which is the direction a camera looks along. All three
260/// are normalised, so a scaled camera node still gives a unit basis.
261fn view_basis(matrix_world: &Matrix4) -> (Vector3, Vector3, Vector3) {
262    let mut right = Vector3::ZERO;
263    let mut up = Vector3::ZERO;
264    let mut forward = Vector3::ZERO;
265    matrix_world.extract_basis(&mut right, &mut up, &mut forward);
266
267    right.normalize();
268    up.normalize();
269    forward.normalize().negate();
270
271    (right, up, forward)
272}
273
274/// The box's eight corners as offsets from its centre, resolved in a camera
275/// basis: `x` is the offset along `right`, `y` along `up`, `z` along `forward`
276/// — that is, how much deeper than the centre the corner lies.
277fn corner_offsets(box_: &Box3, right: &Vector3, up: &Vector3, forward: &Vector3) -> [Vector3; 8] {
278    let center = box_.get_center();
279    let mut offsets = [Vector3::ZERO; 8];
280
281    for (i, offset) in offsets.iter_mut().enumerate() {
282        // The same binary pattern `Box3::apply_matrix4()` uses.
283        let corner = Vector3::new(
284            if i & 4 == 0 { box_.min.x } else { box_.max.x },
285            if i & 2 == 0 { box_.min.y } else { box_.max.y },
286            if i & 1 == 0 { box_.min.z } else { box_.max.z },
287        );
288
289        let mut d = Vector3::ZERO;
290        d.sub_vectors(&corner, &center);
291
292        offset.set(d.dot(right), d.dot(up), d.dot(forward));
293    }
294
295    offsets
296}