Skip to main content

three_rs/objects/
batched_mesh.rs

1//! Port of `three.js/src/objects/BatchedMesh.js` — the subset
2//! `webgpu_mesh_batch` exercises: geometry ranges packed into one
3//! `BufferGeometry`, per-instance matrices and colours in `DataTexture`s, the
4//! per-instance frustum cull and the sorted draw list `onBeforeRender()` builds.
5//!
6//! Under `WebGPURenderer` there is no multi-draw and no indirect draw: the
7//! backend walks `_multiDrawStarts` / `_multiDrawCounts` and issues one
8//! ordinary `drawIndexed( count, 1, start / bytesPerElement, 0, i )` per
9//! range, with `firstInstance = i` — the *draw ordinal*, which is what
10//! `@builtin(instance_index)` reads and what `_indirectTexture` maps back to an
11//! instance id. See `docs/rung11-progress.md`.
12
13use std::rc::Rc;
14
15use crate::core::{
16    ArrayKind, BufferAttribute, BufferGeometry, Index, Object3D, ObjectRef, TypedArray,
17};
18use crate::materials::MeshBasicNodeMaterial;
19use crate::math::{Box3, CoordinateSystem, Frustum, Matrix4, Sphere, Vector3};
20use crate::nodes::batch::BatchEntry;
21use crate::objects::{Mesh, Payload};
22use crate::textures::DataTexture;
23
24/// One entry of `_geometryInfo`.
25#[derive(Clone, Debug)]
26pub struct GeometryInfo {
27    /// The first vertex of this geometry's range in the packed buffer.
28    pub vertex_start: usize,
29    /// How many vertices of the geometry were actually written.
30    pub vertex_count: usize,
31    /// How many vertices the range reserves, which may exceed `vertex_count`.
32    pub reserved_vertex_count: usize,
33    /// `-1` when the batch geometry is not indexed.
34    pub index_start: isize,
35    /// How many indices of the geometry were actually written.
36    pub index_count: usize,
37    /// How many indices the range reserves, which may exceed `index_count`.
38    pub reserved_index_count: usize,
39    /// The draw range: `indexStart` / `indexCount` for an indexed batch.
40    pub start: usize,
41    /// The draw range's count.
42    pub count: usize,
43    pub(crate) bounding_box: Option<Box3>,
44    pub(crate) bounding_sphere: Option<Sphere>,
45    pub(crate) active: bool,
46}
47
48/// One entry of `_instanceInfo`.
49#[derive(Clone, Copy, Debug)]
50pub(crate) struct InstanceInfo {
51    pub visible: bool,
52    pub active: bool,
53    pub geometry_index: usize,
54}
55
56/// One entry of `MultiDrawRenderList.list`.
57#[derive(Clone, Copy, Debug)]
58pub struct MultiDrawItem {
59    /// The draw range's start.
60    pub start: usize,
61    /// The draw range's count.
62    pub count: usize,
63    /// The sort depth, camera-space.
64    pub z: f64,
65    /// The instance id this draw item belongs to.
66    pub index: usize,
67}
68
69/// What the page's `sortFunction` reads off `this` and `camera`. three.js calls
70/// the custom sort with `this` bound to the mesh and the camera as the second
71/// argument; the port hands it only the two values any sort on the ladder uses.
72#[derive(Clone, Copy, Debug)]
73pub struct SortContext {
74    /// `camera.far`.
75    pub camera_far: f64,
76    /// `this.material.transparent`, which the page uses as `options.reversed`.
77    pub transparent: bool,
78    /// `this.maxInstanceCount`, the page's `options.aux` length.
79    pub max_instance_count: usize,
80}
81
82/// `BatchedMesh.customSort`.
83pub type CustomSort = Rc<dyn Fn(&mut Vec<MultiDrawItem>, &SortContext)>;
84
85/// One `drawIndexed()` the backend issues for this batch.
86#[derive(Clone, Copy, Debug)]
87#[doc(hidden)]
88pub struct SubDraw {
89    pub first_index: u32,
90    pub index_count: u32,
91    /// `firstInstance` — the draw ordinal, not the instance id.
92    pub first_instance: u32,
93}
94
95/// The camera state `onBeforeRender()` needs.
96#[derive(Clone, Copy, Debug)]
97pub struct BatchCamera {
98    /// `camera.projectionMatrix`.
99    pub projection_matrix: Matrix4,
100    /// `camera.matrixWorldInverse`.
101    pub matrix_world_inverse: Matrix4,
102    /// `camera.matrixWorld`.
103    pub matrix_world: Matrix4,
104    /// `camera.coordinateSystem`.
105    pub coordinate_system: CoordinateSystem,
106    /// `camera.far`.
107    pub far: f64,
108}
109
110/// `BatchedMesh extends Mesh`.
111#[derive(Clone)]
112pub struct BatchedMesh {
113    /// The `Mesh` half: geometry, material and morph state.
114    pub mesh: Mesh,
115    /// `_perObjectFrustumCulled` — whether each instance is culled by its own
116    /// bounding sphere.
117    pub per_object_frustum_culled: bool,
118    /// `_sortObjects` — whether instances are depth-sorted before drawing.
119    pub sort_objects: bool,
120    /// `customSort`, set by [`set_custom_sort`](Self::set_custom_sort).
121    pub custom_sort: Option<CustomSort>,
122
123    instance_info: Vec<InstanceInfo>,
124    geometry_info: Vec<GeometryInfo>,
125
126    next_index_start: usize,
127    next_vertex_start: usize,
128    geometry_count: usize,
129
130    visibility_changed: bool,
131    geometry_initialized: bool,
132
133    max_instance_count: usize,
134    max_vertex_count: usize,
135    max_index_count: usize,
136
137    /// `_multiDrawStarts` — in *bytes*, as three.js keeps them.
138    multi_draw_starts: Vec<i32>,
139    multi_draw_counts: Vec<i32>,
140    multi_draw_count: usize,
141    multi_draw_bytes_per_element: usize,
142
143    /// three.js' module-level `_vector`, reproduced as state because
144    /// `getBoundingBoxAt()` / `getBoundingSphereAt()` overwrite it while they
145    /// lazily compute a geometry's bounds, and `onBeforeRender()`'s sort reads
146    /// it afterwards as if it still held the camera position. See
147    /// `docs/rung11-progress.md`.
148    shared_vector: Vector3,
149
150    matrices_texture: DataTexture,
151    indirect_texture: DataTexture,
152    colors_texture: Option<DataTexture>,
153}
154
155impl BatchedMesh {
156    /// `new BatchedMesh( maxInstanceCount, maxVertexCount, maxIndexCount, material )`,
157    /// as a scene-graph [`ObjectRef`].
158    #[allow(clippy::new_ret_no_self)] // mirrors three.js' constructor, which returns the object the scene holds
159    pub fn new(
160        max_instance_count: usize,
161        max_vertex_count: usize,
162        max_index_count: usize,
163        material: MeshBasicNodeMaterial,
164    ) -> ObjectRef {
165        let mut object = Object3D {
166            object_type: "BatchedMesh",
167            ..Default::default()
168        };
169        object.payload = Payload::BatchedMesh(Box::new(Self {
170            mesh: Mesh {
171                geometry: Rc::new(BufferGeometry::new()),
172                material: Some(material),
173                materials: Vec::new(),
174                morph_target_influences: Vec::new(),
175                line_segments: None,
176                count: None,
177            },
178            per_object_frustum_culled: true,
179            sort_objects: true,
180            custom_sort: None,
181            instance_info: Vec::new(),
182            geometry_info: Vec::new(),
183            next_index_start: 0,
184            next_vertex_start: 0,
185            geometry_count: 0,
186            visibility_changed: true,
187            geometry_initialized: false,
188            max_instance_count,
189            max_vertex_count,
190            max_index_count,
191            multi_draw_starts: vec![0; max_instance_count],
192            multi_draw_counts: vec![0; max_instance_count],
193            multi_draw_count: 0,
194            multi_draw_bytes_per_element: 1,
195            shared_vector: Vector3::ZERO,
196            matrices_texture: init_matrices_texture(max_instance_count),
197            indirect_texture: init_indirect_texture(max_instance_count),
198            colors_texture: None,
199        }));
200        object.into_node()
201    }
202
203    /// `maxInstanceCount`.
204    pub fn max_instance_count(&self) -> usize {
205        self.max_instance_count
206    }
207
208    /// `instanceCount` — the number of active instances.
209    pub fn instance_count(&self) -> usize {
210        self.instance_info.iter().filter(|i| i.active).count()
211    }
212
213    /// The packed geometry every instance draws a range of.
214    pub fn geometry(&self) -> &Rc<BufferGeometry> {
215        &self.mesh.geometry
216    }
217
218    /// `getGeometryRangeAt( geometryId )` — the packed range this geometry
219    /// owns inside the shared `BufferGeometry`.
220    pub fn geometry_range_at(&self, geometry_id: usize) -> Option<&GeometryInfo> {
221        self.geometry_info
222            .get(geometry_id)
223            .filter(|info| info.active)
224    }
225
226    /// The three textures the node system binds.
227    #[doc(hidden)]
228    pub fn batch_entry(&self) -> BatchEntry {
229        BatchEntry {
230            indirect: self.indirect_texture.clone(),
231            matrices: self.matrices_texture.clone(),
232            colors: self.colors_texture.clone(),
233        }
234    }
235
236    /// `_multiDrawCount` sub-ranges as `(firstIndex, indexCount, firstInstance)`
237    /// — `WebGPUBackend.draw()`'s `object.isBatchedMesh` arm, which divides the
238    /// byte start back out by `bytesPerElement`.
239    #[doc(hidden)]
240    pub fn sub_draws(&self) -> Vec<SubDraw> {
241        let bpe = self.multi_draw_bytes_per_element.max(1) as i32;
242        (0..self.multi_draw_count)
243            .map(|i| SubDraw {
244                first_index: (self.multi_draw_starts[i] / bpe) as u32,
245                index_count: self.multi_draw_counts[i] as u32,
246                first_instance: i as u32,
247            })
248            .collect()
249    }
250
251    /// `setCustomSort( func )`.
252    pub fn set_custom_sort(&mut self, func: Option<CustomSort>) -> &mut Self {
253        self.custom_sort = func;
254        self
255    }
256
257    fn init_colors_texture(&mut self) {
258        let size = (self.max_instance_count as f64).sqrt().ceil().max(1.0) as u32;
259        // "4 floats per RGBA pixel initialized to white" — the alpha a
260        // `Color.toArray()` never writes therefore stays 1.
261        self.colors_texture = Some(DataTexture::new_f32(
262            vec![1.0; (size * size * 4) as usize],
263            size,
264            size,
265        ));
266    }
267
268    /// `_initializeGeometry( reference )`.
269    fn initialize_geometry(&mut self, reference: &BufferGeometry) {
270        if self.geometry_initialized {
271            return;
272        }
273        let max_vertex_count = self.max_vertex_count;
274        let max_index_count = self.max_index_count;
275        let geometry = Rc::get_mut(&mut self.mesh.geometry)
276            .expect("three-rs: the batch geometry is shared; add geometries before rendering");
277
278        // "create new attribute buffers to hold the geometry data", each of
279        // the reference's typed-array kind and `normalized`.
280        let names: Vec<(String, usize, ArrayKind, bool)> = reference
281            .attributes()
282            .map(|(name, attr)| {
283                (
284                    name.to_string(),
285                    attr.item_size,
286                    attr.kind(),
287                    attr.normalized,
288                )
289            })
290            .collect();
291        for (name, item_size, kind, normalized) in names {
292            geometry.set_attribute(
293                &name,
294                BufferAttribute::from_typed(
295                    TypedArray::zeros(kind, max_vertex_count * item_size),
296                    item_size,
297                    normalized,
298                ),
299            );
300        }
301
302        if reference.index.is_some() {
303            // "Reserve last u16 index for primitive restart."
304            geometry.set_index_attribute(if max_vertex_count > 65535 {
305                Index::U32(vec![0; max_index_count])
306            } else {
307                Index::U16(vec![0; max_index_count])
308            });
309        }
310
311        self.geometry_initialized = true;
312    }
313
314    /// `_validateGeometry( geometry )`.
315    fn validate_geometry(&self, geometry: &BufferGeometry) {
316        let batch = &self.mesh.geometry;
317        assert_eq!(
318            geometry.index.is_some(),
319            batch.index.is_some(),
320            "THREE.BatchedMesh: All geometries must consistently have \"index\"."
321        );
322        for (name, dst) in batch.attributes() {
323            let src = geometry.get_attribute(name).unwrap_or_else(|| {
324                panic!(
325                    "THREE.BatchedMesh: Added geometry missing \"{name}\". \
326                     All geometries must have consistent attributes."
327                )
328            });
329            assert_eq!(
330                src.item_size, dst.item_size,
331                "THREE.BatchedMesh: All attributes must have a consistent itemSize."
332            );
333        }
334    }
335
336    /// `addGeometry( geometry )` with the default reserved counts.
337    pub fn add_geometry(&mut self, geometry: &BufferGeometry) -> usize {
338        self.initialize_geometry(geometry);
339        self.validate_geometry(geometry);
340
341        let reserved_vertex_count = geometry
342            .position()
343            .expect("three-rs: an added geometry needs a position attribute")
344            .count();
345        let reserved_index_count = geometry.index.as_ref().map(|i| i.count()).unwrap_or(0);
346
347        let info = GeometryInfo {
348            vertex_start: self.next_vertex_start,
349            vertex_count: 0,
350            reserved_vertex_count,
351            index_start: if geometry.index.is_some() {
352                self.next_index_start as isize
353            } else {
354                -1
355            },
356            index_count: 0,
357            reserved_index_count,
358            start: 0,
359            count: 0,
360            bounding_box: None,
361            bounding_sphere: None,
362            active: true,
363        };
364
365        assert!(
366            !(info.index_start != -1
367                && info.index_start as usize + info.reserved_index_count > self.max_index_count
368                || info.vertex_start + info.reserved_vertex_count > self.max_vertex_count),
369            "THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size."
370        );
371
372        let geometry_id = self.geometry_count;
373        self.geometry_count += 1;
374        self.geometry_info.push(info);
375
376        self.set_geometry_at(geometry_id, geometry);
377
378        let info = &self.geometry_info[geometry_id];
379        self.next_index_start = (info.index_start.max(0) as usize) + info.reserved_index_count;
380        self.next_vertex_start = info.vertex_start + info.reserved_vertex_count;
381
382        geometry_id
383    }
384
385    /// `setGeometryAt( geometryId, geometry )`.
386    pub fn set_geometry_at(&mut self, geometry_id: usize, geometry: &BufferGeometry) -> usize {
387        assert!(
388            geometry_id < self.geometry_count,
389            "THREE.BatchedMesh: Maximum geometry count reached."
390        );
391        self.validate_geometry(geometry);
392
393        let info = self.geometry_info[geometry_id].clone();
394        let has_index = self.mesh.geometry.index.is_some();
395        let src_index_count = geometry.index.as_ref().map(|i| i.count()).unwrap_or(0);
396        assert!(
397            !(has_index && src_index_count > info.reserved_index_count
398                || geometry.position().map(|p| p.count()).unwrap_or(0)
399                    > info.reserved_vertex_count),
400            "THREE.BatchedMesh: Reserved space not large enough for provided geometry."
401        );
402
403        let vertex_start = info.vertex_start;
404        let reserved_vertex_count = info.reserved_vertex_count;
405        let vertex_count = geometry
406            .position()
407            .expect("three-rs: an added geometry needs a position attribute")
408            .count();
409
410        {
411            let batch = Rc::get_mut(&mut self.mesh.geometry)
412                .expect("three-rs: the batch geometry is shared; add geometries before rendering");
413
414            let names: Vec<String> = batch.attributes().map(|(n, _)| n.to_string()).collect();
415            for name in names {
416                let src = geometry
417                    .get_attribute(&name)
418                    .expect("three-rs: validate_geometry checked this attribute exists");
419                let item_size = src.item_size;
420                let src_count = src.count();
421                let dst = batch
422                    .get_attribute_mut(&name)
423                    .expect("three-rs: the batch geometry has this attribute");
424                copy_attribute_data(src, dst, vertex_start);
425                // "fill the rest in with zeroes"
426                for i in src_count..reserved_vertex_count {
427                    for c in 0..item_size {
428                        dst.set_component(vertex_start + i, c, 0.0);
429                    }
430                }
431                dst.set_needs_update();
432            }
433        }
434
435        let (start, count) = if has_index {
436            let index_start = info.index_start.max(0) as usize;
437            let reserved_index_count = info.reserved_index_count;
438            let src: Vec<u32> = match geometry.index.as_ref() {
439                Some(Index::U16(v)) => v.iter().map(|&x| x as u32).collect(),
440                Some(Index::U32(v)) => v.clone(),
441                None => Vec::new(),
442            };
443            let batch = Rc::get_mut(&mut self.mesh.geometry)
444                .expect("three-rs: the batch geometry is shared; add geometries before rendering");
445            let write = |dst: &mut dyn FnMut(usize, u32)| {
446                for (i, value) in src.iter().enumerate() {
447                    dst(index_start + i, vertex_start as u32 + value);
448                }
449                for i in src.len()..reserved_index_count {
450                    dst(index_start + i, vertex_start as u32);
451                }
452            };
453            match batch.index.as_mut() {
454                Some(Index::U16(v)) => write(&mut |i, x| v[i] = x as u16),
455                Some(Index::U32(v)) => write(&mut |i, x| v[i] = x),
456                None => {}
457            }
458            (index_start, src.len())
459        } else {
460            (vertex_start, vertex_count)
461        };
462
463        let info = &mut self.geometry_info[geometry_id];
464        info.vertex_count = vertex_count;
465        if has_index {
466            info.index_count = count;
467        }
468        info.start = start;
469        info.count = count;
470        info.bounding_box = None;
471        info.bounding_sphere = None;
472
473        self.visibility_changed = true;
474        geometry_id
475    }
476
477    /// `addInstance( geometryId )`.
478    pub fn add_instance(&mut self, geometry_id: usize) -> usize {
479        assert!(
480            self.instance_info.len() < self.max_instance_count,
481            "THREE.BatchedMesh: Maximum item count reached."
482        );
483        let draw_id = self.instance_info.len();
484        self.instance_info.push(InstanceInfo {
485            visible: true,
486            active: true,
487            geometry_index: geometry_id,
488        });
489
490        let identity = Matrix4::identity().to_array();
491        self.matrices_texture.with_f32_mut(|data| {
492            for (i, v) in identity.iter().enumerate() {
493                data[draw_id * 16 + i] = *v as f32;
494            }
495        });
496
497        if let Some(colors) = &self.colors_texture {
498            colors.with_f32_mut(|data| {
499                data[draw_id * 4] = 1.0;
500                data[draw_id * 4 + 1] = 1.0;
501                data[draw_id * 4 + 2] = 1.0;
502            });
503        }
504
505        self.visibility_changed = true;
506        draw_id
507    }
508
509    /// `setMatrixAt( instanceId, matrix )`.
510    pub fn set_matrix_at(&mut self, instance_id: usize, matrix: &Matrix4) -> &mut Self {
511        let values = matrix.to_array();
512        self.matrices_texture.with_f32_mut(|data| {
513            for (i, v) in values.iter().enumerate() {
514                data[instance_id * 16 + i] = *v as f32;
515            }
516        });
517        self
518    }
519
520    /// `getMatrixAt( instanceId, matrix )`.
521    pub fn matrix_at(&self, instance_id: usize) -> Matrix4 {
522        let values: Vec<f64> = self.matrices_texture.with_f32(|data| {
523            data[instance_id * 16..instance_id * 16 + 16]
524                .iter()
525                .map(|v| *v as f64)
526                .collect()
527        });
528        let mut matrix = Matrix4::identity();
529        matrix.from_array(&values, 0);
530        matrix
531    }
532
533    /// `setColorAt( instanceId, color )`. `Color.toArray()` writes `rgb` only,
534    /// so the alpha stays at the texture's initial 1.
535    pub fn set_color_at(&mut self, instance_id: usize, color: &crate::math::Color) -> &mut Self {
536        if self.colors_texture.is_none() {
537            self.init_colors_texture();
538        }
539        let colors = self
540            .colors_texture
541            .as_ref()
542            .expect("three-rs: the colours texture was just initialised");
543        colors.with_f32_mut(|data| {
544            data[instance_id * 4] = color.r as f32;
545            data[instance_id * 4 + 1] = color.g as f32;
546            data[instance_id * 4 + 2] = color.b as f32;
547        });
548        self
549    }
550
551    /// `getBoundingBoxAt( geometryId, target )` — computed from the packed
552    /// geometry's own index range, so it costs nothing until the first cull.
553    pub fn bounding_box_at(&mut self, geometry_id: usize) -> Option<Box3> {
554        if geometry_id >= self.geometry_count {
555            return None;
556        }
557        if self.geometry_info[geometry_id].bounding_box.is_none() {
558            let info = self.geometry_info[geometry_id].clone();
559            let geometry = &self.mesh.geometry;
560            let position = geometry.position()?;
561            let mut box3 = Box3::default();
562            let mut scratch = Vector3::ZERO;
563            for i in info.start..info.start + info.count {
564                let iv = index_at(geometry, i);
565                // `box.expandByPoint( _vector.fromBufferAttribute( position, iv ) )`
566                scratch = position.get_vector3(iv);
567                box3.expand_by_point(&scratch);
568            }
569            self.shared_vector = scratch;
570            self.geometry_info[geometry_id].bounding_box = Some(box3);
571        }
572        self.geometry_info[geometry_id].bounding_box
573    }
574
575    /// `getBoundingSphereAt( geometryId, target )`.
576    pub fn bounding_sphere_at(&mut self, geometry_id: usize) -> Option<Sphere> {
577        if geometry_id >= self.geometry_count {
578            return None;
579        }
580        if self.geometry_info[geometry_id].bounding_sphere.is_none() {
581            let box3 = self.bounding_box_at(geometry_id)?;
582            let info = self.geometry_info[geometry_id].clone();
583            let center = box3.get_center();
584            let geometry = &self.mesh.geometry;
585            let position = geometry.position()?;
586            let mut max_radius_sq: f64 = 0.0;
587            let mut scratch = Vector3::ZERO;
588            for i in info.start..info.start + info.count {
589                let iv = index_at(geometry, i);
590                // `_vector.fromBufferAttribute( position, iv )`
591                scratch = position.get_vector3(iv);
592                max_radius_sq = max_radius_sq.max(center.distance_to_squared(&scratch));
593            }
594            self.shared_vector = scratch;
595            self.geometry_info[geometry_id].bounding_sphere =
596                Some(Sphere::new(center, max_radius_sq.sqrt()));
597        }
598        self.geometry_info[geometry_id].bounding_sphere
599    }
600
601    /// `BatchedMesh.raycast( raycaster, intersects )` — `Mesh.raycast()` once
602    /// per active, visible instance, over that instance's geometry range with
603    /// its per-geometry bounds and `matrixWorld × instanceMatrix`, each hit
604    /// tagged with its `batchId`.
605    ///
606    /// three.js points a scratch `Mesh` (no morph targets) at the batch
607    /// geometry's attributes for this; the port passes the same pieces to the
608    /// shared mesh raycast directly.
609    pub fn raycast(
610        &mut self,
611        matrix_world: &Matrix4,
612        object: &ObjectRef,
613        raycaster: &crate::core::Raycaster,
614        intersects: &mut Vec<crate::core::Intersection>,
615    ) {
616        let side = self
617            .mesh
618            .material
619            .as_ref()
620            .map_or(crate::materials::Side::Front, |m| m.side);
621        let mut batch_intersects = Vec::new();
622
623        for i in 0..self.instance_info.len() {
624            let info = self.instance_info[i];
625            if !info.visible || !info.active {
626                continue;
627            }
628
629            let geometry_id = info.geometry_index;
630            let (Some(bounding_box), Some(bounding_sphere)) = (
631                self.bounding_box_at(geometry_id),
632                self.bounding_sphere_at(geometry_id),
633            ) else {
634                continue;
635            };
636            let geometry_info = &self.geometry_info[geometry_id];
637
638            // Get the intersects.
639            let mut instance_world_matrix = self.matrix_at(i);
640            instance_world_matrix.premultiply(matrix_world);
641
642            let geometry = &self.mesh.geometry;
643            let target = crate::objects::mesh::MeshRaycast {
644                geometry,
645                side,
646                matrix_world: instance_world_matrix,
647                draw_start: geometry_info.start,
648                draw_count: Some(geometry_info.count),
649                vertex_position: &|index| {
650                    crate::objects::mesh::vertex_position(geometry, &[], index)
651                },
652            };
653            target.raycast(
654                &bounding_sphere,
655                Some(&bounding_box),
656                object,
657                raycaster,
658                &mut batch_intersects,
659            );
660
661            // Add the batch id to the intersects.
662            for mut intersect in batch_intersects.drain(..) {
663                intersect.batch_id = Some(i);
664                intersects.push(intersect);
665            }
666        }
667    }
668
669    /// `_multiDrawCount` after the last `onBeforeRender()`.
670    #[doc(hidden)]
671    pub fn multi_draw_count(&self) -> usize {
672        self.multi_draw_count
673    }
674
675    /// The first `n` entries of `_indirectTexture` — the draw ordinal → instance
676    /// id table, for tests.
677    #[doc(hidden)]
678    pub fn indirect_prefix(&self, n: usize) -> Vec<u32> {
679        self.indirect_texture.with_u32(|data| data[..n].to_vec())
680    }
681
682    /// `onBeforeRender( renderer, scene, camera, geometry, material )`.
683    pub fn on_before_render(&mut self, matrix_world: &Matrix4, camera: &BatchCamera) {
684        if !self.visibility_changed && !self.per_object_frustum_culled && !self.sort_objects {
685            return;
686        }
687
688        // The indexed multi-draw start offset is in bytes.
689        let bytes_per_element = match &self.mesh.geometry.index {
690            Some(Index::U16(_)) => 2,
691            Some(Index::U32(_)) => 4,
692            None => 1,
693        };
694
695        let mut frustum = Frustum::default();
696        if self.per_object_frustum_culled {
697            let mut m = Matrix4::identity();
698            m.multiply_matrices(&camera.projection_matrix, &camera.matrix_world_inverse);
699            m.multiply(matrix_world);
700            frustum.set_from_projection_matrix(&m, camera.coordinate_system, false);
701        }
702
703        let mut multi_draw_count = 0usize;
704
705        if self.sort_objects {
706            // The camera position and forward axis in the batch's local frame.
707            let mut inverse = *matrix_world;
708            inverse.invert();
709            let mut camera_pos = Vector3::ZERO;
710            camera_pos.set_from_matrix_position(&camera.matrix_world);
711            camera_pos.apply_matrix4(&inverse);
712            self.shared_vector = camera_pos;
713            let mut forward = Vector3::new(0.0, 0.0, -1.0);
714            forward.transform_direction(&camera.matrix_world);
715            forward.transform_direction(&inverse);
716
717            let mut list: Vec<MultiDrawItem> = Vec::new();
718            for i in 0..self.instance_info.len() {
719                let info = self.instance_info[i];
720                if !(info.visible && info.active) {
721                    continue;
722                }
723                let geometry_id = info.geometry_index;
724                let matrix = self.matrix_at(i);
725                let mut sphere = match self.bounding_sphere_at(geometry_id) {
726                    Some(sphere) => sphere,
727                    None => continue,
728                };
729                sphere.apply_matrix4(&matrix);
730
731                let culled = self.per_object_frustum_culled && !frustum.intersects_sphere(&sphere);
732                if culled {
733                    continue;
734                }
735                let range = &self.geometry_info[geometry_id];
736                // `_temp.subVectors( _sphere.center, _vector ).dot( _forward )`
737                // — deliberately `_vector`, not the camera position: the
738                // `getBoundingSphereAt()` above overwrites it the first time a
739                // geometry's bounds are computed, so on the frame that fills
740                // the cache the depths are measured from the last vertex of the
741                // last geometry visited. Three does this; the graded frame is
742                // that first frame, so the port does it too.
743                let mut temp = Vector3::ZERO;
744                temp.sub_vectors(&sphere.center, &self.shared_vector);
745                let z = temp.dot(&forward);
746                list.push(MultiDrawItem {
747                    start: range.start,
748                    count: range.count,
749                    z,
750                    index: i,
751                });
752            }
753
754            let transparent = self
755                .mesh
756                .material
757                .as_ref()
758                .map(|m| m.transparent)
759                .unwrap_or(false);
760            match &self.custom_sort {
761                None => {
762                    // `list.sort( material.transparent ? sortTransparent : sortOpaque )`.
763                    if transparent {
764                        list.sort_by(|a, b| b.z.total_cmp(&a.z));
765                    } else {
766                        list.sort_by(|a, b| a.z.total_cmp(&b.z));
767                    }
768                }
769                Some(sort) => {
770                    let sort = sort.clone();
771                    sort(
772                        &mut list,
773                        &SortContext {
774                            camera_far: camera.far,
775                            transparent,
776                            max_instance_count: self.max_instance_count,
777                        },
778                    );
779                }
780            }
781
782            let mut indirect = Vec::with_capacity(list.len());
783            for item in &list {
784                self.multi_draw_starts[multi_draw_count] = (item.start * bytes_per_element) as i32;
785                self.multi_draw_counts[multi_draw_count] = item.count as i32;
786                indirect.push(item.index as u32);
787                multi_draw_count += 1;
788            }
789            self.indirect_texture.with_u32_mut(|data| {
790                for (i, value) in indirect.iter().enumerate() {
791                    data[i] = *value;
792                }
793            });
794        } else {
795            let mut indirect = Vec::new();
796            for i in 0..self.instance_info.len() {
797                let info = self.instance_info[i];
798                if !(info.visible && info.active) {
799                    continue;
800                }
801                let geometry_id = info.geometry_index;
802                let culled = if self.per_object_frustum_culled {
803                    let matrix = self.matrix_at(i);
804                    match self.bounding_sphere_at(geometry_id) {
805                        Some(mut sphere) => {
806                            sphere.apply_matrix4(&matrix);
807                            !frustum.intersects_sphere(&sphere)
808                        }
809                        None => false,
810                    }
811                } else {
812                    false
813                };
814                if culled {
815                    continue;
816                }
817                let range = &self.geometry_info[geometry_id];
818                self.multi_draw_starts[multi_draw_count] = (range.start * bytes_per_element) as i32;
819                self.multi_draw_counts[multi_draw_count] = range.count as i32;
820                indirect.push(i as u32);
821                multi_draw_count += 1;
822            }
823            self.indirect_texture.with_u32_mut(|data| {
824                for (i, value) in indirect.iter().enumerate() {
825                    data[i] = *value;
826                }
827            });
828        }
829
830        self.multi_draw_count = multi_draw_count;
831        self.multi_draw_bytes_per_element = bytes_per_element;
832        self.visibility_changed = false;
833    }
834}
835
836/// `index ? index.getX( i ) : i`.
837fn index_at(geometry: &BufferGeometry, i: usize) -> usize {
838    match &geometry.index {
839        Some(Index::U16(v)) => v[i] as usize,
840        Some(Index::U32(v)) => v[i] as usize,
841        None => i,
842    }
843}
844
845/// `_initMatricesTexture()`: one matrix is four RGBA texels, and the side is
846/// rounded up to a multiple of four so a matrix never straddles two rows.
847fn init_matrices_texture(max_instance_count: usize) -> DataTexture {
848    let mut size = ((max_instance_count * 4) as f64).sqrt();
849    size = (size / 4.0).ceil() * 4.0;
850    let size = (size.max(4.0)) as u32;
851    DataTexture::new_f32(vec![0.0; (size * size * 4) as usize], size, size)
852}
853
854/// `_initIndirectTexture()`.
855fn init_indirect_texture(max_instance_count: usize) -> DataTexture {
856    let size = (max_instance_count as f64).sqrt().ceil().max(1.0) as u32;
857    DataTexture::new_u32(vec![0; (size * size) as usize], size, size)
858}
859
860/// `copyAttributeData( src, target, targetOffset )` from
861/// `BatchedMesh.js`'s utils: a straight typed-array copy when both arrays are
862/// the same kind and `src` is not interleaved, otherwise through the
863/// component getters and setters (which denormalize and renormalize).
864///
865/// "Same kind" is stricter than three's `src.array.constructor !==
866/// target.array.constructor` in one pair: a `Float16BufferAttribute` keeps its
867/// binary16 bits in a `Uint16Array`, so three block-copies an `F16` source
868/// into a `U16` target (and back) bit for bit, where the port's [`ArrayKind`]
869/// tells them apart and copies the decoded values through the getters.
870///
871/// [`ArrayKind`]: crate::core::ArrayKind
872fn copy_attribute_data(src: &BufferAttribute, target: &mut BufferAttribute, target_offset: usize) {
873    let item_size = target.item_size;
874    if src.is_interleaved() || src.kind() != target.kind() {
875        for i in 0..src.count() {
876            for c in 0..item_size {
877                target.set_component(i + target_offset, c, src.get_component(i, c));
878            }
879        }
880    } else {
881        let src = src.data();
882        let mut dst = target.data_mut();
883        for i in 0..src.len() {
884            dst.set(target_offset * item_size + i, src.get(i));
885        }
886    }
887    target.set_needs_update();
888}