Skip to main content

three_rs/objects/
payload.rs

1//! What a scene-graph node *is*, beyond its transform.
2//!
3//! three.js gets this from subclassing: `Mesh extends Object3D` adds `geometry`
4//! and `material`, and `Renderer._projectObject()` branches on `object.isMesh`.
5//! Rust has no inheritance, so the subclass' extra state is a variant of
6//! [`Payload`] held by [`crate::core::Object3D`], and `isMesh` is a `match`.
7//!
8//! This replaces the flat `Scene.children: Vec<Child>` list the renderer used to
9//! iterate: a payload lives on the node itself, so a `Mesh` can sit anywhere in
10//! the tree (under a `Group`, under a light) and the renderer's traversal finds
11//! it. See `docs/scene-graph.md`.
12
13use std::fmt;
14
15use std::rc::Rc;
16
17use crate::core::BufferGeometry;
18use crate::lights::LightObject;
19use crate::materials::MeshBasicNodeMaterial;
20use crate::math::{Matrix4, Sphere};
21use crate::objects::{
22    BatchedMesh, ClippingGroup, InstancedBufferAttribute, InstancedMesh, Line, Mesh, Points,
23    SkinnedMesh, Sprite,
24};
25
26/// The subclass state of one [`crate::core::Object3D`].
27///
28/// `None` is a plain `Object3D`, a `Group`, a `Bone` — anything the renderer
29/// walks through without drawing.
30#[derive(Clone, Default)]
31#[non_exhaustive]
32pub enum Payload {
33    /// A plain `Object3D`, a `Group` or a `Bone`: nothing to draw.
34    #[default]
35    None,
36    /// `Mesh.geometry` / `Mesh.material`.
37    Mesh(Mesh),
38    /// `InstancedMesh extends Mesh`.
39    InstancedMesh(InstancedMesh),
40    /// `SkinnedMesh extends Mesh` — the skeleton and the two bind matrices on
41    /// top of the `Mesh`. `is_mesh()` is true for it, as `isMesh` is in
42    /// three.js. Boxed because the two bind matrices and the bounding volumes
43    /// make it half again the size of the next-largest variant, and every
44    /// `Object3D` in the tree carries a `Payload`.
45    SkinnedMesh(Box<SkinnedMesh>),
46    /// `BatchedMesh extends Mesh` — boxed because it is much the largest
47    /// variant (three data textures and two draw-list arrays).
48    BatchedMesh(Box<BatchedMesh>),
49    /// `Line extends Object3D` — and `LineSegments extends Line`, which is the
50    /// `is_line_segments` flag inside. Not a `Mesh`: the renderer reads the
51    /// object to pick `line-strip` / `line-list` over `triangle-list`.
52    Line(Line),
53    /// `Points extends Object3D` — like `Line`, not a `Mesh`: the renderer
54    /// reads the object to pick `point-list` over `triangle-list`.
55    Points(Points),
56    /// `Sprite extends Object3D` — not a `Mesh` either: `_projectObject()`
57    /// gives it an arm of its own, culled by `Frustum.intersectsSprite()` and
58    /// sorted by its origin rather than by a geometry bounding sphere.
59    Sprite(Sprite),
60    /// `Light extends Object3D`, one variant per subclass. The renderer reaches
61    /// it through `RenderList.lights`, which `_projectObject()` fills from
62    /// `object.is_light` — set alongside this variant.
63    Light(LightObject),
64    /// `ClippingGroup extends Group` — the planes `_projectObject()` folds
65    /// into the clipping context of everything below it.
66    ClippingGroup(ClippingGroup),
67}
68
69impl fmt::Debug for Payload {
70    /// `Object3D` derives `Debug`; geometries, materials and node graphs do not,
71    /// so a payload prints as its variant.
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        let name = match self {
74            Payload::None => "None",
75            Payload::Mesh(_) => "Mesh",
76            Payload::InstancedMesh(_) => "InstancedMesh",
77            Payload::SkinnedMesh(_) => "SkinnedMesh",
78            Payload::BatchedMesh(_) => "BatchedMesh",
79            Payload::Line(line) => {
80                if line.is_line_segments {
81                    "LineSegments"
82                } else {
83                    "Line"
84                }
85            }
86            Payload::Points(_) => "Points",
87            Payload::Sprite(_) => "Sprite",
88            Payload::Light(_) => "Light",
89            Payload::ClippingGroup(_) => "ClippingGroup",
90        };
91        f.write_str(name)
92    }
93}
94
95impl Payload {
96    /// `object.isMesh` — true for `InstancedMesh` too, exactly as in three.js
97    /// where `InstancedMesh extends Mesh`.
98    pub fn is_mesh(&self) -> bool {
99        matches!(
100            self,
101            Payload::Mesh(_)
102                | Payload::InstancedMesh(_)
103                | Payload::SkinnedMesh(_)
104                | Payload::BatchedMesh(_)
105        )
106    }
107
108    /// `object.isSkinnedMesh`.
109    pub fn is_skinned_mesh(&self) -> bool {
110        matches!(self, Payload::SkinnedMesh(_))
111    }
112
113    /// The `SkinnedMesh` this node is, if it is one.
114    pub fn skinned_mesh(&self) -> Option<&SkinnedMesh> {
115        match self {
116            Payload::SkinnedMesh(skin) => Some(skin),
117            _ => None,
118        }
119    }
120
121    /// The `SkinnedMesh` this node is, mutably, if it is one.
122    pub fn skinned_mesh_mut(&mut self) -> Option<&mut SkinnedMesh> {
123        match self {
124            Payload::SkinnedMesh(skin) => Some(skin),
125            _ => None,
126        }
127    }
128
129    /// `object.isInstancedMesh`.
130    pub fn is_instanced_mesh(&self) -> bool {
131        matches!(self, Payload::InstancedMesh(_))
132    }
133
134    /// `object.isLine` — true for a `LineSegments` too, exactly as in three.js
135    /// where `LineSegments extends Line`.
136    pub fn is_line(&self) -> bool {
137        matches!(self, Payload::Line(_))
138    }
139
140    /// `object.isLineSegments`.
141    pub fn is_line_segments(&self) -> bool {
142        matches!(self, Payload::Line(line) if line.is_line_segments)
143    }
144
145    /// `object.isPoints`.
146    pub fn is_points(&self) -> bool {
147        matches!(self, Payload::Points(_))
148    }
149
150    /// `object.isSprite`.
151    pub fn is_sprite(&self) -> bool {
152        matches!(self, Payload::Sprite(_))
153    }
154
155    /// `object.isClippingGroup`.
156    pub fn is_clipping_group(&self) -> bool {
157        matches!(self, Payload::ClippingGroup(_))
158    }
159
160    /// The `ClippingGroup` this node is, if it is one.
161    pub fn clipping_group(&self) -> Option<&ClippingGroup> {
162        match self {
163            Payload::ClippingGroup(group) => Some(group),
164            _ => None,
165        }
166    }
167
168    /// The `ClippingGroup` this node is, mutably, if it is one.
169    pub fn clipping_group_mut(&mut self) -> Option<&mut ClippingGroup> {
170        match self {
171            Payload::ClippingGroup(group) => Some(group),
172            _ => None,
173        }
174    }
175
176    /// The `Sprite` this node is, if it is one.
177    pub fn sprite(&self) -> Option<&Sprite> {
178        match self {
179            Payload::Sprite(sprite) => Some(sprite),
180            _ => None,
181        }
182    }
183
184    /// The `Sprite` this node is, mutably, if it is one.
185    pub fn sprite_mut(&mut self) -> Option<&mut Sprite> {
186        match self {
187            Payload::Sprite(sprite) => Some(sprite),
188            _ => None,
189        }
190    }
191
192    /// The `Points` this node is, if it is one.
193    pub fn points(&self) -> Option<&Points> {
194        match self {
195            Payload::Points(points) => Some(points),
196            _ => None,
197        }
198    }
199
200    /// The `Points` this node is, mutably, if it is one.
201    pub fn points_mut(&mut self) -> Option<&mut Points> {
202        match self {
203            Payload::Points(points) => Some(points),
204            _ => None,
205        }
206    }
207
208    /// The `Line` this node is, if it is one.
209    pub fn line(&self) -> Option<&Line> {
210        match self {
211            Payload::Line(line) => Some(line),
212            _ => None,
213        }
214    }
215
216    /// The `Line` this node is, mutably, if it is one.
217    pub fn line_mut(&mut self) -> Option<&mut Line> {
218        match self {
219            Payload::Line(line) => Some(line),
220            _ => None,
221        }
222    }
223
224    /// `object.geometry` for anything `_projectObject()`'s
225    /// `isMesh || isLine || isPoints` arm draws, and for its `isSprite` arm.
226    pub fn geometry(&self) -> Option<&Rc<BufferGeometry>> {
227        match self {
228            Payload::Mesh(mesh) => Some(&mesh.geometry),
229            Payload::InstancedMesh(instanced) => Some(&instanced.mesh.geometry),
230            Payload::SkinnedMesh(skin) => Some(&skin.mesh.geometry),
231            Payload::BatchedMesh(batched) => Some(&batched.mesh.geometry),
232            Payload::Line(line) => Some(&line.geometry),
233            Payload::Points(points) => Some(&points.geometry),
234            Payload::Sprite(sprite) => Some(&sprite.geometry),
235            _ => None,
236        }
237    }
238
239    /// `object.material` for the same set. `None` is three.js' "no material of
240    /// its own", which `scene.overrideMaterial` (or `MeshBasicNodeMaterial`'s
241    /// defaults) stands in for.
242    pub fn material(&self) -> Option<&MeshBasicNodeMaterial> {
243        match self {
244            Payload::Mesh(mesh) => mesh.material.as_ref(),
245            Payload::InstancedMesh(instanced) => instanced.mesh.material.as_ref(),
246            Payload::SkinnedMesh(skin) => skin.mesh.material.as_ref(),
247            Payload::BatchedMesh(batched) => batched.mesh.material.as_ref(),
248            Payload::Line(line) => line.material.as_ref(),
249            Payload::Points(points) => points.material.as_ref(),
250            Payload::Sprite(sprite) => Some(&sprite.material),
251            _ => None,
252        }
253    }
254
255    /// `object.material` for writing — what `ReflectorNode.updateBefore()`
256    /// needs to set `material.visible = false` around its own render.
257    pub fn material_mut(&mut self) -> Option<&mut MeshBasicNodeMaterial> {
258        match self {
259            Payload::Mesh(mesh) => mesh.material.as_mut(),
260            Payload::InstancedMesh(instanced) => instanced.mesh.material.as_mut(),
261            Payload::SkinnedMesh(skin) => skin.mesh.material.as_mut(),
262            Payload::BatchedMesh(batched) => batched.mesh.material.as_mut(),
263            Payload::Line(line) => line.material.as_mut(),
264            Payload::Points(points) => points.material.as_mut(),
265            Payload::Sprite(sprite) => Some(&mut sprite.material),
266            _ => None,
267        }
268    }
269
270    /// `object.material` when it is an array (`Array.isArray( material )`):
271    /// the [`Mesh::materials`] of a plain `Mesh`, empty for everything else
272    /// and for a mesh with a single material.
273    pub(crate) fn material_array(&self) -> &[MeshBasicNodeMaterial] {
274        match self {
275            Payload::Mesh(mesh) => &mesh.materials,
276            _ => &[],
277        }
278    }
279
280    /// `Frustum.intersectsObject( object )`' geometry half, for a mesh or a
281    /// line.
282    ///
283    /// three.js' `intersectsObject` reads `object.boundingSphere` when the
284    /// object has one and falls back to `geometry.boundingSphere` otherwise;
285    /// [`InstancedMesh::bounding_sphere`] is that field, and it is the only way
286    /// an instanced draw whose instances are spread out is not culled as a
287    /// point at its own origin.
288    pub(crate) fn bounding_sphere_in(&self, matrix_world: &Matrix4) -> Option<Sphere> {
289        match self {
290            Payload::Line(line) => line.bounding_sphere_in(matrix_world),
291            Payload::Points(points) => points.bounding_sphere_in(matrix_world),
292            // `Sprite.intersectsFrustum( frustum )` is
293            // `frustum.intersectsSprite( this )`, whose sphere is this.
294            Payload::Sprite(sprite) => Some(sprite.bounding_sphere_in(matrix_world)),
295            Payload::InstancedMesh(instanced) => match instanced.bounding_sphere {
296                Some(bounding_sphere) => {
297                    let mut sphere = bounding_sphere;
298                    sphere.apply_matrix4(matrix_world);
299                    Some(sphere)
300                }
301                None => instanced.mesh.bounding_sphere_in(matrix_world),
302            },
303            // `Frustum.intersectsObject` prefers the object's own
304            // `boundingSphere` — `SkinnedMesh.computeBoundingSphere()` puts the
305            // posed skin there — and falls back to the geometry's.
306            Payload::SkinnedMesh(skin) => match skin.bounding_sphere {
307                Some(bounding_sphere) => {
308                    let mut sphere = bounding_sphere;
309                    sphere.apply_matrix4(matrix_world);
310                    Some(sphere)
311                }
312                None => skin.mesh.bounding_sphere_in(matrix_world),
313            },
314            _ => self.mesh()?.bounding_sphere_in(matrix_world),
315        }
316    }
317
318    /// `Mesh.morphTargetInfluences`. A `Line` has the field in three.js too, but
319    /// nothing on the ladder morphs one, so it is always empty here. A
320    /// `SkinnedMesh` keeps its influences behind an `Rc<RefCell<…>>` — the
321    /// animation binding writes into them from outside — so this returns a
322    /// value rather than a borrow.
323    pub fn morph_target_influences(&self) -> Vec<f64> {
324        match self {
325            Payload::SkinnedMesh(skin) => skin.morph_target_influences.borrow().clone(),
326            _ => match self.mesh() {
327                Some(mesh) => mesh.morph_target_influences.clone(),
328                None => Vec::new(),
329            },
330        }
331    }
332
333    /// The `Mesh` half of whichever mesh-ish payload this is.
334    pub fn mesh(&self) -> Option<&Mesh> {
335        match self {
336            Payload::Mesh(mesh) => Some(mesh),
337            Payload::InstancedMesh(instanced) => Some(&instanced.mesh),
338            Payload::SkinnedMesh(skin) => Some(&skin.mesh),
339            Payload::BatchedMesh(batched) => Some(&batched.mesh),
340            _ => None,
341        }
342    }
343
344    /// The `Mesh` half, mutably, of whichever mesh-ish payload this is.
345    pub fn mesh_mut(&mut self) -> Option<&mut Mesh> {
346        match self {
347            Payload::Mesh(mesh) => Some(mesh),
348            Payload::InstancedMesh(instanced) => Some(&mut instanced.mesh),
349            Payload::SkinnedMesh(skin) => Some(&mut skin.mesh),
350            Payload::BatchedMesh(batched) => Some(&mut batched.mesh),
351            _ => None,
352        }
353    }
354
355    /// The light this node is, if it is one.
356    pub fn light(&self) -> Option<&LightObject> {
357        match self {
358            Payload::Light(light) => Some(light),
359            _ => None,
360        }
361    }
362
363    /// The light this node is, mutably, if it is one.
364    pub fn light_mut(&mut self) -> Option<&mut LightObject> {
365        match self {
366            Payload::Light(light) => Some(light),
367            _ => None,
368        }
369    }
370
371    /// `object.isBatchedMesh`.
372    pub fn is_batched_mesh(&self) -> bool {
373        matches!(self, Payload::BatchedMesh(_))
374    }
375
376    /// The `BatchedMesh` this node is, if it is one.
377    pub fn batched_mesh(&self) -> Option<&BatchedMesh> {
378        match self {
379            Payload::BatchedMesh(batched) => Some(batched),
380            _ => None,
381        }
382    }
383
384    /// The `BatchedMesh` this node is, mutably, if it is one.
385    pub fn batched_mesh_mut(&mut self) -> Option<&mut BatchedMesh> {
386        match self {
387            Payload::BatchedMesh(batched) => Some(batched),
388            _ => None,
389        }
390    }
391
392    /// The `InstancedMesh` this node is, if it is one.
393    pub fn instanced_mesh(&self) -> Option<&InstancedMesh> {
394        match self {
395            Payload::InstancedMesh(instanced) => Some(instanced),
396            _ => None,
397        }
398    }
399
400    /// The `InstancedMesh` this node is, mutably, if it is one.
401    pub fn instanced_mesh_mut(&mut self) -> Option<&mut InstancedMesh> {
402        match self {
403            Payload::InstancedMesh(instanced) => Some(instanced),
404            _ => None,
405        }
406    }
407
408    /// `RenderObject.getInstanceCount()` (`RenderObject.js:617-631`): the
409    /// instanced geometry's count, else `object.count` when the object defines
410    /// one, else 1. `Points.count` is the second arm — see [`Points::count`].
411    pub(crate) fn count(&self) -> u32 {
412        match self {
413            Payload::InstancedMesh(instanced) => instanced.count as u32,
414            Payload::Points(points) => points.count.unwrap_or(1) as u32,
415            Payload::Sprite(sprite) => sprite.count as u32,
416            // An instanced geometry's `instanceCount` (a `LineSegments2`'s
417            // segment count) wins over this; the renderer reads it first.
418            Payload::Mesh(mesh) => mesh.count.unwrap_or(1) as u32,
419            _ => 1,
420        }
421    }
422
423    /// `InstancedMesh.instanceMatrix`, `None` for a plain mesh.
424    pub fn instance_matrix(&self) -> Option<&InstancedBufferAttribute> {
425        match self {
426            Payload::InstancedMesh(instanced) => Some(&instanced.instance_matrix),
427            _ => None,
428        }
429    }
430
431    /// `InstancedMesh.instanceColor` — `None` until `setColorAt()` is called,
432    /// and `None` for a plain mesh.
433    pub fn instance_color(&self) -> Option<&InstancedBufferAttribute> {
434        match self {
435            Payload::InstancedMesh(instanced) => instanced.instance_color.as_ref(),
436            _ => None,
437        }
438    }
439}