Skip to main content

three_rs/objects/
instanced_mesh.rs

1//! Port of `three.js/src/objects/InstancedMesh.js` +
2//! `src/core/InstancedBufferAttribute.js` (rung 2 subset).
3//!
4//! `InstancedMesh` extends `Mesh` in three.js; here it holds the `Mesh` payload
5//! it extends, and the node's [`Payload`] variant keeps the two apart for the
6//! renderer.
7
8use std::rc::Rc;
9
10use crate::core::{AttributeId, BufferGeometry, Object3D, ObjectRef};
11use crate::materials::MeshBasicNodeMaterial;
12use crate::math::{Color, Matrix4, Sphere};
13use crate::objects::{Mesh, Payload};
14
15/// `new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 )`.
16///
17/// The renderer keeps one GPU buffer per attribute, keyed on [`id`](Self::id),
18/// and writes into it only when [`version`](Self::version) has moved since the
19/// last write, as three.js' `Attributes.update()` does (issue #89).
20///
21/// Unlike three.js, a write through this type bumps the version itself:
22/// [`array_mut`](Self::array_mut) always does, and `setMatrixAt()` /
23/// `setColorAt()` do when the value they write differs from the one there.
24/// three.js needs `attribute.needsUpdate = true` because its `Float32Array` is
25/// mutated behind the attribute's back; here every write goes through the
26/// attribute, so a second call would only add a stale-frame footgun, the same
27/// reasoning as `Texture::set_data` (`docs/api.md`).
28/// [`set_needs_update`](Self::set_needs_update) stays, for forcing a write.
29///
30/// `clone()` mints a fresh id, as a cloned `BufferAttribute` does, and shares
31/// the array until one side writes to it.
32#[derive(Clone)]
33pub struct InstancedBufferAttribute {
34    /// `BufferAttribute.id`, from the same never-reused counter.
35    id: AttributeId,
36    /// The `Float32Array` — `count * item_size` values. Behind an `Rc` so the
37    /// renderer's per-frame snapshot of a draw is a pointer copy rather than a
38    /// copy of the array (eight megabytes at 1 << 17 instance matrices).
39    array: Rc<Vec<f32>>,
40    /// `BufferAttribute.itemSize`.
41    pub item_size: usize,
42    /// `BufferAttribute.version`.
43    version: u32,
44}
45
46impl InstancedBufferAttribute {
47    /// `new InstancedBufferAttribute( array, itemSize )`.
48    pub fn new(array: Vec<f32>, item_size: usize) -> Self {
49        Self {
50            id: AttributeId::default(),
51            array: Rc::new(array),
52            item_size,
53            version: 0,
54        }
55    }
56
57    /// `BufferAttribute.id`. Never reused, and never shared with a clone.
58    pub fn id(&self) -> usize {
59        self.id.get()
60    }
61
62    /// `attribute.array`, for reading.
63    pub fn array(&self) -> &[f32] {
64        &self.array
65    }
66
67    /// `attribute.array`, for writing. Bumps the version, so the next render
68    /// re-writes the GPU buffer: the caller is taken to have changed something.
69    pub fn array_mut(&mut self) -> &mut [f32] {
70        self.version += 1;
71        Rc::make_mut(&mut self.array).as_mut_slice()
72    }
73
74    /// `BufferAttribute.version` — how many times the array has been changed
75    /// or marked changed.
76    pub fn version(&self) -> u32 {
77        self.version
78    }
79
80    /// `attribute.needsUpdate = true` — `version ++`, so the next render
81    /// re-writes the GPU buffer even though nothing was written through
82    /// [`array_mut`](Self::array_mut).
83    pub fn set_needs_update(&mut self) {
84        self.version += 1;
85    }
86
87    /// `BufferAttribute.count` — `array.length / itemSize`.
88    pub fn count(&self) -> usize {
89        self.array.len() / self.item_size
90    }
91
92    /// `values` written at `offset`, and the version bumped only if that
93    /// changed the array: an animation loop that re-sets the matrices it set
94    /// last frame costs no upload.
95    fn write(&mut self, offset: usize, values: &[f32]) {
96        let range = offset..offset + values.len();
97        if self.array[range.clone()] != *values {
98            self.array_mut()[range].copy_from_slice(values);
99        }
100    }
101
102    /// What the renderer reads of this attribute for one frame: the identity
103    /// and version its GPU buffer is cached on, and the array to write.
104    pub(crate) fn snapshot(&self) -> InstanceData {
105        InstanceData {
106            id: self.id(),
107            version: self.version,
108            array: self.array.clone(),
109            item_size: self.item_size,
110        }
111    }
112}
113
114/// An [`InstancedBufferAttribute`] as one frame's draws see it. It keeps the
115/// attribute's id, which a clone of the attribute would not, and holds the
116/// array by `Rc` only until the frame's render list is dropped.
117#[derive(Clone)]
118pub(crate) struct InstanceData {
119    pub id: usize,
120    pub version: u32,
121    pub array: Rc<Vec<f32>>,
122    pub item_size: usize,
123}
124
125impl InstanceData {
126    /// `BufferAttribute.count`.
127    pub fn count(&self) -> usize {
128        self.array.len() / self.item_size
129    }
130}
131
132/// `InstancedMesh extends Mesh`: one geometry and material, drawn `count`
133/// times with a per-instance transform (and optionally colour).
134#[derive(Clone)]
135pub struct InstancedMesh {
136    /// The `Mesh` half: geometry, material and morph state.
137    pub mesh: Mesh,
138    /// `InstancedMesh.count` — the number of instances the renderer draws.
139    pub count: usize,
140    /// `InstancedMesh.instanceMatrix`.
141    pub instance_matrix: InstancedBufferAttribute,
142    /// `InstancedMesh.instanceColor`, `null` until `setColorAt()` is called.
143    pub instance_color: Option<InstancedBufferAttribute>,
144    /// `InstancedMesh.boundingSphere` — the object's *own* bounding sphere, in
145    /// object space, over all of its instances.
146    ///
147    /// `Frustum.intersectsObject` prefers it to the geometry's whenever the
148    /// object declares one (`object.boundingSphere !== undefined` in three.js),
149    /// which is the only thing that keeps an instanced draw whose instances are
150    /// spread out from being culled as a point at the object's origin.
151    /// `None` is three.js' `null`: nothing has computed it yet, so the
152    /// geometry's sphere is used instead.
153    pub bounding_sphere: Option<Sphere>,
154}
155
156impl InstancedMesh {
157    /// `new InstancedMesh( geometry, material, count )`, as a scene-graph [`ObjectRef`].
158    #[allow(clippy::new_ret_no_self)] // `new` mirrors three.js's constructor and returns a scene-graph `ObjectRef`, not `Self`; public API, not changing.
159    pub fn new(
160        geometry: Rc<BufferGeometry>,
161        material: MeshBasicNodeMaterial,
162        count: usize,
163    ) -> ObjectRef {
164        let mut object = Object3D {
165            object_type: "InstancedMesh",
166            ..Default::default()
167        };
168        let mut instanced = Self {
169            mesh: Mesh {
170                geometry,
171                material: Some(material),
172                materials: Vec::new(),
173                morph_target_influences: Vec::new(),
174                line_segments: None,
175                count: None,
176            },
177            count,
178            instance_matrix: InstancedBufferAttribute::new(vec![0.0; count * 16], 16),
179            instance_color: None,
180            bounding_sphere: None,
181        };
182        // `for ( let i = 0; i < count; i ++ ) this.setMatrixAt( i, _identity );`
183        // — the constructor's last step. A mesh whose instances are never placed
184        // still draws at the origin, not collapsed to a zero matrix.
185        let identity = Matrix4::identity();
186        for i in 0..count {
187            instanced.set_matrix_at(i, &identity);
188        }
189        object.payload = Payload::InstancedMesh(instanced);
190        object.into_node()
191    }
192
193    /// `InstancedMesh.getMatrixAt( index, matrix )` —
194    /// `matrix.fromArray( this.instanceMatrix.array, index * 16 )`.
195    pub fn matrix_at(&self, index: usize) -> Matrix4 {
196        let offset = index * 16;
197        let mut matrix = Matrix4::identity();
198        for (e, &a) in matrix
199            .elements
200            .iter_mut()
201            .zip(&self.instance_matrix.array()[offset..offset + 16])
202        {
203            *e = a as f64;
204        }
205        matrix
206    }
207
208    /// `InstancedMesh.computeBoundingSphere()` — the geometry's sphere pushed
209    /// through every instance matrix, unioned. `count` instances, not the
210    /// array's capacity, exactly as three.js does.
211    ///
212    /// A geometry with no position attribute has no sphere to spread, so this
213    /// leaves [`InstancedMesh::bounding_sphere`] alone; three.js would throw.
214    pub fn compute_bounding_sphere(&mut self) {
215        let Some(geometry_sphere) = self.mesh.geometry.compute_bounding_sphere() else {
216            return;
217        };
218        let mut bounding_sphere = Sphere::default();
219        bounding_sphere.make_empty();
220
221        for i in 0..self.count {
222            let mut sphere = Sphere::new(geometry_sphere.center, geometry_sphere.radius);
223            sphere.apply_matrix4(&self.matrix_at(i));
224            bounding_sphere.union(&sphere);
225        }
226
227        self.bounding_sphere = Some(bounding_sphere);
228    }
229
230    /// `InstancedMesh.raycast( raycaster, intersects )` — the object's own
231    /// bounding sphere first, then `Mesh.raycast()` once per instance with
232    /// `matrixWorld × instanceMatrix`, each hit tagged with its `instanceId`.
233    ///
234    /// three.js raycasts each instance through a scratch `Mesh` that has no
235    /// `morphTargetInfluences`, so morph targets are ignored here too.
236    pub fn raycast(
237        &mut self,
238        matrix_world: &Matrix4,
239        object: &crate::core::ObjectRef,
240        raycaster: &crate::core::Raycaster,
241        intersects: &mut Vec<crate::core::Intersection>,
242    ) {
243        // Test with the bounding sphere first.
244        if self.bounding_sphere.is_none() {
245            self.compute_bounding_sphere();
246        }
247        let Some(mut sphere) = self.bounding_sphere else {
248            return;
249        };
250        sphere.apply_matrix4(matrix_world);
251        if !raycaster.ray.intersects_sphere(&sphere) {
252            return;
253        }
254
255        let geometry = &self.mesh.geometry;
256        let Some(geometry_sphere) = geometry.compute_bounding_sphere() else {
257            return;
258        };
259        let geometry_sphere = Sphere::new(geometry_sphere.center, geometry_sphere.radius);
260        let side = self
261            .mesh
262            .material
263            .as_ref()
264            .map_or(crate::materials::Side::Front, |m| m.side);
265
266        // Now test each instance.
267        let mut instance_intersects = Vec::new();
268        for instance_id in 0..self.count {
269            // The world matrix of this instance; the mesh represents it alone.
270            let mut instance_world_matrix = Matrix4::identity();
271            instance_world_matrix.multiply_matrices(matrix_world, &self.matrix_at(instance_id));
272
273            let target = crate::objects::mesh::MeshRaycast {
274                geometry,
275                side,
276                matrix_world: instance_world_matrix,
277                draw_start: geometry.draw_range.start,
278                draw_count: geometry.draw_range.count,
279                vertex_position: &|index| {
280                    crate::objects::mesh::vertex_position(geometry, &[], index)
281                },
282            };
283            target.raycast(
284                &geometry_sphere,
285                None,
286                object,
287                raycaster,
288                &mut instance_intersects,
289            );
290
291            for mut intersect in instance_intersects.drain(..) {
292                intersect.instance_id = Some(instance_id);
293                intersects.push(intersect);
294            }
295        }
296    }
297
298    /// `InstancedMesh.setColorAt( index, color )`.
299    ///
300    /// The array is allocated on the first call and **filled with 1**, not 0,
301    /// so an instance that is never given a colour keeps the material's own —
302    /// `new Float32Array( count * 3 ).fill( 1 )` in three.js.
303    ///
304    /// The colour is stored in the working (linear-sRGB) space the `Color`
305    /// already holds; three.js writes `color.toArray()`, which is the same.
306    ///
307    /// Bumps `instanceColor`'s version when the colour differs from the one
308    /// there; see [`InstancedBufferAttribute`] for why no `needsUpdate`.
309    pub fn set_color_at(&mut self, index: usize, color: &Color) {
310        let colors = self.instance_color.get_or_insert_with(|| {
311            InstancedBufferAttribute::new(vec![1.0; self.instance_matrix.count() * 3], 3)
312        });
313        colors.write(index * 3, &[color.r as f32, color.g as f32, color.b as f32]);
314    }
315
316    /// `InstancedMesh.setMatrixAt( index, matrix )` —
317    /// `matrix.toArray( this.instanceMatrix.array, index * 16 )`.
318    ///
319    /// Bumps `instanceMatrix`'s version when the matrix differs from the one
320    /// there; see [`InstancedBufferAttribute`] for why no `needsUpdate`.
321    pub fn set_matrix_at(&mut self, index: usize, matrix: &Matrix4) {
322        self.instance_matrix
323            .write(index * 16, &matrix.to_f32_array());
324    }
325}
326
327/// The array is `count * item_size` floats — sixteen per instance for the
328/// instance matrix. Debug prints its length, as the textures do.
329impl std::fmt::Debug for InstancedBufferAttribute {
330    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
331        f.debug_struct("InstancedBufferAttribute")
332            .field("id", &self.id())
333            .field("array", &format_args!("{} floats", self.array.len()))
334            .field("item_size", &self.item_size)
335            .field("version", &self.version)
336            .finish()
337    }
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343    use crate::geometries::plane_geometry;
344    use crate::objects::Payload;
345
346    /// Two instances ten units either side of the origin: the object's own
347    /// sphere has to span both, where the geometry's spans one unit plane at
348    /// the origin. This is the difference that decides whether a spread-out
349    /// instanced draw survives the frustum cull.
350    #[test]
351    fn compute_bounding_sphere_spans_the_instances() {
352        let node = InstancedMesh::new(
353            Rc::new(plane_geometry(1.0, 1.0, 1, 1)),
354            MeshBasicNodeMaterial::default(),
355            2,
356        );
357
358        let half_diagonal = (0.5f64 * 0.5 + 0.5 * 0.5).sqrt();
359        {
360            let mut object = node.borrow_mut();
361            let instanced = object
362                .payload
363                .instanced_mesh_mut()
364                .expect("InstancedMesh::new makes an InstancedMesh payload");
365            let mut left = Matrix4::identity();
366            left.set_position(-10.0, 0.0, 0.0);
367            let mut right = Matrix4::identity();
368            right.set_position(10.0, 0.0, 0.0);
369            instanced.set_matrix_at(0, &left);
370            instanced.set_matrix_at(1, &right);
371
372            // Before `computeBoundingSphere`, `boundingSphere` is null and the
373            // geometry's sphere stands in — the unit plane at the origin.
374            assert!(instanced.bounding_sphere.is_none());
375
376            instanced.compute_bounding_sphere();
377            let sphere = instanced
378                .bounding_sphere
379                .expect("compute_bounding_sphere sets it for a geometry with positions");
380            assert!(sphere.center.x.abs() < 1e-12);
381            assert!((sphere.radius - (10.0 + half_diagonal)).abs() < 1e-12);
382        }
383
384        // And the payload hands that sphere to the cull, not the geometry's.
385        let object = node.borrow();
386        let sphere = object
387            .payload
388            .bounding_sphere_in(&object.matrix_world)
389            .expect("a plane has a bounding sphere");
390        assert!((sphere.radius - (10.0 + half_diagonal)).abs() < 1e-12);
391
392        // The same payload with no sphere of its own falls back to the
393        // geometry's, as three.js does.
394        let plain = InstancedMesh::new(
395            Rc::new(plane_geometry(1.0, 1.0, 1, 1)),
396            MeshBasicNodeMaterial::default(),
397            2,
398        );
399        let plain = plain.borrow();
400        let Payload::InstancedMesh(instanced) = &plain.payload else {
401            panic!("InstancedMesh::new makes an InstancedMesh payload");
402        };
403        assert!(instanced.bounding_sphere.is_none());
404        let sphere = plain
405            .payload
406            .bounding_sphere_in(&plain.matrix_world)
407            .expect("a plane has a bounding sphere");
408        assert!((sphere.radius - half_diagonal).abs() < 1e-12);
409    }
410}