Skip to main content

crcbl_render/
cluster_pool.rs

1//! The cluster buffers `mesh_cluster.slang` reads: §3.5's meshlets, resident on
2//! the GPU.
3//!
4//! Four storage buffers and a range per mesh. The **clusters** are
5//! [`crcbl_shaders::meshlet::Meshlet`] records back to back in mesh order; the
6//! **vertex** array is the original vertex indices, one run per cluster; the
7//! **corner** array is `u8` corner indices packed four to a word; and the
8//! **selection** array is one
9//! [`crcbl_shaders::cluster_select::ClusterSelect`] per cluster — the two groups
10//! topic 25's descent tests, and which level of a DAG the cluster's
11//! vertices live in. Every one of those shapes is decided by the record, not
12//! here — see those modules, which are where both sides of the packing are
13//! written.
14//!
15//! # It receives clusters; it does not build them
16//!
17//! Topic 03 §3.5 makes the meshlet build a **bake
18//! step**, and the layering makes it one whether or not it wants to be:
19//! `crcbl_scene::meshlet::build_meshlets` is the builder, `crcbl-scene` pulls in
20//! `gltf`, and a renderer that depended on the glTF importer to describe its own
21//! geometry would have the direction backwards. So a caller hands this module
22//! cooked clusters. [`crcbl_shaders::meshlet::cube_clusters`] and its pyramid
23//! siblings are the cooked form of the meshes the forward pass has resident,
24//! and `crcbl-scene`'s own test is what checks them against the real builder.
25//!
26//! # It is only built on the mesh-shader path
27//!
28//! A device on either indirect tail draws the same geometry out of the index
29//! pool, so nothing reads these buffers and [`crate::forward`] does not create
30//! them. That is why this is a pool of its own rather than three more fields on
31//! [`MeshPool`](crate::mesh_pool::MeshPool): the geometry pools are every
32//! device's, and these are one path's.
33
34use crcbl_hal::{BufferDesc, BufferHandle, BufferUsage, Device, HalError, MemoryLocation};
35use crcbl_shaders::cluster_select::{self, ClusterSelect};
36use crcbl_shaders::meshlet::{self, MeshClusters};
37
38/// Where one mesh's clusters live in [`ClusterPool::clusters`].
39///
40/// The two numbers a bucket's [`ClusterDrawConstants`] block carries, and the
41/// x extent of the dispatch that draws it.
42///
43/// [`ClusterDrawConstants`]: crcbl_shaders::meshlet::ClusterDrawConstants
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
45pub struct ClusterRange {
46    /// This mesh's first cluster.
47    pub base: u32,
48    /// How many clusters it has. Never zero for a mesh with triangles, which is
49    /// what lets the mesh stage read cluster `base` unconditionally.
50    pub count: u32,
51}
52
53/// Several meshes' cluster arrays laid end to end, before any of it is a
54/// buffer.
55///
56/// Separate from [`ClusterPool::new`] so the arithmetic that shifts a mesh's
57/// offsets is testable without a device — which is what a test of it has to be
58/// to be a test at all: the seam takes bytes and hands back a handle, so a pool
59/// that concatenated wrongly uploads exactly as many bytes as one that did not.
60#[derive(Debug, Default, PartialEq)]
61struct Concatenated {
62    clusters: Vec<meshlet::Meshlet>,
63    vertices: Vec<u32>,
64    corners: Vec<u8>,
65    ranges: Vec<ClusterRange>,
66}
67
68/// One mesh's clusters and, if it has a DAG, what each of them needs to descend
69/// it.
70///
71/// A pair rather than a fourth array on [`MeshClusters`], because that type is
72/// the *geometry* — it is what `crcbl_scene::meshlet::build_meshlets` produces
73/// for a mesh with no hierarchy at all — and selection is
74/// `crcbl_shaders::cluster_dag`'s. [`without_lod`](Self::without_lod) is what a
75/// caller with only geometry passes, and it is not a special case downstream:
76/// [`ClusterSelect::ALWAYS`] draws from every camera, so the pool uploads one
77/// record per cluster either way.
78#[derive(Clone, Debug, PartialEq)]
79pub struct PooledMesh {
80    /// The clusters, their vertex runs and their corners.
81    pub clusters: MeshClusters,
82    /// One [`ClusterSelect`] per cluster, parallel to
83    /// [`clusters.clusters`](MeshClusters::clusters).
84    pub selection: Vec<ClusterSelect>,
85}
86
87impl PooledMesh {
88    /// A mesh that is a single level: every cluster drawn whenever the mesh is.
89    #[must_use]
90    pub fn without_lod(clusters: MeshClusters) -> Self {
91        Self {
92            selection: vec![ClusterSelect::ALWAYS; clusters.clusters.len()],
93            clusters,
94        }
95    }
96}
97
98/// Lays `meshes`' three arrays end to end, moving each cluster's offsets by
99/// what came before it.
100///
101/// # Errors
102///
103/// [`HalError::InvalidDescriptor`] when an offset outgrows the `u32` the record
104/// holds, or when `meshes` cluster into nothing.
105fn concatenate(meshes: &[MeshClusters]) -> Result<Concatenated, HalError> {
106    let mut out = Concatenated::default();
107    for mesh in meshes {
108        let base = u32::try_from(out.clusters.len()).map_err(|_| {
109            HalError::InvalidDescriptor(
110                "more clusters than a u32 can name; the record's offsets are 32-bit".to_string(),
111            )
112        })?;
113        // Every offset in this mesh moves by however much came before it.
114        // Rebuilt through `Meshlet::new` rather than added into the existing
115        // fields, because that is the constructor that refuses an offset a
116        // `u32` cannot hold — and a wrapped one would point at the previous
117        // mesh's corners.
118        for cluster in &mesh.clusters {
119            let shifted = meshlet::Meshlet::new(
120                cluster.vertex_offset as usize + out.vertices.len(),
121                cluster.vertex_count as usize,
122                cluster.triangle_offset as usize + out.corners.len(),
123                cluster.triangle_count as usize,
124                cluster.bounds,
125            )
126            .map_err(|error| HalError::InvalidDescriptor(error.to_string()))?;
127            out.clusters.push(shifted);
128        }
129        out.vertices.extend_from_slice(&mesh.vertices);
130        out.corners.extend_from_slice(&mesh.corners);
131        let count = u32::try_from(mesh.clusters.len())
132            .unwrap_or_else(|_| unreachable!("the running total above would have refused first"));
133        out.ranges.push(ClusterRange { base, count });
134    }
135    if out.clusters.is_empty() {
136        return Err(HalError::InvalidDescriptor(
137            "a cluster pool with no clusters has nothing for a mesh stage to read".to_string(),
138        ));
139    }
140    Ok(out)
141}
142
143/// The four cluster buffers, and where each mesh's clusters are in them.
144#[derive(Debug)]
145pub struct ClusterPool {
146    clusters: BufferHandle,
147    vertices: BufferHandle,
148    corners: BufferHandle,
149    selection: BufferHandle,
150    ranges: Vec<ClusterRange>,
151    count: u32,
152}
153
154impl ClusterPool {
155    /// Uploads `meshes`' clusters, concatenated in the order given, and returns
156    /// the pool plus a range per mesh.
157    ///
158    /// The three buffers are `HostUpload` rather than device-local with a
159    /// staging copy, on [`InstancePool`](crate::instance_pool::InstancePool)'s
160    /// terms: they are written once at start-up and read by every frame, and a
161    /// staging copy would buy a transfer submit and a barrier for bytes that
162    /// never change. A bake cache that streams clusters is what would make them
163    /// device-local, and that is §3.5's own later slice.
164    ///
165    /// # Errors
166    ///
167    /// [`HalError`] from any seam call, and
168    /// [`HalError::InvalidDescriptor`] if `meshes` cluster into nothing — a
169    /// pipeline whose cluster buffer is empty has a mesh stage that cannot
170    /// safely read element zero, which is the read its out-of-range path makes.
171    pub fn new(device: &dyn Device, label: &str, meshes: &[PooledMesh]) -> Result<Self, HalError> {
172        let geometry: Vec<MeshClusters> = meshes.iter().map(|mesh| mesh.clusters.clone()).collect();
173        let Concatenated {
174            clusters,
175            vertices,
176            corners,
177            ranges,
178        } = concatenate(&geometry)?;
179
180        // Parallel to the clusters by construction, and refused rather than
181        // padded: a selection array short by one leaves a cluster reading its
182        // neighbour's groups, which is a level chosen wrong rather than a crash.
183        let mut selection = Vec::with_capacity(clusters.len());
184        for mesh in meshes {
185            if mesh.selection.len() != mesh.clusters.clusters.len() {
186                return Err(HalError::InvalidDescriptor(format!(
187                    "a mesh of {} clusters carries {} selection records",
188                    mesh.clusters.clusters.len(),
189                    mesh.selection.len()
190                )));
191            }
192            selection.extend_from_slice(&mesh.selection);
193        }
194
195        let mut created: Vec<BufferHandle> = Vec::with_capacity(4);
196        let mut upload = |name: &str, bytes: &[u8]| -> Result<BufferHandle, HalError> {
197            let buffer = device.create_buffer(&BufferDesc {
198                label: Some(&format!("{label} {name}")),
199                size: bytes.len() as u64,
200                usage: BufferUsage::STORAGE,
201                memory: MemoryLocation::HostUpload,
202            })?;
203            created.push(buffer);
204            device.write_buffer(buffer, 0, bytes)?;
205            Ok(buffer)
206        };
207        // Each `?` can leave the ones before it created, so the whole sequence
208        // is rolled back on the way out rather than leaked — the same shape
209        // every other pool in this crate uses.
210        let built = (|| {
211            let cluster_buffer = upload("clusters", &meshlet::cluster_bytes(&clusters))?;
212            let vertex_bytes: Vec<u8> = vertices.iter().flat_map(|v| v.to_le_bytes()).collect();
213            let vertex_buffer = upload("cluster vertices", &vertex_bytes)?;
214            let corner_buffer = upload("cluster corners", &meshlet::corner_bytes(&corners))?;
215            let selection_buffer = upload(
216                "cluster selection",
217                &cluster_select::selection_bytes(&selection),
218            )?;
219            Ok::<_, HalError>((
220                cluster_buffer,
221                vertex_buffer,
222                corner_buffer,
223                selection_buffer,
224            ))
225        })();
226        let count = u32::try_from(clusters.len())
227            .unwrap_or_else(|_| unreachable!("`concatenate` refused a larger pool first"));
228        match built {
229            Ok((clusters, vertices, corners, selection)) => Ok(Self {
230                clusters,
231                vertices,
232                corners,
233                selection,
234                ranges,
235                count,
236            }),
237            Err(error) => {
238                for buffer in created {
239                    device.destroy_buffer(buffer);
240                }
241                Err(error)
242            }
243        }
244    }
245
246    /// The cluster records, as `mesh_cluster.slang`'s binding 9.
247    #[must_use]
248    pub const fn clusters(&self) -> BufferHandle {
249        self.clusters
250    }
251
252    /// The per-cluster vertex runs, as binding 10.
253    #[must_use]
254    pub const fn vertices(&self) -> BufferHandle {
255        self.vertices
256    }
257
258    /// The packed corner words, as binding 11.
259    #[must_use]
260    pub const fn corners(&self) -> BufferHandle {
261        self.corners
262    }
263
264    /// The per-cluster selection records, as binding 17.
265    #[must_use]
266    pub const fn selection(&self) -> BufferHandle {
267        self.selection
268    }
269
270    /// How many clusters the pool holds in total — the length of the buffer a
271    /// frame records its chosen cut into.
272    #[must_use]
273    pub const fn count(&self) -> u32 {
274        self.count
275    }
276
277    /// Where mesh `index`'s clusters are, in the order [`ClusterPool::new`]
278    /// received them.
279    #[must_use]
280    pub fn range(&self, index: usize) -> Option<ClusterRange> {
281        self.ranges.get(index).copied()
282    }
283
284    /// Releases the four buffers. The device must be idle.
285    pub fn destroy(self, device: &dyn Device) {
286        for buffer in [self.clusters, self.vertices, self.corners, self.selection] {
287            device.destroy_buffer(buffer);
288        }
289    }
290}
291
292// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
293#[cfg(all(test, not(target_arch = "wasm32")))]
294mod tests {
295    use super::*;
296    use crcbl_hal::null::{NullInstance, Recorder};
297    use crcbl_hal::{DeviceDesc, Instance, QueueKind};
298
299    fn open() -> (Recorder, Box<dyn Device>) {
300        let recorder = Recorder::new();
301        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
302        let adapter = instance.adapters().remove(0);
303        let device = instance
304            .create_device(&DeviceDesc::for_adapter(adapter.id))
305            .expect("the null backend always opens");
306        let _ = device.queue(QueueKind::Graphics);
307        (recorder, device)
308    }
309
310    /// **A second mesh's clusters address their own runs.** That is the whole
311    /// job of concatenating three arrays: every offset in the second mesh moves
312    /// by the length of the first's runs, and one that did not would draw the
313    /// first mesh's corners under the second mesh's name — same triangle count,
314    /// same buffer sizes, wrong geometry.
315    ///
316    /// Against [`concatenate`] rather than through a device, because a device
317    /// cannot see it: the seam takes bytes and hands back a handle, so a pool
318    /// that shifted nothing uploads exactly as many bytes as one that did.
319    #[test]
320    fn the_second_mesh_s_clusters_point_past_the_first_s_runs() {
321        let cube = crcbl_shaders::meshlet::cube_clusters();
322        let pyramid = crcbl_shaders::meshlet::pyramid_clusters();
323        let laid_out = concatenate(&[cube.clone(), pyramid.clone()]).expect("both meshes fit");
324
325        assert_eq!(
326            laid_out.ranges,
327            vec![
328                ClusterRange {
329                    base: 0,
330                    count: u32::try_from(cube.clusters.len()).expect("small"),
331                },
332                ClusterRange {
333                    base: u32::try_from(cube.clusters.len()).expect("small"),
334                    count: u32::try_from(pyramid.clusters.len()).expect("small"),
335                },
336            ],
337            "each mesh's clusters start where the last mesh's ended"
338        );
339
340        // The cooked records are mesh-relative — both meshes' first cluster
341        // starts at offset zero — which is what makes the shift observable at
342        // all rather than a no-op that happens to agree.
343        assert_eq!(pyramid.clusters[0].vertex_offset, 0);
344        assert_eq!(pyramid.clusters[0].triangle_offset, 0);
345        assert!(
346            !cube.vertices.is_empty() && !cube.corners.is_empty(),
347            "the first mesh has to have runs for the second one's shift to be \
348             anything but zero"
349        );
350
351        let shifted = laid_out.clusters[cube.clusters.len()];
352        assert_eq!(
353            shifted.vertex_offset,
354            u32::try_from(cube.vertices.len()).expect("small"),
355            "the pyramid's vertex run starts where the cube's ended"
356        );
357        assert_eq!(
358            shifted.triangle_offset,
359            u32::try_from(cube.corners.len()).expect("small"),
360            "and so does its corner run"
361        );
362        assert_eq!(
363            shifted.bounds, pyramid.clusters[0].bounds,
364            "the bounds are carried through unchanged — only the offsets move"
365        );
366        assert_eq!(
367            (laid_out.vertices.len(), laid_out.corners.len()),
368            (
369                cube.vertices.len() + pyramid.vertices.len(),
370                cube.corners.len() + pyramid.corners.len()
371            ),
372            "and both runs hold every entry of both meshes"
373        );
374    }
375
376    /// The pool uploads what [`concatenate`] produced, at the stride the shader
377    /// reads — checked against the writes the recorder saw rather than against
378    /// a host-side copy.
379    #[test]
380    fn the_pool_uploads_every_cluster_of_every_mesh() {
381        let (recorder, device) = open();
382        let cube = crcbl_shaders::meshlet::cube_clusters();
383        let pyramid = crcbl_shaders::meshlet::pyramid_clusters();
384        let pool = ClusterPool::new(
385            device.as_ref(),
386            "test",
387            &[
388                PooledMesh::without_lod(cube.clone()),
389                PooledMesh::without_lod(pyramid.clone()),
390            ],
391        )
392        .expect("the null backend accepts every descriptor");
393
394        assert_eq!(pool.range(2), None, "there is no third mesh");
395        let written = |buffer| {
396            recorder
397                .events()
398                .into_iter()
399                .find_map(|event| match event {
400                    crcbl_hal::null::Event::BufferWritten {
401                        buffer: written,
402                        len,
403                        ..
404                    } if written == buffer => Some(len),
405                    _ => None,
406                })
407                .expect("the buffer was written")
408        };
409        assert_eq!(
410            written(pool.clusters()),
411            (cube.clusters.len() + pyramid.clusters.len()) * crcbl_shaders::meshlet::MESHLET_STRIDE
412        );
413        assert_eq!(
414            written(pool.vertices()),
415            (cube.vertices.len() + pyramid.vertices.len()) * 4
416        );
417        assert_eq!(
418            written(pool.corners()),
419            (cube.corners.len() + pyramid.corners.len()).div_ceil(4) * 4,
420            "corners pack four to a word, tail included"
421        );
422        assert_eq!(
423            written(pool.selection()),
424            (cube.clusters.len() + pyramid.clusters.len())
425                * crcbl_shaders::cluster_select::CLUSTER_SELECT_STRIDE,
426            "one selection record per cluster of every mesh"
427        );
428        assert_eq!(
429            pool.count(),
430            u32::try_from(cube.clusters.len() + pyramid.clusters.len()).expect("small")
431        );
432
433        pool.destroy(device.as_ref());
434        recorder.assert_valid();
435    }
436
437    /// A pool with nothing in it is refused rather than created empty: the mesh
438    /// stage reads cluster `cluster_base` on its out-of-range path, and an
439    /// empty buffer makes that read out of bounds.
440    #[test]
441    fn a_pool_with_no_clusters_is_refused() {
442        let (_, device) = open();
443        let error = ClusterPool::new(device.as_ref(), "test", &[])
444            .expect_err("an empty pool has nothing to draw");
445        assert!(
446            matches!(error, HalError::InvalidDescriptor(ref message) if message.contains("no clusters")),
447            "{error}"
448        );
449    }
450
451    /// Every buffer created is destroyed, which is the leak assertion the rest
452    /// of this crate's pools carry.
453    #[test]
454    fn the_pool_leaks_nothing() {
455        let (recorder, device) = open();
456        let before = recorder.total_live_objects();
457        let pool = ClusterPool::new(
458            device.as_ref(),
459            "test",
460            &[PooledMesh::without_lod(
461                crcbl_shaders::meshlet::cube_clusters(),
462            )],
463        )
464        .expect("built");
465        assert!(recorder.total_live_objects() > before);
466        pool.destroy(device.as_ref());
467        assert_eq!(recorder.total_live_objects(), before);
468        recorder.assert_valid();
469    }
470}