three_rs/core/raycaster.rs
1//! Port of `three.js/src/core/Raycaster.js`, together with the intersection
2//! record every `Object3D.raycast()` fills in and the dispatch from a scene
3//! node to its subclass's `raycast()`.
4//!
5//! three.js dispatches `object.raycast( raycaster, intersects )` through the
6//! prototype chain. The port's subclasses live in a node's
7//! [`Payload`](crate::objects::Payload), so [`ObjectRef::raycast`] matches on it and
8//! calls the ported method of whichever subclass is there; a plain
9//! `Object3D` / `Group` / light raycasts to nothing, as `Object3D.raycast()`
10//! does.
11
12use crate::cameras::RenderCamera;
13use crate::core::{Layers, ObjectRef};
14use crate::math::{Matrix4, Ray, Vector2, Vector3};
15
16/// The camera state `Raycaster.camera` is read for — by `Sprite.raycast()`
17/// and by `LineSegments2`'s screen-space raycast.
18///
19/// three.js stores a *reference* to the camera, so a raycast sees the camera
20/// as it is when `intersectObject()` runs. The port's cameras are plain
21/// structs rather than scene nodes both can point at, so
22/// [`Raycaster::set_from_camera`] copies what those two methods read. A
23/// camera that moves between `setFromCamera()` and `intersectObject()` is the
24/// one case where the two differ; every three.js example sets the ray and
25/// intersects in the same breath.
26#[derive(Clone, Copy, Debug, PartialEq)]
27pub struct RaycasterCamera {
28 /// `camera.isPerspectiveCamera`.
29 pub is_perspective_camera: bool,
30 /// `camera.isOrthographicCamera`.
31 pub is_orthographic_camera: bool,
32 /// `camera.near`.
33 pub near: f64,
34 /// `camera.far`.
35 pub far: f64,
36 /// `camera.matrixWorld`.
37 pub matrix_world: Matrix4,
38 /// `camera.matrixWorldInverse`.
39 pub matrix_world_inverse: Matrix4,
40 /// `camera.projectionMatrix`.
41 pub projection_matrix: Matrix4,
42 /// `camera.projectionMatrixInverse`.
43 pub projection_matrix_inverse: Matrix4,
44}
45
46impl RaycasterCamera {
47 /// Snapshot `camera`.
48 pub fn of(camera: &impl RenderCamera) -> Self {
49 Self {
50 is_perspective_camera: camera.is_perspective_camera(),
51 is_orthographic_camera: camera.is_orthographic_camera(),
52 near: camera.near(),
53 far: camera.far(),
54 matrix_world: camera.matrix_world(),
55 matrix_world_inverse: camera.matrix_world_inverse(),
56 projection_matrix: camera.projection_matrix(),
57 projection_matrix_inverse: camera.projection_matrix_inverse(),
58 }
59 }
60}
61
62/// One `{ threshold }` entry of `Raycaster.params`.
63#[derive(Clone, Copy, Debug, PartialEq)]
64pub struct Threshold {
65 /// The distance within which a ray counts as a hit.
66 pub threshold: f64,
67}
68
69/// `Raycaster.params`.
70///
71/// three.js' object also has empty `Mesh`, `LOD` and `Sprite` entries, which
72/// nothing reads; they are left out rather than ported as unit structs.
73#[derive(Clone, Copy, Debug, PartialEq)]
74#[non_exhaustive]
75pub struct RaycasterParams {
76 /// `params.Line` — the world-space distance within which a ray hits a
77 /// `Line` / `LineSegments`. Default 1.
78 pub line: Threshold,
79 /// `params.Points` — the same for `Points`. Default 1.
80 pub points: Threshold,
81 /// `params.Line2` — extra width added to a fat line's `linewidth` by
82 /// `LineSegments2.raycast()`. three.js has no such entry until an app adds
83 /// one (`raycaster.params.Line2 = { threshold: 0 }` in
84 /// `webgpu_lines_fat_raycasting`), and the addon then reads
85 /// `params.Line2?.threshold || 0`; 0 here is that absent entry.
86 pub line2: Threshold,
87}
88
89impl Default for RaycasterParams {
90 fn default() -> Self {
91 Self {
92 line: Threshold { threshold: 1.0 },
93 points: Threshold { threshold: 1.0 },
94 line2: Threshold { threshold: 0.0 },
95 }
96 }
97}
98
99/// `intersection.face` — the triangle a mesh ray hit.
100#[derive(Clone, Copy, Debug, PartialEq)]
101pub struct Face {
102 /// Vertex indices of the triangle.
103 pub a: usize,
104 /// The triangle's second vertex index.
105 pub b: usize,
106 /// The triangle's third vertex index.
107 pub c: usize,
108 /// `Triangle.getNormal()` of the (morphed, skinned) triangle, in object
109 /// space.
110 pub normal: Vector3,
111 /// `face.materialIndex`. Always 0 in the port: see
112 /// [`Mesh`](crate::objects::Mesh)'s raycast, which has a single material.
113 pub material_index: usize,
114}
115
116/// One entry of the array `Raycaster.intersectObject()` returns.
117///
118/// three.js builds a plain object whose keys depend on what was hit; every key
119/// that some `raycast()` can leave out is an `Option` here, `None` being both
120/// three's absent key and its explicit `null`.
121#[derive(Clone, Debug)]
122pub struct Intersection {
123 /// `distance` — from the ray origin to the hit, in world units.
124 pub distance: f64,
125 /// `distanceToRay` — `Points` only: how far the point is from the ray.
126 pub distance_to_ray: Option<f64>,
127 /// `point` — the hit in world space.
128 pub point: Vector3,
129 /// `pointOnLine` — `LineSegments2` only: the closest point on the segment.
130 pub point_on_line: Option<Vector3>,
131 /// `index` — `Line` / `Points` only: the segment's first vertex, or the
132 /// point.
133 pub index: Option<usize>,
134 /// `face` — meshes only.
135 pub face: Option<Face>,
136 /// `faceIndex` — the triangle number for a mesh, the segment number for a
137 /// `LineSegments2`.
138 pub face_index: Option<usize>,
139 /// `uv` at the hit — meshes with a `uv` attribute, and sprites.
140 pub uv: Option<Vector2>,
141 /// `uv1` at the hit.
142 pub uv1: Option<Vector2>,
143 /// `normal` — the interpolated vertex normal, flipped to face the ray.
144 pub normal: Option<Vector3>,
145 /// `barycoord` — the hit's barycentric coordinates in the triangle.
146 pub barycoord: Option<Vector3>,
147 /// `instanceId` — `InstancedMesh` only.
148 pub instance_id: Option<usize>,
149 /// `batchId` — `BatchedMesh` only.
150 pub batch_id: Option<usize>,
151 /// `object` — the object that was hit.
152 pub object: ObjectRef,
153}
154
155impl Intersection {
156 /// The fields every hit has; the rest start absent.
157 pub fn new(distance: f64, point: Vector3, object: ObjectRef) -> Self {
158 Self {
159 distance,
160 distance_to_ray: None,
161 point,
162 point_on_line: None,
163 index: None,
164 face: None,
165 face_index: None,
166 uv: None,
167 uv1: None,
168 normal: None,
169 barycoord: None,
170 instance_id: None,
171 batch_id: None,
172 object,
173 }
174 }
175}
176
177/// `Raycaster` — picks the objects a ray passes through.
178#[derive(Clone, Debug)]
179pub struct Raycaster {
180 /// `raycaster.ray` — its direction is assumed normalised.
181 pub ray: Ray,
182 /// `raycaster.near` — hits closer than this are dropped. Default 0.
183 pub near: f64,
184 /// `raycaster.far` — hits farther than this are dropped. Default ∞.
185 pub far: f64,
186 /// `raycaster.camera`, set by [`set_from_camera`](Self::set_from_camera):
187 /// `null` until then. See [`RaycasterCamera`] for why it is a copy.
188 pub camera: Option<RaycasterCamera>,
189 /// `raycaster.layers` — an object is only tested when its layers share one
190 /// with these, though its children are still visited.
191 pub layers: Layers,
192 /// `raycaster.params`.
193 pub params: RaycasterParams,
194}
195
196impl Default for Raycaster {
197 /// `new Raycaster()` — the default `Ray`, near 0, far ∞.
198 fn default() -> Self {
199 let ray = Ray::default();
200 Self::new(ray.origin, ray.direction, 0.0, f64::INFINITY)
201 }
202}
203
204impl Raycaster {
205 /// `new Raycaster( origin, direction, near, far )`.
206 pub fn new(origin: Vector3, direction: Vector3, near: f64, far: f64) -> Self {
207 Self {
208 ray: Ray::new(origin, direction),
209 near,
210 far,
211 camera: None,
212 layers: Layers::new(),
213 params: RaycasterParams::default(),
214 }
215 }
216
217 /// `raycaster.set( origin, direction )` — `direction` is assumed
218 /// normalised, for accurate distances.
219 pub fn set(&mut self, origin: &Vector3, direction: &Vector3) {
220 self.ray.set(origin, direction);
221 }
222
223 /// `raycaster.setFromCamera( coords, camera )` — a ray from the camera
224 /// through `coords`, in normalised device coordinates (`-1 … 1` on both
225 /// axes, `y` up).
226 pub fn set_from_camera(&mut self, coords: &Vector2, camera: &impl RenderCamera) {
227 if camera.is_perspective_camera() {
228 self.ray
229 .origin
230 .set_from_matrix_position(&camera.matrix_world());
231 let origin = self.ray.origin;
232 self.ray.direction = Vector3::new(coords.x, coords.y, 0.5);
233 self.ray
234 .direction
235 .unproject(camera)
236 .sub(&origin)
237 .normalize();
238 self.camera = Some(RaycasterCamera::of(camera));
239 } else if camera.is_orthographic_camera() {
240 // Set the origin in the plane of the camera.
241 let z = camera.projection_matrix().elements[14];
242 self.ray.origin = Vector3::new(coords.x, coords.y, z);
243 self.ray.origin.unproject(camera);
244 self.ray.direction = Vector3::new(0.0, 0.0, -1.0);
245 self.ray
246 .direction
247 .transform_direction(&camera.matrix_world());
248 self.camera = Some(RaycasterCamera::of(camera));
249 } else {
250 eprintln!("THREE.Raycaster: Unsupported camera type.");
251 }
252 }
253
254 /// `raycaster.intersectObject( object, recursive )` — every hit on
255 /// `object`, and on its descendants when `recursive` (three's default),
256 /// nearest first.
257 pub fn intersect_object(&self, object: &ObjectRef, recursive: bool) -> Vec<Intersection> {
258 let mut intersects = Vec::new();
259 intersect(object, self, &mut intersects, recursive);
260 sort(&mut intersects);
261 intersects
262 }
263
264 /// `raycaster.intersectObjects( objects, recursive )`.
265 pub fn intersect_objects(&self, objects: &[ObjectRef], recursive: bool) -> Vec<Intersection> {
266 let mut intersects = Vec::new();
267 for object in objects {
268 intersect(object, self, &mut intersects, recursive);
269 }
270 sort(&mut intersects);
271 intersects
272 }
273}
274
275/// `intersects.sort( ascSort )`. `Array.prototype.sort` is stable, and so is
276/// `sort_by`; a `NaN` distance compares equal, where JavaScript's comparator
277/// would return `NaN` and leave the pair alone too.
278fn sort(intersects: &mut [Intersection]) {
279 intersects.sort_by(|a, b| {
280 a.distance
281 .partial_cmp(&b.distance)
282 .unwrap_or(std::cmp::Ordering::Equal)
283 });
284}
285
286/// `intersect( object, raycaster, intersects, recursive )`.
287///
288/// The layer test gates the object's own `raycast()` only: its children are
289/// visited either way. three's `propagate` flag, which a `raycast()` that
290/// returns `false` clears, exists for `LOD`, which is not ported.
291fn intersect(
292 object: &ObjectRef,
293 raycaster: &Raycaster,
294 intersects: &mut Vec<Intersection>,
295 recursive: bool,
296) {
297 let tested = object.borrow().layers.test(&raycaster.layers);
298 if tested {
299 object.raycast(raycaster, intersects);
300 }
301
302 if recursive {
303 for child in object.children() {
304 intersect(&child, raycaster, intersects, true);
305 }
306 }
307}
308
309impl ObjectRef {
310 /// `object.raycast( raycaster, intersects )` — push this object's hits
311 /// (unsorted) onto `intersects`. Dispatches on the subclass in the
312 /// payload; an object that draws nothing has nothing to hit.
313 pub fn raycast(&self, raycaster: &Raycaster, intersects: &mut Vec<Intersection>) {
314 use crate::objects::Payload;
315
316 // `BatchedMesh.raycast()` lazily computes per-geometry bounds, and
317 // `InstancedMesh` / `SkinnedMesh` their own bounding volumes, so the
318 // borrow is mutable.
319 let mut object = self.borrow_mut();
320 let matrix_world = object.matrix_world;
321 let scale = object.scale;
322 match &mut object.payload {
323 Payload::None | Payload::Light(_) | Payload::ClippingGroup(_) => {}
324 Payload::Mesh(mesh) => {
325 if mesh.line_segments.is_some() {
326 crate::addons::lines::raycast(mesh, &matrix_world, self, raycaster, intersects);
327 } else {
328 mesh.raycast(&matrix_world, self, raycaster, intersects);
329 }
330 }
331 Payload::SkinnedMesh(skinned) => {
332 skinned.raycast(&matrix_world, self, raycaster, intersects)
333 }
334 Payload::InstancedMesh(instanced) => {
335 instanced.raycast(&matrix_world, self, raycaster, intersects)
336 }
337 Payload::BatchedMesh(batched) => {
338 batched.raycast(&matrix_world, self, raycaster, intersects)
339 }
340 Payload::Line(line) => line.raycast(&matrix_world, &scale, self, raycaster, intersects),
341 Payload::Points(points) => {
342 points.raycast(&matrix_world, &scale, self, raycaster, intersects)
343 }
344 Payload::Sprite(sprite) => sprite.raycast(&matrix_world, self, raycaster, intersects),
345 }
346 }
347}