Skip to main content

three_rs/helpers/
camera_helper.rs

1//! Port of `three.js/src/helpers/CameraHelper.js`.
2
3use std::collections::HashMap;
4use std::rc::Rc;
5
6use crate::cameras::RenderCamera;
7use crate::core::{BufferAttribute, BufferGeometry, ObjectRef};
8use crate::materials::MeshBasicNodeMaterial;
9use crate::math::{Color, CoordinateSystem, Vector3};
10use crate::objects::LineSegments;
11
12/// `new CameraHelper( camera )` — a `LineSegments` of the camera's frustum,
13/// cone, up triangle, target line and cross hairs, in the camera's local
14/// space, drawn with vertex colours.
15///
16/// Three sets `this.matrix = camera.matrixWorld` — the helper *shares* the
17/// camera's world matrix object — with `matrixAutoUpdate = false`, so every
18/// `updateMatrixWorld()` traversal that reaches the helper multiplies in
19/// whatever the camera's world matrix holds at that moment. The port's
20/// [`Object3D::matrix_alias`](crate::core::Object3D::matrix_alias) is that
21/// sharing, read at the same point of the traversal; `webgpu_camera` depends
22/// on it, since the helper sits before the camera in the scene and so sees the
23/// camera's matrix from the previous traversal.
24///
25/// A camera with no scene-graph node (the port's `OrthographicCamera`) cannot
26/// be aliased; its helper takes a copy of the camera's world matrix instead.
27pub struct CameraHelper {
28    /// The `LineSegments` itself.
29    pub node: ObjectRef,
30    /// `this.pointMap` — each named point's vertex indices.
31    point_map: HashMap<&'static str, Vec<usize>>,
32}
33
34/// The constructor's `addLine()` calls, in order.
35const LINES: [(&str, &str); 25] = [
36    // near
37    ("n1", "n2"),
38    ("n2", "n4"),
39    ("n4", "n3"),
40    ("n3", "n1"),
41    // far
42    ("f1", "f2"),
43    ("f2", "f4"),
44    ("f4", "f3"),
45    ("f3", "f1"),
46    // sides
47    ("n1", "f1"),
48    ("n2", "f2"),
49    ("n3", "f3"),
50    ("n4", "f4"),
51    // cone
52    ("p", "n1"),
53    ("p", "n2"),
54    ("p", "n3"),
55    ("p", "n4"),
56    // up
57    ("u1", "u2"),
58    ("u2", "u3"),
59    ("u3", "u1"),
60    // target
61    ("c", "t"),
62    ("p", "c"),
63    // cross
64    ("cn1", "cn2"),
65    ("cn3", "cn4"),
66    ("cf1", "cf2"),
67    ("cf3", "cf4"),
68];
69
70impl CameraHelper {
71    /// `new CameraHelper( camera )`.
72    ///
73    /// Three's constructor calls `camera.updateProjectionMatrix()` first; both
74    /// of the port's cameras compute their projection in `new` and on every
75    /// `update_projection_matrix()`, so the call is already made by the time a
76    /// helper can be built for them.
77    pub fn new(camera: &dyn RenderCamera) -> Self {
78        let mut vertices: Vec<f32> = Vec::new();
79        let mut colors: Vec<f32> = Vec::new();
80        let mut point_map: HashMap<&'static str, Vec<usize>> = HashMap::new();
81
82        let mut add_point = |id: &'static str| {
83            vertices.extend([0.0, 0.0, 0.0]);
84            colors.extend([0.0, 0.0, 0.0]);
85            point_map
86                .entry(id)
87                .or_default()
88                .push(vertices.len() / 3 - 1);
89        };
90        for (a, b) in LINES {
91            add_point(a);
92            add_point(b);
93        }
94
95        let mut geometry = BufferGeometry::new();
96        geometry.set_attribute("position", BufferAttribute::new(vertices, 3));
97        geometry.set_attribute("color", BufferAttribute::new(colors, 3));
98
99        // `new LineBasicMaterial( { color: 0xffffff, vertexColors: true,
100        // toneMapped: false } )`. `toneMapped` has no counterpart, as in
101        // `GridHelper`: the port tone maps in the output pass.
102        let mut material = MeshBasicNodeMaterial::line(Color::from_hex(0xffffff));
103        material.vertex_colors = true;
104
105        let node = LineSegments::new(Rc::new(geometry), material);
106        {
107            let mut object = node.borrow_mut();
108            object.object_type = "CameraHelper";
109            // `this.matrix = camera.matrixWorld; this.matrixAutoUpdate = false`.
110            match camera.node() {
111                Some(camera_node) => object.matrix_alias = Some(camera_node.downgrade()),
112                None => object.matrix = camera.matrix_world(),
113            }
114            object.matrix_auto_update = false;
115        }
116
117        let helper = Self { node, point_map };
118        helper.update(camera);
119
120        // colors
121        helper.set_colors(
122            Color::from_hex(0xffaa00),
123            Color::from_hex(0xff0000),
124            Color::from_hex(0x00aaff),
125            Color::from_hex(0xffffff),
126            Color::from_hex(0x333333),
127        );
128
129        helper
130    }
131
132    fn geometry(&self) -> Rc<BufferGeometry> {
133        self.node
134            .borrow()
135            .geometry()
136            .expect("three-rs: a CameraHelper is a LineSegments")
137            .clone()
138    }
139
140    /// `CameraHelper.setColors( frustum, cone, up, target, cross )` — vertices
141    /// 0–23 frustum, 24–31 cone, 32–37 up, 38–39 target, 40–49 cross (the
142    /// `p`–`c` line included).
143    pub fn set_colors(&self, frustum: Color, cone: Color, up: Color, target: Color, cross: Color) {
144        let geometry = self.geometry();
145        let color_attribute = geometry
146            .get_attribute("color")
147            .expect("three-rs: the helper has a color attribute");
148        {
149            let mut array = color_attribute.array_mut();
150            for i in 0..50 {
151                let color = match i {
152                    0..=23 => frustum,
153                    24..=31 => cone,
154                    32..=37 => up,
155                    38..=39 => target,
156                    _ => cross,
157                };
158                array[i * 3..i * 3 + 3].copy_from_slice(&[
159                    color.r as f32,
160                    color.g as f32,
161                    color.b as f32,
162                ]);
163            }
164        }
165        color_attribute.set_needs_update();
166    }
167
168    /// `CameraHelper.update()`: every named point un-projected from NDC
169    /// through the camera's `projectionMatrixInverse` alone (three's `_camera`
170    /// has an identity world matrix — the helper's own matrix places it).
171    ///
172    /// `camera.reversedDepth` is never set on the port's cameras, so the near
173    /// and far planes are the coordinate system's: `-1`/`1` under WebGL, `0`/`1`
174    /// under WebGPU.
175    pub fn update(&self, camera: &dyn RenderCamera) {
176        let (w, h) = (1.0, 1.0);
177
178        let (near_z, far_z) = match camera.coordinate_system() {
179            CoordinateSystem::WebGl => (-1.0, 1.0),
180            CoordinateSystem::WebGpu => (0.0, 1.0),
181        };
182
183        let projection_matrix_inverse = camera.projection_matrix_inverse();
184        let geometry = self.geometry();
185        let position = geometry
186            .get_attribute("position")
187            .expect("three-rs: the helper has a position attribute");
188
189        let points: [(&str, f64, f64, f64); 21] = [
190            // center / target
191            ("c", 0.0, 0.0, near_z),
192            ("t", 0.0, 0.0, far_z),
193            // near
194            ("n1", -w, -h, near_z),
195            ("n2", w, -h, near_z),
196            ("n3", -w, h, near_z),
197            ("n4", w, h, near_z),
198            // far
199            ("f1", -w, -h, far_z),
200            ("f2", w, -h, far_z),
201            ("f3", -w, h, far_z),
202            ("f4", w, h, far_z),
203            // up
204            ("u1", w * 0.7, h * 1.1, near_z),
205            ("u2", -w * 0.7, h * 1.1, near_z),
206            ("u3", 0.0, h * 2.0, near_z),
207            // cross
208            ("cf1", -w, 0.0, far_z),
209            ("cf2", w, 0.0, far_z),
210            ("cf3", 0.0, -h, far_z),
211            ("cf4", 0.0, h, far_z),
212            ("cn1", -w, 0.0, near_z),
213            ("cn2", w, 0.0, near_z),
214            ("cn3", 0.0, -h, near_z),
215            ("cn4", 0.0, h, near_z),
216        ];
217        // `p` is never set: its vertices stay at the origin, the camera's eye.
218
219        {
220            let mut array = position.array_mut();
221            for (point, x, y, z) in points {
222                // `setPoint()`: `_vector.set( x, y, z ).unproject( _camera )`.
223                let Some(indices) = self.point_map.get(point) else {
224                    continue;
225                };
226                let mut vector = Vector3::new(x, y, z);
227                vector.apply_matrix4(&projection_matrix_inverse);
228                for &i in indices {
229                    array[i * 3..i * 3 + 3].copy_from_slice(&[
230                        vector.x as f32,
231                        vector.y as f32,
232                        vector.z as f32,
233                    ]);
234                }
235            }
236        }
237        position.set_needs_update();
238    }
239}