Skip to main content

crcbl_render/
draw_gen.rs

1//! GPU draw generation: the cull dispatch, the draw-argument dispatch, and the
2//! buffers between them.
3//!
4//! ```text
5//!  begin_frame ──▶ cull params (this frame's frustum)
6//!
7//!  add_passes ──┬─ compute "clear-counters" ──▶ cull stats, draw args,
8//!               │                             counts+mesh args
9//!               │                                        │ graph barrier
10//!               ├─ compute "cull"      instances ──▶ survivors | · | · | ·
11//!               │                                 ──▶ cull stats
12//!               │                                        │ graph barrier
13//!               └─ compute "draw-args"
14//!                    bin      survivors ──▶ · | routes | · | ·
15//!                                       ──▶ draw args, counts+mesh args
16//!                    starts   counts    ──▶ · | · | · | run starts
17//!                    scatter  routes    ──▶ · | · | bucket runs | ·
18//!                                       ──▶ draw args
19//!                                                        │ graph barrier
20//!                        the caller's render pass ◀──────┘  IndirectArgument
21//! ```
22//!
23//! `a | b` is one buffer with regions; the passes below say which is which.
24//!
25//! Topic 03 §3.3, both halves: "compute pass:
26//! frustum cull against instance AABBs → compacted visible instance list →
27//! `draw_indexed_indirect` records + count buffer". The first dispatch is
28//! `cull.slang` and the second is `draw_gen.slang`, with `clear_counters.slang`
29//! ahead of both; **there is not one hand-written barrier here** — the three
30//! passes declare what they touch and [`crate::graph`] computes the
31//! transitions, including the one into [`ResourceState::IndirectArgument`] that
32//! the seam calls the single most important barrier in a GPU-driven frame.
33//!
34//! # Buckets, and why the CPU still records a draw at all
35//!
36//! A draw's instances have to be addressable by the vertex stage, and
37//! `mesh.slang`'s header measures the only number the four shader targets agree
38//! about: `SV_InstanceID`, and only while the draw's first instance is zero. So
39//! the arguments cannot be one per visible instance distinguished by a first
40//! instance — that reaches the shader as the instance index on two targets and
41//! as zero on the other two.
42//!
43//! What they are instead is §3.3's 2026-07-27 correction: **a fixed bucket
44//! table**, one argument structure per bucket, with an instance count the GPU
45//! writes and a contiguous run of surviving instance indices the vertex stage
46//! walks. The caller records one indirect call per bucket — a number decided
47//! when the table is built and independent of what the scene holds, which is the
48//! property the whole stage is for.
49//!
50//! Today a bucket is one resident mesh, because the index range in an argument
51//! structure is per draw and instances of two meshes cannot share one. The
52//! `(material template, permutation, pass)` bucket the correction describes is
53//! the same table with a longer key.
54//!
55//! # The counters a dispatch zeroes, and why it is a dispatch
56//!
57//! Both shaders only ever *add*: the cull pass's survivor counter, each bucket's
58//! instance count and the y extent of its mesh dispatch are atomics, and an
59//! argument buffer left holding last frame's totals would draw last frame's
60//! scene twice over. Something has to zero them.
61//!
62//! The run starts and the routes are **not** among them, and need not be: the
63//! draw-argument pass writes every start and every route it later reads in the
64//! same frame, before it reads them. Only a counter reads what it adds to.
65//!
66//! The seam has a fill for exactly this — `CommandEncoder::fill_buffer`, "the
67//! idiomatic way to zero an indirect count buffer" — and it is unusable here
68//! twice over. A fill is legal only *outside* a pass, and a render-graph frame
69//! is passes end to end; and `crcbl-dx12` refuses one outright — a deliberate
70//! non-fix argued at its `fill_buffer`, D3D12's fill being
71//! `ClearUnorderedAccessViewUint` over a descriptor from a shader-visible heap.
72//! The first reason is the one that binds here regardless of what any backend
73//! decides: a frame of passes has nowhere to put a fill.
74//!
75//! So the zero is a dispatch of its own, `clear_counters.slang`, scheduled
76//! ahead of the cull pass by [`DrawGen::add_passes`] like any other producer —
77//! and the barrier between its write and the cull pass's first atomic is the
78//! graph's, computed from what the two declare. Every backend that can run the
79//! two passes this zeroes for can run this one, which a fill is not true of.
80//!
81//! **Every buffer here a shader writes is therefore
82//! [`MemoryLocation::DeviceLocal`]**, which is not a tidiness point: D3D12 has
83//! no unordered-access view of an upload-heap resource at all — the flag is
84//! rejected at creation and the heap pins the resource to `GENERIC_READ` for
85//! its lifetime — so the counters being host-visible and bound writable is what
86//! took its device down. That rule is about the *binding*, not the frequency:
87//! topic 25's hysteresis state is written once a frame by
88//! `draw_gen.slang` and is device-local for the same reason the counters are,
89//! even though nothing zeroes it per frame. What does zero it is a start-up
90//! copy, on [`crate::mesh_pool`]'s and [`crate::texture`]'s terms — see
91//! [`DrawGen::group_state`] for why zeroing it twice would be worse than not
92//! zeroing it at all. Read-only bindings are untouched by any of this, and the
93//! tables beside it stay host-visible.
94//!
95//! The ones the clearing pass owns carry [`BufferUsage::TRANSFER_DST`] as well
96//! as `TRANSFER_SRC`, and for the same reason: a buffer only ever written by a
97//! shader is one nothing can poison, and a test that cannot poison a counter
98//! cannot tell a zero this pass wrote from the zero the allocation came with.
99//! `crcbl-vk`'s `draw_gen` end-to-end fills them with a sentinel before the
100//! frame.
101//!
102//! # The overflow is visible, and it is not silent
103//!
104//! `cull.slang`'s counter is the *true* survivor count and can exceed the
105//! visible list's capacity; `draw_gen.slang` clamps before it indexes anything
106//! and generates draws for the prefix that fit. [`DrawGen::visible_capacity`] is
107//! what a caller sizes against, and the counter is where a scene that outgrew it
108//! says so.
109//!
110//! # The runs share one region, so a run's start is decided per frame
111//!
112//! **A bucket's run is not a region of its own.** Every bucket used to reserve a
113//! whole [`DrawGenDesc::instance_capacity`] of `u32`, which can never overflow
114//! and made the survivors-and-runs buffer `capacity * (1 + buckets)` words — per
115//! frame in flight, per generator, and a renderer holds a generator per camera,
116//! cascade, shadow light slot and secondary view. In a game scene of 17219
117//! instances and 938 buckets that was 61.7 MiB a buffer and about 864 MiB a
118//! renderer, and it ran a 2 GiB device out of memory.
119//!
120//! A survivor lands in exactly one bucket, so the runs between them hold what the
121//! survivor list does, and the buffer is now **one capacity of runs** beside the
122//! list — plus a capacity of routes and a word per bucket, for the reasons below.
123//! [`draw_gen::runs_at`] has the table, and [`draw_gen::runs_words`] is the size;
124//! `tests::the_measured_scene_pays_a_word_per_bucket_rather_than_a_capacity`
125//! works the same scene through both formulas.
126//!
127//! What that costs is that where a run starts depends on how many survivors the
128//! buckets in front of it took, which the GPU learns only once every survivor is
129//! counted. So `draw_gen.slang` is three entry points dispatched in turn inside
130//! the one `draw-args` pass — route and count each survivor, prefix-sum the
131//! counts into starts, scatter each survivor at its bucket's start — and that
132//! shader's header argues each. The **routes** are the capacity the buffer grew
133//! by: a parallel scatter reads each survivor's bucket while writing the runs,
134//! so the two cannot be one region.
135//!
136//! **And the geometry stages read the start rather than being told it.** The
137//! `DrawConstants` block a draw binds is written once at build, and the draw's
138//! first instance is the one number the four shader targets disagree about, so
139//! neither can carry a per-frame start; the vertex stage's storage bindings are
140//! spent. So the starts are a region of the buffer the stages already read, and
141//! the block names **the word** a bucket's start is in —
142//! [`DrawGen::bucket_start_word`], fixed at build. `mesh.slang`'s header is where
143//! that is argued in full.
144//!
145//! # Buffers here are shared, and the accessors are views rather than allocations
146//!
147//! **The draw-argument pass binds eight storage buffers**, which is what a
148//! WebGPU device guarantees per shader stage — see `shaders/draw_gen.slang`'s
149//! header, which is where the merges and their costs are argued. It bound
150//! fourteen until 2026-08 and could therefore not be created on a browser at the
151//! default limits, nor on SwiftShader, which is every CI runner without a GPU.
152//!
153//! The consequence for a caller is that several of the accessors below **hand
154//! back the same buffer**:
155//!
156//! * [`DrawGen::visible`] and [`DrawGen::runs`] are one buffer. The survivor
157//!   list is at offset zero, and bucket `b`'s run starts at the word this frame
158//!   wrote into word [`DrawGen::bucket_start_word`]`(b)` of it — an absolute
159//!   word index, so a reader multiplies that by four too.
160//! * [`DrawGen::counts`] and [`DrawGen::mesh_args`] are one buffer. The counts
161//!   are at offset zero and bucket `b`'s dispatch extents at
162//!   [`DrawGen::mesh_args_offset`]`(b)`.
163//! * Every host-written table — the bucket table, its per-bucket material
164//!   modes, the per-bucket cluster counts, topic 25's three
165//!   selection tables and the `(mesh, mode) → bucket` lookup built from the
166//!   first two — is one buffer, packed by
167//!   [`crcbl_shaders::draw_gen::pack_tables`].
168//!
169//! So a reader that copies a region back must take its offset from the accessor
170//! that names it. Reading at zero because a region used to be its own allocation
171//! reads the region in front of it, and the words it finds there are plausible
172//! `u32`s.
173
174use std::sync::Arc;
175use std::sync::atomic::{AtomicU32, Ordering};
176
177use crcbl_hal::{
178    BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
179    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
180    BufferUsage, ComputePipelineDesc, ComputePipelineHandle, Device, HalError, ImageViewType,
181    MemoryLocation, PipelineLayoutDesc, PipelineLayoutHandle, ResourceState, SampleType,
182    ShaderEntry, ShaderModuleDesc, ShaderStages, check_portable_storage_buffers,
183};
184use crcbl_shaders::draw_gen::DrawMode;
185use crcbl_shaders::{
186    CLEAR_COUNTERS, CULL, DRAW_GEN, Stage, clear_counters, cull as cull_shader, draw_gen,
187};
188use glam::Mat4;
189
190use crate::cull::{FacePlanes, Frustum};
191use crate::graph::{BufferId, ImageId, ImportedBuffer, RenderGraph};
192use crate::pipeline_batch;
193use crate::texture::UploadBatch;
194
195// `startsMain` is one workgroup of this size on every device, so it has to fit
196// the smallest workgroup any backend promises.
197const _: () = assert!(
198    draw_gen::STARTS_WORKGROUP_SIZE
199        <= crcbl_hal::Limits::minimum().max_compute_invocations_per_workgroup
200        && draw_gen::STARTS_WORKGROUP_SIZE
201            <= crcbl_hal::Limits::minimum().max_compute_workgroup_size[0]
202);
203
204/// How large a [`DrawGen`] is, and what it draws.
205#[derive(Clone, Copy, Debug)]
206pub struct DrawGenDesc<'a> {
207    /// Debug name; every buffer is named after it.
208    pub label: Option<&'a str>,
209    /// The instance array, one buffer per frame in flight — the ring
210    /// [`crate::instance_pool::InstancePool::buffers`] hands out. Its length is
211    /// how many frames this keeps state for.
212    pub instances: &'a [BufferHandle],
213    /// The mesh table both dispatches resolve ranges and bounds out of.
214    pub mesh_table: BufferHandle,
215    /// Which mesh each bucket draws, as an index into the mesh table, in bucket
216    /// order. One entry per indirect call the caller will record.
217    pub bucket_meshes: &'a [u32],
218    /// Which material **mode** each bucket draws, in the same order — the other
219    /// half of a bucket's routing key.
220    ///
221    /// [`GpuMaterial::mode`](crcbl_shaders::mesh::GpuMaterial::mode) of the rows
222    /// the scene holds, and the scatter sends an instance to the bucket matching
223    /// its mesh *and* the mode its own record carries. So one mesh drawn by an
224    /// opaque material and by a cutout one is two buckets, and the depth prepass
225    /// and the shadow atlas bind a pipeline per bucket instead of one per frame.
226    ///
227    /// The same length as [`bucket_meshes`](Self::bucket_meshes). All zeroes for
228    /// a scene whose materials are all opaque, which is every demo in this tree:
229    /// one bucket per mesh, and the region costs one word each.
230    pub bucket_modes: &'a [u32],
231    /// How many clusters each bucket's mesh has, in the same order — the x
232    /// extent of that bucket's mesh dispatch, and the only word of the
233    /// mesh-dispatch arguments — see [`DrawGen::mesh_args`] — the GPU does not
234    /// decide.
235    ///
236    /// **Zero on every geometry path with no mesh stage**, where nothing reads
237    /// those arguments. It is still the same length as
238    /// [`bucket_meshes`](Self::bucket_meshes): the pass writes one structure
239    /// per bucket whatever the path, exactly as it writes one draw argument
240    /// per bucket.
241    pub bucket_clusters: &'a [u32],
242    /// Where each bucket's mesh's clusters start in the cluster pool, in the
243    /// same order — [`TableOffsets::bucket_cluster_bases_at`]'s region, which
244    /// this pass packs and never reads.
245    ///
246    /// **Zero on every geometry path with no mesh stage**, like
247    /// [`bucket_clusters`](Self::bucket_clusters), and the same length as
248    /// [`bucket_meshes`](Self::bucket_meshes).
249    ///
250    /// [`TableOffsets::bucket_cluster_bases_at`]: draw_gen::TableOffsets::bucket_cluster_bases_at
251    pub bucket_cluster_bases: &'a [u32],
252    /// Where each mesh's cluster DAG is, **indexed by mesh id** — so this is
253    /// parallel to the mesh table and long enough for every id an instance can
254    /// name, not one entry per bucket.
255    ///
256    /// [`MeshLevels::FLAT`](crcbl_shaders::level_select::MeshLevels::FLAT) with
257    /// its `first_level` filled in is what an entry
258    /// for a mesh with no hierarchy holds, and it is also what a caller whose
259    /// geometry path selects per cluster hands over for every mesh — see
260    /// `crcbl_shaders::level_select`, which is where that arrangement is written
261    /// down.
262    pub mesh_levels: &'a [crcbl_shaders::level_select::MeshLevels],
263    /// Every mesh's DAG groups end to end, in the order `mesh_levels` points
264    /// into. Empty where nothing has a hierarchy.
265    pub level_groups: &'a [crcbl_shaders::level_select::LevelGroup],
266    /// Which mesh draws which level: element `first_level + d` of a mesh's run
267    /// is the mesh id of its level `d`.
268    pub level_meshes: &'a [u32],
269    /// Instances the pool this culls can hold.
270    ///
271    /// Sizes the visible list, its routes, and the one run region every bucket
272    /// shares, which is what makes a bucket unable to overflow: at most this
273    /// many instances survive, and they are spread across the buckets rather
274    /// than duplicated into each — see the module docs.
275    ///
276    /// It also sizes topic 25's hysteresis state, which is one word
277    /// per (instance slot, group) — see [`DrawGen::group_state`].
278    pub instance_capacity: u32,
279    /// The [`GpuInstance::flags`](crcbl_shaders::mesh::GpuInstance::flags) bit
280    /// that removes an instance from this cull, written into every frame's cull
281    /// parameters.
282    ///
283    /// One bit of
284    /// [`GpuInstance::HIDDEN_VIEWS_MASK`](crcbl_shaders::mesh::GpuInstance::HIDDEN_VIEWS_MASK)
285    /// for a generator that culls for a camera, and
286    /// [`GpuInstance::CASTS_NO_SHADOW`](crcbl_shaders::mesh::GpuInstance::CASTS_NO_SHADOW)
287    /// for one that culls for no view — a shadow cascade's or a shadowed
288    /// light's — so an instance a camera hides still casts its shadow and one
289    /// told not to cast does not. Zero rejects nothing on it.
290    pub hidden_view: u32,
291    /// The most a frame of this generator may ask for, which decides what it
292    /// allocates: [`DrawMode::Plain`] is region 0 alone, as every generator was;
293    /// [`DrawMode::Occlusion`] adds the two occlusion regions and dispatches the
294    /// occlusion pipelines, which its [`DrawGenPipelines`] must carry;
295    /// [`DrawMode::Faces`] adds six face regions and six capacities of face
296    /// runs.
297    ///
298    /// A frame may always run [`DrawMode::Plain`] instead — see
299    /// [`DrawGen::begin_frame_with`].
300    pub mode: DrawMode,
301    /// How many (cluster, instance slot) pairs one task workgroup of the mesh
302    /// tail decides — [`draw_gen::Params::task_lanes`].
303    ///
304    /// [`TASK_LANES`](crcbl_shaders::meshlet::TASK_LANES) for a caller drawing
305    /// behind `mesh_cluster.slang`'s amplification stage, which then reads
306    /// each bucket's mesh-dispatch extents as
307    /// [`task_extents`](crcbl_shaders::meshlet::task_extents). **Zero for every
308    /// other caller**, including a mesh path with no task stage: its
309    /// `meshMain` launches one workgroup per pair from the
310    /// `(clusters, instances, 1)` extents zero leaves in place.
311    pub task_lanes: u32,
312}
313
314/// [`DrawGen::frame_modes`]' word for a frame that dispatches the occlusion
315/// entry point for its small-feature test alone and scatters plainly — past
316/// every [`DrawMode`] word.
317const SMALL_FEATURE_ONLY: u32 = 3;
318
319/// The eye and the budgets a frame's level of detail is selected under — the two
320/// numbers [`DrawGen::begin_frame`] takes beside the frustum, as one value for
321/// [`DrawGen::begin_frame_with`].
322#[derive(Clone, Copy, Debug, PartialEq)]
323pub struct Selection {
324    /// The eye, in world space — [`draw_gen::Params::camera_position`].
325    pub camera_position: [f32; 3],
326    /// Pixels per unit and the two budgets — [`draw_gen::Params::lod_params`].
327    pub lod_params: [f32; 3],
328}
329
330/// What one frame's cull does beyond the frustum — handed to
331/// [`DrawGen::begin_frame_with`].
332#[derive(Clone, Copy, Debug)]
333pub enum FrameCull<'a> {
334    /// The frustum and nothing else, into region 0.
335    Plain,
336    /// A point light's cull: the frustum is the light's box, and each survivor
337    /// is tagged with the faces whose side planes it reaches and scattered into
338    /// each of those faces' regions. Needs a [`DrawMode::Faces`] generator.
339    Faces(&'a FacePlanes),
340    /// The camera's two-phase occlusion and small-feature culls. Needs a
341    /// [`DrawMode::Occlusion`] generator.
342    Occlusion(OcclusionFrame),
343}
344
345/// The camera's half of an occlusion frame — see [`FrameCull::Occlusion`].
346#[derive(Clone, Copy, Debug, PartialEq)]
347pub struct OcclusionFrame {
348    /// This frame's world → clip.
349    pub view_projection: Mat4,
350    /// The previous frame's, which the first phase reprojects through.
351    pub previous_view_projection: Mat4,
352    /// The depth prepass's extent, which is level 0 of the pyramid.
353    pub target: (u32, u32),
354    /// Levels of the farthest-depth pyramid, from
355    /// [`occlusion_cull::levels_for`](crate::occlusion_cull::levels_for).
356    pub pyramid_levels: u32,
357    /// Whether the two phases run at all. With this off the frame is
358    /// [`DrawMode::Plain`] and only the small-feature test is added.
359    pub occlusion: bool,
360    /// Whether the pyramid holds the previous frame at this extent, so the first
361    /// phase may test against it. Off, every survivor is drawn early.
362    pub history: bool,
363    /// The small-feature threshold in pixels, or `None` where it is off.
364    pub small_feature_pixels: Option<f32>,
365}
366
367/// The farthest-depth pyramid a frame's occlusion passes read — see
368/// [`DrawGen::add_occlusion_passes`].
369#[derive(Clone, Copy, Debug)]
370pub struct PyramidInputs<'p> {
371    /// Every distinct level image, as the graph knows it, so the two culls can
372    /// declare their reads and the reduction passes their writes.
373    pub levels: &'p [ImageId],
374    /// The group naming those images at the slots `cull.slang` declares in set
375    /// 1, built against [`DrawGen::occlusion_layout`].
376    pub group: BindGroupHandle,
377}
378
379/// What one frame's generated draws live in.
380///
381/// Returned by [`DrawGen::add_passes`] and consumed by the caller's render
382/// pass, which needs both halves: the [`BufferId`]s to declare its reads with,
383/// so the graph transitions them, and the handles to name in the indirect call
384/// itself.
385#[derive(Clone, Copy, Debug)]
386pub struct GeneratedDraws {
387    /// The indirect arguments, [`draw_gen::DRAW_ARGS_SIZE`] bytes per bucket.
388    ///
389    /// **A buffer of its own**, unlike the counts and dispatch extents below,
390    /// and for the one reason that survives the storage-buffer squeeze the module
391    /// docs describe: the mesh path reads these as a shader read in the same pass
392    /// that executes those as indirect arguments, and a resource is in one state
393    /// at a time.
394    pub args: BufferHandle,
395    /// The same buffer as the graph knows it. Declare it in
396    /// [`ResourceState::IndirectArgument`], or as a shader read on the mesh path.
397    pub args_id: BufferId,
398    /// The per-bucket draw counts **and** the per-bucket mesh-dispatch
399    /// arguments, in that order, in one buffer.
400    ///
401    /// At [`DrawGen::count_offset`]`(b)` is bucket `b`'s `u32` draw count: `1`
402    /// for a bucket with something in it and `0` for one without, which is what
403    /// [`GeometryPath::IndirectCount`](crcbl_hal::GeometryPath::IndirectCount)'s
404    /// call reads. At [`DrawGen::mesh_args_offset`]`(b)` are its
405    /// [`draw_gen::MESH_ARGS_SIZE`] bytes of `(clusters, surviving instances,
406    /// 1)` — or, where [`DrawGenDesc::task_lanes`] is non-zero,
407    /// [`task_extents`](crcbl_shaders::meshlet::task_extents) of those two —
408    /// which is what
409    /// [`CommandEncoder::draw_mesh_tasks_indirect`](crcbl_hal::CommandEncoder::draw_mesh_tasks_indirect)
410    /// reads on
411    /// [`GeometryPath::MeshShader`](crcbl_hal::GeometryPath::MeshShader).
412    ///
413    /// One buffer because no pass reads both: the two indirect tails execute the
414    /// counts and the mesh path executes the extents, so it is in
415    /// [`ResourceState::IndirectArgument`] either way and never in two states at
416    /// once.
417    pub counts: BufferHandle,
418    /// The same buffer as the graph knows it. Declare it in
419    /// [`ResourceState::IndirectArgument`] — **once**, whichever region the
420    /// pass reads.
421    pub counts_id: BufferId,
422    /// Byte offset in [`counts`](Self::counts) of region 0's first flat task
423    /// dispatch: behind every region this generator allocates, one
424    /// [`draw_gen::MESH_ARGS_SIZE`] structure per
425    /// [flat segment](draw_gen::flat_segment) a region, which is where a flat
426    /// call's arguments are — see [`DrawGen::flat_args_offset`]. Per generator
427    /// rather than per renderer, because it sits behind however many regions
428    /// the generator was built with.
429    pub flat_args_offset: u64,
430    /// `cull.slang`'s survivor list, each survivor's route, the per-bucket runs
431    /// of surviving instance indices the vertex stage reads, and where each run
432    /// starts this frame, in that order, in one buffer. Declare it as a shader
433    /// read.
434    ///
435    /// A pass that draws reads only the starts and the runs: bucket `b`'s start
436    /// at word [`DrawGen::bucket_start_word`]`(b)` — which is the number
437    /// [`DrawConstants::start_at`](crcbl_shaders::mesh::DrawConstants::start_at)
438    /// carries — and then the run from the word that start names.
439    pub runs_id: BufferId,
440    /// Topic 25's hysteresis state, as the graph knows it.
441    ///
442    /// Here because a caller whose geometry path has an amplification stage
443    /// **reads** it: `mesh_cluster.slang` looks up the two groups a cluster
444    /// names, so the pass that runs it declares [`ResourceState::ShaderRead`] on
445    /// this id and the graph orders that read after the draw-argument pass's
446    /// write. A caller on a path with no amplification stage declares nothing,
447    /// and the state is then written and read by that pass alone.
448    pub group_state_id: BufferId,
449    /// The frame's culling statistics, as the graph knows them — the buffer
450    /// [`DrawGen::visible_count`] hands out.
451    ///
452    /// Here because §3.5's amplification stage **writes** it: it counts
453    /// surviving clusters into
454    /// [`CLUSTER_SURVIVOR_WORD`](crcbl_shaders::cull::CLUSTER_SURVIVOR_WORD),
455    /// so the pass that runs it declares
456    /// [`ResourceState::ShaderReadWrite`] on this id and the graph orders that
457    /// write after the draw-argument pass's read. A caller on a geometry path
458    /// with no amplification stage declares nothing and the counter keeps the
459    /// zero the clearing pass wrote.
460    pub visible_count_id: BufferId,
461}
462
463/// The cull and draw-argument dispatches, and everything they need.
464#[derive(Debug)]
465pub struct DrawGen {
466    /// Every host-written table `draw_gen.slang` reads, in one buffer: the
467    /// bucket table, the per-bucket cluster counts and topic 25's
468    /// three selection tables.
469    ///
470    /// **Written once**, which is what makes the merge sound rather than merely
471    /// convenient: all five are decided when a mesh becomes resident and none is
472    /// rewritten per frame, so they change together or not at all.
473    /// [`crcbl_shaders::draw_gen::pack_tables`] is what lays them out and
474    /// [`table_offsets`](Self::table_offsets) is where each region starts.
475    tables: BufferHandle,
476    /// Where each region of [`tables`](Self::tables) begins, as the four words
477    /// [`draw_gen::Params`] carries into the shader.
478    table_offsets: draw_gen::TableOffsets,
479    /// The two buffer lengths the clearing dispatch zeroes. Shared by every
480    /// frame's group, because both are fixed when the bucket table is built.
481    clear_params: BufferHandle,
482    /// Topic 25's hysteresis state: one word per (instance slot,
483    /// group), holding whether that instance had that group expanded.
484    ///
485    /// **One buffer, deliberately not a ring**, and `draw_gen.slang`'s own
486    /// declaration is where that is argued: a frame reads what the last frame
487    /// wrote, an instance the frustum rejected writes nothing at all, and a
488    /// per-frame slot would hand such an instance a state that is neither its
489    /// own nor monotone — which is a crack rather than a stale level. Frames are
490    /// ordered against each other by the graph instead, out of the
491    /// `ShaderReadWrite` both the writing and the reading pass declare on it.
492    ///
493    /// Zeroed at build and never again, which is where the monotonicity
494    /// induction starts — by the start-up copy [`DrawGen::new`] records into
495    /// its caller's [`UploadBatch`],
496    /// because a shader writes this and a buffer a shader writes cannot be
497    /// host-visible. A second zero anywhere would erase the history rather than
498    /// establish it, so there is deliberately no per-frame clear of it.
499    group_state: BufferHandle,
500    /// How many groups one instance's run of [`group_state`](Self::group_state)
501    /// holds — every resident mesh's group count summed, and at least one so the
502    /// buffer is never zero-length.
503    group_stride: u32,
504
505    // One per frame in flight, indexed by the caller's frame slot.
506    /// The block naming the bucket count, the two capacities and this frame's
507    /// selection camera.
508    ///
509    /// **Ringed since the uniform cut arrived**, where it used to be one shared
510    /// buffer: the camera and the pixel budget change every frame, and a frame
511    /// still in flight is a frame still reading them.
512    gen_params: Vec<BufferHandle>,
513    cull_params: Vec<BufferHandle>,
514    visible_count: Vec<BufferHandle>,
515    /// `cull.slang`'s survivor list, its routes, the per-bucket runs and their
516    /// starts — see the module docs, and [`DrawGen::bucket_start_word`] for where
517    /// a bucket's start is.
518    runs: Vec<BufferHandle>,
519    args: Vec<BufferHandle>,
520    /// The per-bucket draw counts, then the per-bucket mesh-dispatch extents.
521    counts: Vec<BufferHandle>,
522    clear_groups: Vec<BindGroupHandle>,
523    cull_groups: Vec<BindGroupHandle>,
524    gen_groups: Vec<BindGroupHandle>,
525
526    /// The layouts and pipelines every generator of a renderer shares — this
527    /// one's reference to them, released by [`destroy`](Self::destroy).
528    pipelines: Arc<DrawGenPipelines>,
529
530    bucket_count: u32,
531    capacity: u32,
532    /// Words in each frame's [`runs`](Self::runs) buffer —
533    /// [`draw_gen::runs_words`], checked once at build.
534    runs_words: u32,
535    hidden_view: u32,
536    /// [`DrawGenDesc::task_lanes`], written into every frame's block.
537    task_lanes: u32,
538    /// What [`DrawGenDesc::mode`] built this for.
539    mode: DrawMode,
540    /// `[frame]`: the mode [`DrawGen::begin_frame_with`] last wrote, as its
541    /// word, so the passes a frame records cannot disagree with the block its
542    /// dispatches read.
543    frame_modes: Vec<AtomicU32>,
544}
545
546/// The two occlusion phases' cull pipelines and the late draw-argument ones.
547#[derive(Debug)]
548struct OcclusionPipelines {
549    /// Set 1 of the cull layout: the farthest-depth pyramid's levels.
550    pyramid_layout: BindGroupLayoutHandle,
551    /// The cull's set 0 and the pyramid's set 1.
552    cull_pipeline_layout: PipelineLayoutHandle,
553    early: ComputePipelineHandle,
554    late: ComputePipelineHandle,
555    late_scatter: ComputePipelineHandle,
556    late_finish: ComputePipelineHandle,
557}
558
559/// The layouts and compute pipelines a [`DrawGen`] dispatches, built once and
560/// shared by every generator a renderer makes.
561///
562/// **None of it depends on a [`DrawGenDesc`]**: the bind-group layouts and
563/// their pipeline layouts are fixed by the shaders' declarations, and every
564/// pipeline is one fixed entry point and workgroup size of `clear_counters`,
565/// `cull` or `draw_gen`. What differs between a camera's generator and a shadow
566/// cascade's — buffers, bind groups, bucket tables, the mode — is the
567/// generator's own. So one set serves them all, and building it once instead
568/// of once per generator is the saving: measured cold on radv in 2026-10, a
569/// set was about 13 ms of driver compile.
570///
571/// **Shared by reference count.** [`DrawGen::new`] keeps an [`Arc`] of it and
572/// [`DrawGen::destroy`] gives that back through [`release`](Self::release),
573/// which destroys the set only when it was the last reference — so it cannot be
574/// destroyed while a generator still dispatches it, nor twice.
575///
576/// **Dropping an [`Arc`] of it is not releasing it.** The handles are the
577/// device's, not Rust's: a holder whose `Arc` is dropped without
578/// [`release`](Self::release) leaks every layout and pipeline in the set if it
579/// was the last holder, exactly as a [`DrawGen`] dropped without `destroy`
580/// leaks its buffers.
581#[derive(Debug)]
582pub struct DrawGenPipelines {
583    clear_layout: BindGroupLayoutHandle,
584    clear_pipeline_layout: PipelineLayoutHandle,
585    clear_pipeline: ComputePipelineHandle,
586    cull_layout: BindGroupLayoutHandle,
587    cull_pipeline_layout: PipelineLayoutHandle,
588    cull_pipeline: ComputePipelineHandle,
589    gen_layout: BindGroupLayoutHandle,
590    gen_pipeline_layout: PipelineLayoutHandle,
591    /// `draw_gen.slang`'s entry points, in the order the `draw-args` pass
592    /// dispatches them: route and count, prefix-sum the counts into starts,
593    /// scatter. One layout serves them all.
594    bin_pipeline: ComputePipelineHandle,
595    starts_pipeline: ComputePipelineHandle,
596    scatter_pipeline: ComputePipelineHandle,
597    /// The occlusion entry points, where the set was built with them.
598    occlusion: Option<OcclusionPipelines>,
599}
600
601impl DrawGenPipelines {
602    /// Builds every layout and pipeline a generator dispatches — with the
603    /// occlusion phases' too where `occlusion` is set, which a
604    /// [`DrawMode::Occlusion`] generator needs.
605    ///
606    /// The pipelines compile side by side where the device allows it, with
607    /// `service` called between rounds of them — see
608    /// [`ForwardRenderer::with_scene_serviced`](crate::ForwardRenderer::with_scene_serviced).
609    ///
610    /// # Errors
611    ///
612    /// [`HalError`] from any seam call. A failure part-way through releases
613    /// everything already created.
614    pub fn new(
615        device: &dyn Device,
616        occlusion: bool,
617        service: &mut dyn FnMut(),
618    ) -> Result<Arc<Self>, HalError> {
619        let mut rollback = Rollback::default();
620        match Self::build(device, occlusion, service, &mut rollback) {
621            Ok(built) => {
622                rollback.disarm();
623                Ok(Arc::new(built))
624            }
625            Err(error) => {
626                rollback.run(device);
627                Err(error)
628            }
629        }
630    }
631
632    /// Gives back one reference, destroying the set if it was the last.
633    ///
634    /// Every holder — each [`DrawGen`] through its [`destroy`](DrawGen::destroy),
635    /// and whoever built the set — calls this once, in any order, and the set
636    /// is destroyed exactly once, after its last user. The device must be idle
637    /// by then, as for any other `destroy`.
638    ///
639    /// **Every holder must call it**: an `Arc` that is dropped instead takes
640    /// its count down without destroying anything, so if that was the last
641    /// reference the set's layouts and pipelines leak.
642    pub fn release(pipelines: Arc<Self>, device: &dyn Device) {
643        if let Some(pipelines) = Arc::into_inner(pipelines) {
644            pipelines.destroy(device);
645        }
646    }
647
648    /// Whether this set carries the occlusion phases' pipelines.
649    #[must_use]
650    pub const fn has_occlusion(&self) -> bool {
651        self.occlusion.is_some()
652    }
653
654    fn build(
655        device: &dyn Device,
656        occlusion: bool,
657        service: &mut dyn FnMut(),
658        rollback: &mut Rollback,
659    ) -> Result<Self, HalError> {
660        // --- the clearing pass ---
661        let clear_entries = [
662            uniform(0),
663            storage(1, false, UINT_STRIDE),
664            storage(2, false, UINT_STRIDE),
665            // The draw counts and the mesh-dispatch extents, one buffer.
666            storage(3, false, UINT_STRIDE),
667        ];
668        let clear_desc = BindGroupLayoutDesc {
669            label: Some("clear counters"),
670            entries: &clear_entries,
671        };
672        check_portable_storage_buffers(clear_desc.label, &[&clear_desc])?;
673        let clear_layout = device.create_bind_group_layout(&clear_desc)?;
674        rollback.bind_group_layouts.push(clear_layout);
675        let clear_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
676            label: Some("clear counters"),
677            bind_group_layouts: &[clear_layout],
678            push_constants: None,
679        })?;
680        rollback.pipeline_layouts.push(clear_pipeline_layout);
681
682        // --- the cull pass ---
683        //
684        // Binding order is `cull.slang`'s declaration order, which is a rule
685        // rather than a convention: Slang's Metal target hands each resource the
686        // next index in its own table, so a layout that renumbered them would
687        // bind the frustum where the instance array goes. See
688        // `crcbl_shaders`' declaration-order lint.
689        let cull_entries = [
690            uniform(0),
691            // `StructuredBuffer` in the shader, so read-only here: the cull
692            // pass decides what is visible and never edits an instance or a
693            // mesh entry.
694            storage(1, true, crcbl_shaders::mesh::INSTANCE_STRIDE as u32),
695            storage(2, true, crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32),
696            storage(3, false, UINT_STRIDE),
697            storage(4, false, UINT_STRIDE),
698        ];
699        let cull_desc = BindGroupLayoutDesc {
700            label: Some("cull"),
701            entries: &cull_entries,
702        };
703        check_portable_storage_buffers(cull_desc.label, &[&cull_desc])?;
704        let cull_layout = device.create_bind_group_layout(&cull_desc)?;
705        rollback.bind_group_layouts.push(cull_layout);
706        let cull_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
707            label: Some("cull"),
708            bind_group_layouts: &[cull_layout],
709            push_constants: None,
710        })?;
711        rollback.pipeline_layouts.push(cull_pipeline_layout);
712
713        // --- the draw-argument pass ---
714        //
715        // **Eight storage bindings, which is every one a WebGPU device
716        // guarantees.** There is no headroom here: a ninth is a pass that cannot
717        // be created in a browser at the default limits or on SwiftShader, which
718        // is what a CI runner without a GPU has. `check_portable_storage_buffers`
719        // below is what turns a ninth into a failure here rather than into a
720        // pipeline-layout refusal on somebody else's device.
721        let gen_entries = [
722            uniform(0),
723            // The instance array and the mesh table, read only.
724            storage(1, true, crcbl_shaders::mesh::INSTANCE_STRIDE as u32),
725            storage(2, true, crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32),
726            // The culling statistics, read only: this pass clamps against the
727            // survivor count and adds to nothing.
728            storage(3, true, UINT_STRIDE),
729            // Every host-written table in one buffer, read only: the bucket
730            // table, the per-bucket cluster counts and topic 25's
731            // three selection tables were all decided when a mesh became
732            // resident.
733            storage(4, true, UINT_STRIDE),
734            // The survivor list, its routes, the per-bucket runs and their
735            // starts. Writable, and read through the same descriptor — binding
736            // one buffer read-only *and* writable in one group is a usage
737            // conflict on WebGPU.
738            storage(5, false, UINT_STRIDE),
739            // The indirect arguments.
740            storage(6, false, UINT_STRIDE),
741            // The draw counts and the mesh-dispatch extents.
742            storage(7, false, UINT_STRIDE),
743            // The hysteresis state, read *and* written: this pass is the
744            // only writer, and it reads the previous frame's answer out of
745            // the same element it then overwrites.
746            storage(8, false, UINT_STRIDE),
747        ];
748        let gen_desc = BindGroupLayoutDesc {
749            label: Some("draw args"),
750            entries: &gen_entries,
751        };
752        check_portable_storage_buffers(gen_desc.label, &[&gen_desc])?;
753        let gen_layout = device.create_bind_group_layout(&gen_desc)?;
754        rollback.bind_group_layouts.push(gen_layout);
755        let gen_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
756            label: Some("draw args"),
757            bind_group_layouts: &[gen_layout],
758            push_constants: None,
759        })?;
760        rollback.pipeline_layouts.push(gen_pipeline_layout);
761
762        // --- the passes' pipelines, as one batch ---
763        //
764        // Every layout they need exists by now, so they compile side by side
765        // where the device allows it — see [`pipeline_batch`]. Each result
766        // is the rollback's before any error is propagated, so a refusal of one
767        // releases the others.
768        //
769        // `cull` is named rather than resolved: `cull.slang` has an entry point
770        // per occlusion phase beside this one. `bin`, `starts` and `scatter`
771        // are three entry points of one module over one layout, which is why
772        // they are `compute_pipeline_entry` too: the route, the prefix sum and
773        // the scatter share the bucket table's accessors and shaders here have
774        // no `#include`.
775        let draw_args = |label, entry_point, workgroup_size| {
776            compute_pipeline_entry(
777                device,
778                label,
779                &DRAW_GEN,
780                entry_point,
781                gen_pipeline_layout,
782                workgroup_size,
783            )
784        };
785        let results = pipeline_batch::create(
786            device,
787            service,
788            [
789                &|| {
790                    compute_pipeline(
791                        device,
792                        "clear counters",
793                        &CLEAR_COUNTERS,
794                        clear_pipeline_layout,
795                        clear_counters::WORKGROUP_SIZE,
796                    )
797                },
798                &|| {
799                    compute_pipeline_entry(
800                        device,
801                        "cull",
802                        &CULL,
803                        "computeMain",
804                        cull_pipeline_layout,
805                        cull_shader::WORKGROUP_SIZE,
806                    )
807                },
808                &|| draw_args("draw args bin", "binMain", draw_gen::WORKGROUP_SIZE),
809                // One workgroup for the whole prefix sum, dispatched once by
810                // `record_passes`: its invocations split the table into chunks
811                // and scan the chunk totals in workgroup memory.
812                &|| {
813                    draw_args(
814                        "draw args starts",
815                        "startsMain",
816                        draw_gen::STARTS_WORKGROUP_SIZE,
817                    )
818                },
819                &|| draw_args("draw args scatter", "scatterMain", draw_gen::WORKGROUP_SIZE),
820            ],
821        );
822        rollback.pipelines.extend(results.iter().flatten().copied());
823        let [
824            clear_pipeline,
825            cull_pipeline,
826            bin_pipeline,
827            starts_pipeline,
828            scatter_pipeline,
829        ] = results;
830        let clear_pipeline = clear_pipeline?;
831        let cull_pipeline = cull_pipeline?;
832        let bin_pipeline = bin_pipeline?;
833        let starts_pipeline = starts_pipeline?;
834        let scatter_pipeline = scatter_pipeline?;
835
836        // --- the occlusion phases, where they were asked for ---
837        let occlusion = if occlusion {
838            Some(Self::build_occlusion(
839                device,
840                rollback,
841                cull_layout,
842                gen_pipeline_layout,
843                service,
844            )?)
845        } else {
846            None
847        };
848
849        Ok(Self {
850            clear_layout,
851            clear_pipeline_layout,
852            clear_pipeline,
853            cull_layout,
854            cull_pipeline_layout,
855            cull_pipeline,
856            gen_layout,
857            gen_pipeline_layout,
858            bin_pipeline,
859            starts_pipeline,
860            scatter_pipeline,
861            occlusion,
862        })
863    }
864
865    /// The pipelines only an occlusion generator uses: `cull.slang`'s two phases
866    /// over the cull's set 0 and the pyramid's set 1, and `draw_gen.slang`'s late
867    /// scatter and finish over the draw-argument layout.
868    fn build_occlusion(
869        device: &dyn Device,
870        rollback: &mut Rollback,
871        cull_layout: BindGroupLayoutHandle,
872        gen_pipeline_layout: PipelineLayoutHandle,
873        service: &mut dyn FnMut(),
874    ) -> Result<OcclusionPipelines, HalError> {
875        // One depth texture per level, in `cull.slang`'s declaration order —
876        // which is the order Slang's Metal target hands out texture indices in.
877        let entries: Vec<BindGroupLayoutEntry> = (0..cull_shader::OCCLUSION_MAX_LEVELS)
878            .map(|binding| BindGroupLayoutEntry {
879                binding,
880                visibility: ShaderStages::COMPUTE,
881                kind: BindingKind::SampledImage {
882                    view_type: ImageViewType::D2,
883                    // `Depth`, on `crate::hiz`'s terms: `DepthTexture2D` in the
884                    // shader, read with `Load` and never through a sampler.
885                    sample_type: SampleType::Depth,
886                },
887                count: 1,
888                flags: BindingFlags::empty(),
889            })
890            .collect();
891        let pyramid_desc = BindGroupLayoutDesc {
892            label: Some("occlusion pyramid"),
893            entries: &entries,
894        };
895        check_portable_storage_buffers(pyramid_desc.label, &[&pyramid_desc])?;
896        let pyramid_layout = device.create_bind_group_layout(&pyramid_desc)?;
897        rollback.bind_group_layouts.push(pyramid_layout);
898        let cull_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
899            label: Some("occlusion cull"),
900            bind_group_layouts: &[cull_layout, pyramid_layout],
901            push_constants: None,
902        })?;
903        rollback.pipeline_layouts.push(cull_pipeline_layout);
904        // One batch, on the terms `build` gives for its own.
905        let entry = |label, shader, entry_point, layout, workgroup_size| {
906            compute_pipeline_entry(device, label, shader, entry_point, layout, workgroup_size)
907        };
908        let cull = cull_shader::WORKGROUP_SIZE;
909        let results = pipeline_batch::create(
910            device,
911            service,
912            [
913                &|| {
914                    entry(
915                        "occlusion early cull",
916                        &CULL,
917                        "occlusionMain",
918                        cull_pipeline_layout,
919                        cull,
920                    )
921                },
922                &|| {
923                    entry(
924                        "occlusion late cull",
925                        &CULL,
926                        "lateMain",
927                        cull_pipeline_layout,
928                        cull,
929                    )
930                },
931                &|| {
932                    entry(
933                        "draw args late scatter",
934                        &DRAW_GEN,
935                        "lateScatterMain",
936                        gen_pipeline_layout,
937                        draw_gen::WORKGROUP_SIZE,
938                    )
939                },
940                // One workgroup, on `startsMain`'s terms: its invocations split
941                // the buckets into chunks and scan the two closed regions' task
942                // chunks in workgroup memory.
943                &|| {
944                    entry(
945                        "draw args late finish",
946                        &DRAW_GEN,
947                        "lateFinishMain",
948                        gen_pipeline_layout,
949                        draw_gen::STARTS_WORKGROUP_SIZE,
950                    )
951                },
952            ],
953        );
954        rollback.pipelines.extend(results.iter().flatten().copied());
955        let [early, late, late_scatter, late_finish] = results;
956        let (early, late, late_scatter, late_finish) = (early?, late?, late_scatter?, late_finish?);
957        Ok(OcclusionPipelines {
958            pyramid_layout,
959            cull_pipeline_layout,
960            early,
961            late,
962            late_scatter,
963            late_finish,
964        })
965    }
966
967    /// Releases everything, in dependency order. Only [`release`](Self::release)
968    /// calls it, for the last reference.
969    fn destroy(self, device: &dyn Device) {
970        if let Some(occlusion) = self.occlusion {
971            for pipeline in [
972                occlusion.early,
973                occlusion.late,
974                occlusion.late_scatter,
975                occlusion.late_finish,
976            ] {
977                device.destroy_compute_pipeline(pipeline);
978            }
979            device.destroy_pipeline_layout(occlusion.cull_pipeline_layout);
980            device.destroy_bind_group_layout(occlusion.pyramid_layout);
981        }
982        device.destroy_compute_pipeline(self.scatter_pipeline);
983        device.destroy_compute_pipeline(self.starts_pipeline);
984        device.destroy_compute_pipeline(self.bin_pipeline);
985        device.destroy_pipeline_layout(self.gen_pipeline_layout);
986        device.destroy_compute_pipeline(self.cull_pipeline);
987        device.destroy_pipeline_layout(self.cull_pipeline_layout);
988        device.destroy_compute_pipeline(self.clear_pipeline);
989        device.destroy_pipeline_layout(self.clear_pipeline_layout);
990        device.destroy_bind_group_layout(self.gen_layout);
991        device.destroy_bind_group_layout(self.cull_layout);
992        device.destroy_bind_group_layout(self.clear_layout);
993    }
994}
995
996impl DrawGen {
997    /// Builds every bind group per frame and every buffer between the passes,
998    /// against `pipelines` — the layouts and pipelines it dispatches, which it
999    /// keeps a reference to and does not build. One [`DrawGenPipelines`] serves
1000    /// every generator a renderer makes.
1001    ///
1002    /// `uploads` carries the one start-up copy this makes: the one that zeroes
1003    /// the hysteresis state, described on [`group_state`](Self::group_state).
1004    /// It is recorded, not submitted, so **no frame may run these passes until
1005    /// the caller has submitted that batch** — waiting, with
1006    /// [`UploadBatch::submit`], or, with [`UploadBatch::submit_deferred`], to
1007    /// the queue the frames go to. A renderer building several of these
1008    /// submits all of their copies in one submission.
1009    ///
1010    /// # Errors
1011    ///
1012    /// [`HalError`] from any seam call. A failure part-way through releases
1013    /// everything already created, so a caller that gives up leaves nothing
1014    /// behind — and [abandons](UploadBatch::abandon) `uploads`, which by then
1015    /// may hold a copy into a buffer that release destroyed.
1016    ///
1017    /// # Panics
1018    ///
1019    /// If `instances` is empty or `bucket_meshes` is: a ring with no buffers has
1020    /// nothing to bind, and a table with no buckets generates no draws at all.
1021    /// Also if `desc` asks for [`DrawMode::Occlusion`] and `pipelines` was built
1022    /// without the occlusion phases.
1023    pub fn new(
1024        device: &dyn Device,
1025        uploads: &mut UploadBatch<'_>,
1026        pipelines: &Arc<DrawGenPipelines>,
1027        desc: &DrawGenDesc<'_>,
1028    ) -> Result<Self, HalError> {
1029        assert!(
1030            desc.mode != DrawMode::Occlusion || pipelines.has_occlusion(),
1031            "an occlusion generator dispatches the occlusion phases, and these pipelines were \
1032             built without them"
1033        );
1034        assert!(
1035            !desc.instances.is_empty(),
1036            "draw generation needs at least one instance buffer to cull"
1037        );
1038        assert!(
1039            !desc.bucket_meshes.is_empty(),
1040            "draw generation with no buckets would generate no draws"
1041        );
1042        assert_eq!(
1043            desc.bucket_modes.len(),
1044            desc.bucket_meshes.len(),
1045            "one material mode per bucket: a shorter table would key a bucket on a mode that \
1046             belongs to another bucket, or to nothing, and the instances meant for it would \
1047             scatter nowhere and never be drawn"
1048        );
1049        assert_eq!(
1050            desc.bucket_clusters.len(),
1051            desc.bucket_meshes.len(),
1052            "one cluster count per bucket: a shorter table would leave a bucket's mesh dispatch \
1053             reading a cluster count that belongs to another bucket, or to nothing"
1054        );
1055        assert_eq!(
1056            desc.bucket_cluster_bases.len(),
1057            desc.bucket_meshes.len(),
1058            "one cluster base per bucket: a shorter table would leave a range of buckets drawn \
1059             in one call reading a cluster base that belongs to another bucket, or to nothing"
1060        );
1061        let mut rollback = Rollback::default();
1062        match Self::build(device, uploads, pipelines, desc, &mut rollback) {
1063            Ok(built) => Ok(built),
1064            Err(error) => {
1065                uploads.abandon();
1066                rollback.run(device);
1067                Err(error)
1068            }
1069        }
1070    }
1071
1072    fn build(
1073        device: &dyn Device,
1074        uploads: &mut UploadBatch<'_>,
1075        pipelines: &Arc<DrawGenPipelines>,
1076        desc: &DrawGenDesc<'_>,
1077        rollback: &mut Rollback,
1078    ) -> Result<Self, HalError> {
1079        let stem = desc.label.unwrap_or("draw generation");
1080        let bucket_count = u32::try_from(desc.bucket_meshes.len())
1081            .map_err(|_| HalError::InvalidDescriptor("more buckets than a u32".to_string()))?;
1082        let capacity = desc.instance_capacity;
1083        // **The survivor list carries tags above the index**, so a capacity
1084        // reaching them would be instance indices read back as faces or as an
1085        // occlusion verdict.
1086        if capacity > cull_shader::ENTRY_INDEX_MASK + 1 {
1087            return Err(HalError::InvalidDescriptor(format!(
1088                "{capacity} instances do not fit the {} a survivor entry indexes below its tags",
1089                cull_shader::ENTRY_INDEX_MASK + 1
1090            )));
1091        }
1092        let draw_regions = desc.mode.regions();
1093        // Checked here, once, because the shader indexes the whole buffer with a
1094        // `uint` and every accessor below does the same arithmetic unchecked.
1095        let runs_words = draw_gen::runs_words(capacity, bucket_count, desc.mode == DrawMode::Faces)
1096            .ok_or_else(|| {
1097                HalError::InvalidDescriptor(format!(
1098                    "{capacity} instances and {bucket_count} buckets lay out more survivor and run \
1099                 words than a u32 addresses"
1100                ))
1101            })?;
1102
1103        let mut buffer = |label: &str, size: u64, usage, memory| -> Result<_, HalError> {
1104            let handle = device.create_buffer(&BufferDesc {
1105                label: Some(&format!("{stem} {label}")),
1106                size,
1107                usage,
1108                memory,
1109            })?;
1110            rollback.buffers.push(handle);
1111            Ok(handle)
1112        };
1113
1114        // **Every host-written table in one buffer**, because the draw-argument
1115        // pass has eight storage bindings to spend and a WebGPU device
1116        // guarantees no more — see the module docs. They are packed together
1117        // rather than any other set because they are the ones written at build
1118        // and never per frame: the bucket table, its material modes, its cluster
1119        // counts, and topic 25's three selection tables all follow
1120        // residency and nothing else.
1121        //
1122        // `pack_tables` is what pads an empty selection region out to one zeroed
1123        // record, which is the ordinary case for a renderer whose meshes have no
1124        // hierarchy — a mesh's `first_level` names element zero of the level
1125        // region whether it has a DAG or not.
1126        let packed = draw_gen::pack_tables(
1127            desc.bucket_meshes,
1128            desc.bucket_modes,
1129            desc.bucket_clusters,
1130            desc.bucket_cluster_bases,
1131            desc.mesh_levels,
1132            desc.level_groups,
1133            desc.level_meshes,
1134        )
1135        .ok_or_else(|| {
1136            HalError::InvalidDescriptor("more table words than a u32 addresses".to_string())
1137        })?;
1138        let tables = buffer(
1139            "tables",
1140            packed.bytes.len() as u64,
1141            BufferUsage::STORAGE,
1142            MemoryLocation::HostUpload,
1143        )?;
1144        device.write_buffer(tables, 0, &packed.bytes)?;
1145        let table_offsets = packed.offsets;
1146
1147        // Topic 25's hysteresis state. **Zeroed here and by
1148        // nothing else ever again**: `draw_gen.slang` reads an element before it
1149        // writes it, so what the buffer holds on the very first frame is a real
1150        // input, and freshly allocated device memory holds whatever it holds. A
1151        // state that is not monotone up a DAG is a cut with a hole in it, so
1152        // this is the one write that keeps every later frame's induction
1153        // standing.
1154        //
1155        // Device-local like every other buffer a shader writes here, for the
1156        // reason the module docs give: D3D12 has no unordered-access view of an
1157        // upload-heap resource. So the zero arrives by a **start-up staging
1158        // copy** rather than a `write_buffer` — and not by the clearing
1159        // dispatch, which runs inside every frame. Running it twice would erase
1160        // exactly the history this buffer exists to carry, and once is what a
1161        // copy submitted before the first frame is. It joins the caller's
1162        // batch, whose `submit` is that before; `UploadBatch::fill` is where
1163        // the copy and its barriers are.
1164        //
1165        // At least one word per instance even when nothing resident has a
1166        // hierarchy, because a zero-length buffer is not a descriptor any
1167        // backend binds and both shaders index it unconditionally.
1168        let group_stride = u32::try_from(desc.level_groups.len())
1169            .map_err(|_| HalError::InvalidDescriptor("more groups than a u32".to_string()))?
1170            .max(1);
1171        let group_state_bytes = u64::from(capacity) * u64::from(group_stride) * 4;
1172        let group_state = buffer(
1173            "lod group state",
1174            group_state_bytes,
1175            BufferUsage::STORAGE | BufferUsage::TRANSFER_DST,
1176            MemoryLocation::DeviceLocal,
1177        )?;
1178        uploads.fill(
1179            &format!("{stem} lod group state"),
1180            group_state,
1181            &vec![
1182                0u8;
1183                usize::try_from(group_state_bytes).map_err(|_| HalError::InvalidDescriptor(
1184                    format!(
1185                        "the lod group state is {group_state_bytes} bytes, which does not \
1186                             fit this host's address space"
1187                    )
1188                ))?
1189            ],
1190            ResourceState::ShaderReadWrite,
1191        )?;
1192
1193        let clear_params = buffer(
1194            "clear params",
1195            clear_counters::PARAMS_SIZE as u64,
1196            BufferUsage::UNIFORM,
1197            MemoryLocation::HostUpload,
1198        )?;
1199        // The argument buffer's length in words, from the crate that owns the
1200        // argument layout — so the clearing shader never re-declares it. Every
1201        // region's structures, end to end.
1202        let args_words = draw_regions * bucket_count * draw_gen::DRAW_ARGS_WORDS as u32;
1203        // The counts-and-extents buffer's: every region's counts and extents,
1204        // then every region's flat task dispatches.
1205        let counts_words = draw_gen::flat_args_word(bucket_count, draw_regions, draw_regions, 0, 0);
1206        device.write_buffer(
1207            clear_params,
1208            0,
1209            &clear_counters::Params {
1210                args_words,
1211                counts_words: bucket_count,
1212                stats_words: cull_shader::STATS_WORDS,
1213                // Everything behind region 0's counts: its extents, then every
1214                // further region's counts and extents, which alternate, and
1215                // the flat task dispatches behind them all.
1216                mesh_args_words: counts_words - bucket_count,
1217            }
1218            .to_bytes(),
1219        )?;
1220
1221        let frames = desc.instances.len();
1222        let mut gen_params = Vec::with_capacity(frames);
1223        let mut cull_params = Vec::with_capacity(frames);
1224        let mut visible_count = Vec::with_capacity(frames);
1225        let mut runs = Vec::with_capacity(frames);
1226        let mut args = Vec::with_capacity(frames);
1227        let mut counts = Vec::with_capacity(frames);
1228        for frame in 0..frames {
1229            // The static half is written here and the camera half in
1230            // `begin_frame`, so a frame that never called it still names the
1231            // right bucket count rather than reading a zeroed block.
1232            let params = buffer(
1233                &format!("params {frame}"),
1234                draw_gen::PARAMS_SIZE as u64,
1235                BufferUsage::UNIFORM,
1236                MemoryLocation::HostUpload,
1237            )?;
1238            device.write_buffer(
1239                params,
1240                0,
1241                &draw_gen::Params {
1242                    bucket_count,
1243                    visible_capacity: capacity,
1244                    group_stride,
1245                    bucket_modes_at: table_offsets.bucket_modes_at,
1246                    bucket_clusters_at: table_offsets.bucket_clusters_at,
1247                    mesh_levels_at: table_offsets.mesh_levels_at,
1248                    level_groups_at: table_offsets.level_groups_at,
1249                    level_meshes_at: table_offsets.level_meshes_at,
1250                    bucket_lookup_at: table_offsets.bucket_lookup_at,
1251                    task_lanes: desc.task_lanes,
1252                    flat_segments_at: table_offsets.flat_segments_at,
1253                    ..draw_gen::Params::default()
1254                }
1255                .to_bytes(),
1256            )?;
1257            gen_params.push(params);
1258            cull_params.push(buffer(
1259                &format!("cull params {frame}"),
1260                cull_shader::PARAMS_SIZE as u64,
1261                BufferUsage::UNIFORM,
1262                MemoryLocation::HostUpload,
1263            )?);
1264            // `TRANSFER_SRC` on all four, and it is not there for tidiness:
1265            // everything these passes produce is written by a shader and read by
1266            // another, so a copy out is the *only* way anything can check that
1267            // what they produced is what a CPU would have recorded. `crcbl-vk`'s
1268            // `draw_gen` end-to-end does exactly that, and topic 03 §3.6's
1269            // culling-stats ring — the one readback the frame loop is allowed —
1270            // is the counter below.
1271            //
1272            // `TRANSFER_DST` on the three the clearing dispatch owns, so a test
1273            // can poison them — see the module docs. They are device-local like
1274            // everything else here: nothing writes them from the host any more.
1275            //
1276            // **Two words, not one**, and they belong to different passes: the
1277            // cull dispatch counts surviving instances into the first and
1278            // `mesh_cluster.slang`'s amplification stage counts surviving
1279            // clusters into the second. One buffer keeps §3.6's ring at one
1280            // readback — see [`crcbl_shaders::cull::STATS_WORDS`].
1281            visible_count.push(buffer(
1282                &format!("cull stats {frame}"),
1283                u64::from(cull_shader::STATS_WORDS) * 4,
1284                BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC | BufferUsage::TRANSFER_DST,
1285                MemoryLocation::DeviceLocal,
1286            )?);
1287            // The survivor list, its routes, the per-bucket runs and their
1288            // starts, in that order, in one buffer — see the module docs.
1289            // `cull.slang` writes the first `capacity` words and
1290            // `draw_gen.slang` the rest; nothing reads a word of one region
1291            // through another, and the shader is bound the whole buffer once
1292            // because a read-only view of part of it beside a writable view of
1293            // the rest is a usage conflict on WebGPU.
1294            //
1295            // **One capacity of runs however many buckets there are**: a word
1296            // per bucket is all the bucket count still costs here.
1297            runs.push(buffer(
1298                &format!("visible and bucket runs {frame}"),
1299                u64::from(runs_words) * 4,
1300                BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
1301                MemoryLocation::DeviceLocal,
1302            )?);
1303            args.push(buffer(
1304                &format!("draw args {frame}"),
1305                u64::from(draw_regions) * u64::from(bucket_count) * draw_gen::DRAW_ARGS_SIZE as u64,
1306                BufferUsage::STORAGE
1307                    | BufferUsage::INDIRECT
1308                    | BufferUsage::TRANSFER_SRC
1309                    | BufferUsage::TRANSFER_DST,
1310                MemoryLocation::DeviceLocal,
1311            )?);
1312            // The per-bucket draw counts, then the mesh path's dispatch extents
1313            // — one buffer, on the argument buffer's terms exactly: written by
1314            // the same pass, zeroed by the same one, and read by a driver rather
1315            // than by a shader, so `INDIRECT`, and `TRANSFER_SRC` so a test can
1316            // read back what the GPU decided.
1317            //
1318            // Merged because no pass reads both, so the buffer is never in two
1319            // resource states at once — see [`GeneratedDraws::counts`], and the
1320            // module docs on why a binding had to go.
1321            counts.push(buffer(
1322                &format!("draw counts and mesh dispatch args {frame}"),
1323                u64::from(counts_words) * 4,
1324                BufferUsage::STORAGE
1325                    | BufferUsage::INDIRECT
1326                    | BufferUsage::TRANSFER_SRC
1327                    | BufferUsage::TRANSFER_DST,
1328                MemoryLocation::DeviceLocal,
1329            )?);
1330        }
1331
1332        let mut clear_groups = Vec::with_capacity(frames);
1333        let mut cull_groups = Vec::with_capacity(frames);
1334        let mut gen_groups = Vec::with_capacity(frames);
1335        for frame in 0..frames {
1336            let group = device.create_bind_group(&BindGroupDesc {
1337                label: Some("clear counters"),
1338                layout: pipelines.clear_layout,
1339                entries: &[
1340                    bound(0, clear_params),
1341                    bound(1, visible_count[frame]),
1342                    bound(2, args[frame]),
1343                    bound(3, counts[frame]),
1344                ],
1345                variable_count: None,
1346            })?;
1347            rollback.bind_groups.push(group);
1348            clear_groups.push(group);
1349
1350            // **This frame's slot of every ring, not a shared buffer.** Binding
1351            // one buffer here for every group would undo the ring and put a
1352            // frame's writes where the previous frame is still reading.
1353            let group = device.create_bind_group(&BindGroupDesc {
1354                label: Some("cull"),
1355                layout: pipelines.cull_layout,
1356                entries: &[
1357                    bound(0, cull_params[frame]),
1358                    bound(1, desc.instances[frame]),
1359                    bound(2, desc.mesh_table),
1360                    // The survivor list is the front of the buffer whose later
1361                    // regions hold the routes, the runs and their starts; this
1362                    // pass writes only the front and `CullParams::capacity` is
1363                    // what bounds it there.
1364                    bound(3, runs[frame]),
1365                    bound(4, visible_count[frame]),
1366                ],
1367                variable_count: None,
1368            })?;
1369            rollback.bind_groups.push(group);
1370            cull_groups.push(group);
1371
1372            let group = device.create_bind_group(&BindGroupDesc {
1373                label: Some("draw args"),
1374                layout: pipelines.gen_layout,
1375                entries: &[
1376                    bound(0, gen_params[frame]),
1377                    bound(1, desc.instances[frame]),
1378                    bound(2, desc.mesh_table),
1379                    bound(3, visible_count[frame]),
1380                    bound(4, tables),
1381                    bound(5, runs[frame]),
1382                    bound(6, args[frame]),
1383                    bound(7, counts[frame]),
1384                    bound(8, group_state),
1385                ],
1386                variable_count: None,
1387            })?;
1388            rollback.bind_groups.push(group);
1389            gen_groups.push(group);
1390        }
1391
1392        rollback.disarm();
1393        Ok(Self {
1394            tables,
1395            table_offsets,
1396            clear_params,
1397            group_state,
1398            group_stride,
1399            gen_params,
1400            cull_params,
1401            visible_count,
1402            runs,
1403            args,
1404            counts,
1405            clear_groups,
1406            cull_groups,
1407            gen_groups,
1408            pipelines: Arc::clone(pipelines),
1409            bucket_count,
1410            capacity,
1411            runs_words,
1412            hidden_view: desc.hidden_view,
1413            task_lanes: desc.task_lanes,
1414            mode: desc.mode,
1415            frame_modes: (0..frames).map(|_| AtomicU32::new(0)).collect(),
1416        })
1417    }
1418
1419    /// Buckets in the table, which is how many indirect calls a caller records.
1420    #[must_use]
1421    pub const fn bucket_count(&self) -> u32 {
1422        self.bucket_count
1423    }
1424
1425    /// Instances the visible list holds, and so how many every bucket's run
1426    /// holds between them — see [`DrawGenDesc::instance_capacity`].
1427    #[must_use]
1428    pub const fn visible_capacity(&self) -> u32 {
1429        self.capacity
1430    }
1431
1432    /// Which word of [`DrawGen::runs`] holds where bucket `bucket`'s run starts
1433    /// this frame, as the number `mesh.slang`'s `DrawConstants::start_at`
1434    /// carries.
1435    ///
1436    /// **The word, not the start.** The start is a per-frame number the
1437    /// draw-argument pass writes into this word — an absolute word index into
1438    /// the same buffer, never below [`runs_at`](Self::runs_at) — and the word is
1439    /// fixed at build, which is what lets a constant block written once name it.
1440    /// Past the survivors, their routes and the runs; see the module docs. A
1441    /// reader copying either back multiplies by four.
1442    ///
1443    /// The same for every generator a renderer builds from one bucket table and
1444    /// one capacity, which is what lets one set of constant blocks serve the
1445    /// camera, every shadow cull and every secondary view.
1446    #[must_use]
1447    pub const fn bucket_start_word(&self, bucket: u32) -> u32 {
1448        draw_gen::run_start_word(self.capacity, self.bucket_count, 0, bucket)
1449    }
1450
1451    /// Which word holds where bucket `bucket`'s run of draw region `region`
1452    /// starts this frame — [`bucket_start_word`](Self::bucket_start_word) for a
1453    /// region past 0, on its terms exactly.
1454    ///
1455    /// [`draw_gen::DRAW_REGIONS`] regions of start words are laid out in every
1456    /// generator whatever it allocates, so this is the same for every generator
1457    /// one renderer builds.
1458    #[must_use]
1459    pub const fn region_start_word(&self, region: u32, bucket: u32) -> u32 {
1460        draw_gen::run_start_word(self.capacity, self.bucket_count, region, bucket)
1461    }
1462
1463    /// Which word of [`DrawGen::runs`] holds where bucket `bucket`'s task
1464    /// chunks start in draw region `region` this frame —
1465    /// [`draw_gen::chunk_start_word`], the number
1466    /// [`ClusterDrawConstants::chunk_starts_at`](crcbl_shaders::meshlet::ClusterDrawConstants::chunk_starts_at)
1467    /// carries. `bucket` may be [`bucket_count`](Self::bucket_count), the
1468    /// region's end.
1469    ///
1470    /// The same for every generator one renderer builds, for
1471    /// [`region_start_word`](Self::region_start_word)'s reason.
1472    #[must_use]
1473    pub const fn chunk_start_word(&self, region: u32, bucket: u32) -> u32 {
1474        draw_gen::chunk_start_word(self.capacity, self.bucket_count, region, bucket)
1475    }
1476
1477    /// Byte offset in [`DrawGen::counts`] of flat segment `segment`'s task
1478    /// dispatch in draw region `region` — what a flat call's
1479    /// [`DrawIndirect::offset`](crcbl_hal::DrawIndirect::offset) carries.
1480    /// Behind every region this generator allocates, so it differs between
1481    /// generators of one renderer; [`GeneratedDraws::flat_args_offset`] is
1482    /// region 0's first, handed to the pass that draws them.
1483    #[must_use]
1484    pub const fn flat_args_offset(&self, region: u32, segment: u32) -> u64 {
1485        draw_gen::flat_args_word(self.bucket_count, self.mode.regions(), region, segment, 0) as u64
1486            * 4
1487    }
1488
1489    /// Which word of [`DrawGen::runs`] holds bucket `bucket`'s mesh, as the
1490    /// number `mesh.slang`'s `DrawConstants::mesh_at` carries — filled every
1491    /// frame by the draw-argument pass from the bucket table.
1492    ///
1493    /// The same for every generator one renderer builds, for
1494    /// [`region_start_word`](Self::region_start_word)'s reason.
1495    #[must_use]
1496    pub const fn bucket_mesh_word(&self, bucket: u32) -> u32 {
1497        draw_gen::bucket_mesh_word(self.capacity, self.bucket_count, bucket)
1498    }
1499
1500    /// How far region `region`'s argument structures sit behind region 0's, in
1501    /// bytes — what a draw of that region adds to
1502    /// [`args_offset`](Self::args_offset).
1503    #[must_use]
1504    pub const fn args_region_offset(&self, region: u32) -> u64 {
1505        region as u64 * self.bucket_count as u64 * draw_gen::DRAW_ARGS_SIZE as u64
1506    }
1507
1508    /// How far region `region`'s draw counts and dispatch extents sit behind
1509    /// region 0's, in bytes — what a draw of that region adds to
1510    /// [`count_offset`](Self::count_offset) and
1511    /// [`mesh_args_offset`](Self::mesh_args_offset). A region is one count and
1512    /// one extent structure per bucket, so its counts and its extents move
1513    /// together.
1514    #[must_use]
1515    pub const fn counts_region_offset(&self, region: u32) -> u64 {
1516        region as u64 * self.bucket_count as u64 * (4 + draw_gen::MESH_ARGS_SIZE as u64)
1517    }
1518
1519    /// What [`DrawGenDesc::mode`] built this generator for.
1520    #[must_use]
1521    pub const fn mode(&self) -> DrawMode {
1522        self.mode
1523    }
1524
1525    /// Set 1 of the occlusion cull's layout — the farthest-depth pyramid's
1526    /// levels — which [`PyramidInputs::group`] is built against. `None` on a
1527    /// generator not built for [`DrawMode::Occlusion`].
1528    #[must_use]
1529    pub fn occlusion_layout(&self) -> Option<BindGroupLayoutHandle> {
1530        self.occlusion().map(|pipelines| pipelines.pyramid_layout)
1531    }
1532
1533    /// The shared occlusion pipelines, on a generator built for
1534    /// [`DrawMode::Occlusion`] — `None` on any other, whatever the shared set
1535    /// carries, so a plain generator never dispatches them.
1536    fn occlusion(&self) -> Option<&OcclusionPipelines> {
1537        if self.mode == DrawMode::Occlusion {
1538            self.pipelines.occlusion.as_ref()
1539        } else {
1540            None
1541        }
1542    }
1543
1544    /// The mode `frame`'s dispatches were parametrised for by the last
1545    /// [`begin_frame_with`](Self::begin_frame_with) on that slot.
1546    ///
1547    /// # Panics
1548    ///
1549    /// If `frame` is not a slot this was built with.
1550    #[must_use]
1551    pub fn frame_mode(&self, frame: usize) -> DrawMode {
1552        match self.frame_modes[frame].load(Ordering::Relaxed) {
1553            SMALL_FEATURE_ONLY => DrawMode::Plain,
1554            word if word == DrawMode::Occlusion.word() => DrawMode::Occlusion,
1555            word if word == DrawMode::Faces.word() => DrawMode::Faces,
1556            _ => DrawMode::Plain,
1557        }
1558    }
1559
1560    /// Whether `frame` dispatches `cull.slang`'s occlusion entry point — the two
1561    /// phases, or the small-feature test alone — and so must be recorded with
1562    /// [`add_occlusion_passes`](Self::add_occlusion_passes).
1563    ///
1564    /// # Panics
1565    ///
1566    /// If `frame` is not a slot this was built with.
1567    #[must_use]
1568    pub fn uses_occlusion_entry(&self, frame: usize) -> bool {
1569        let word = self.frame_modes[frame].load(Ordering::Relaxed);
1570        word == DrawMode::Occlusion.word() || word == SMALL_FEATURE_ONLY
1571    }
1572
1573    /// The first word of the run region in [`DrawGen::runs`] — where bucket
1574    /// zero's run starts in every frame, and the floor of every other start.
1575    #[must_use]
1576    pub const fn runs_at(&self) -> u32 {
1577        draw_gen::runs_at(self.capacity)
1578    }
1579
1580    /// Bytes of each frame's [`DrawGen::runs`] buffer: the survivors, their
1581    /// routes, one capacity of runs and a start word per bucket.
1582    #[must_use]
1583    pub const fn runs_size(&self) -> u64 {
1584        self.runs_words as u64 * 4
1585    }
1586
1587    /// Byte offset of bucket `bucket`'s argument structure.
1588    #[must_use]
1589    pub const fn args_offset(&self, bucket: u32) -> u64 {
1590        bucket as u64 * draw_gen::DRAW_ARGS_SIZE as u64
1591    }
1592
1593    /// Byte offset of bucket `bucket`'s draw count, which is at the front of the
1594    /// buffer [`DrawGen::counts`] hands back.
1595    #[must_use]
1596    pub const fn count_offset(&self, bucket: u32) -> u64 {
1597        bucket as u64 * 4
1598    }
1599
1600    /// Byte offset of bucket `bucket`'s mesh-dispatch argument structure — what
1601    /// [`DrawIndirect::offset`](crcbl_hal::DrawIndirect::offset) carries in the
1602    /// call that reads it.
1603    ///
1604    /// **Past the one draw count per bucket** that shares the buffer, so this is
1605    /// never zero — see the module docs.
1606    #[must_use]
1607    pub const fn mesh_args_offset(&self, bucket: u32) -> u64 {
1608        self.bucket_count as u64 * 4 + bucket as u64 * draw_gen::MESH_ARGS_SIZE as u64
1609    }
1610
1611    /// The buffer of per-bucket instance runs for `frame`, which the drawing
1612    /// pass's bind group names.
1613    ///
1614    /// The same buffer [`DrawGen::visible`] hands back: bucket `bucket`'s run
1615    /// starts at the word this frame wrote into word
1616    /// [`bucket_start_word`](Self::bucket_start_word)`(bucket)`, past the
1617    /// survivor list and its routes.
1618    ///
1619    /// # Panics
1620    ///
1621    /// If `frame` is not a slot this was built with.
1622    #[must_use]
1623    pub fn runs(&self, frame: usize) -> BufferHandle {
1624        self.runs[frame]
1625    }
1626
1627    /// `frame`'s cull parameters — the frustum [`DrawGen::begin_frame`] wrote.
1628    ///
1629    /// # Panics
1630    ///
1631    /// If `frame` is not a slot this was built with.
1632    #[must_use]
1633    pub fn cull_params(&self, frame: usize) -> BufferHandle {
1634        self.cull_params[frame]
1635    }
1636
1637    /// `frame`'s compacted visible list — `cull.slang`'s survivors, as indices
1638    /// into the instance array, in no particular order, in the **first
1639    /// [`visible_capacity`](Self::visible_capacity) words** of the buffer.
1640    ///
1641    /// The same buffer [`DrawGen::runs`] hands back; the routes, the per-bucket
1642    /// runs and their starts follow the survivors in it. See the module docs.
1643    ///
1644    /// # Panics
1645    ///
1646    /// If `frame` is not a slot this was built with.
1647    #[must_use]
1648    pub fn visible(&self, frame: usize) -> BufferHandle {
1649        self.runs[frame]
1650    }
1651
1652    /// `frame`'s culling statistics: surviving instances in
1653    /// [`INSTANCE_SURVIVOR_WORD`](crcbl_shaders::cull::INSTANCE_SURVIVOR_WORD)
1654    /// and surviving clusters in
1655    /// [`CLUSTER_SURVIVOR_WORD`](crcbl_shaders::cull::CLUSTER_SURVIVOR_WORD).
1656    ///
1657    /// **Topic 03 §3.6's culling-stats readback is this buffer, on a delayed
1658    /// ring — the one readback the frame loop is allowed.** Both counters live
1659    /// here rather than in a buffer each so that stays one copy per frame.
1660    ///
1661    /// The instance count is the **true** one, which can exceed
1662    /// [`DrawGen::visible_capacity`] — so it is also where a scene that outgrew
1663    /// the list says so. The cluster count is what §3.5's amplification stage
1664    /// kept, and is zero on every path that has no amplification stage: the two
1665    /// indirect tails, and a device with `Features::MESH_SHADER` and no
1666    /// `Features::TASK_SHADER`.
1667    ///
1668    /// # Panics
1669    ///
1670    /// If `frame` is not a slot this was built with.
1671    #[must_use]
1672    pub fn visible_count(&self, frame: usize) -> BufferHandle {
1673        self.visible_count[frame]
1674    }
1675
1676    /// `frame`'s indirect arguments, [`draw_gen::DRAW_ARGS_SIZE`] bytes per
1677    /// bucket. The same buffer [`GeneratedDraws::args`] names.
1678    ///
1679    /// # Panics
1680    ///
1681    /// If `frame` is not a slot this was built with.
1682    #[must_use]
1683    pub fn args(&self, frame: usize) -> BufferHandle {
1684        self.args[frame]
1685    }
1686
1687    /// `frame`'s per-bucket draw counts, in the **first
1688    /// [`bucket_count`](Self::bucket_count) words** of the buffer
1689    /// [`GeneratedDraws::counts`] names.
1690    ///
1691    /// # Panics
1692    ///
1693    /// If `frame` is not a slot this was built with.
1694    #[must_use]
1695    pub fn counts(&self, frame: usize) -> BufferHandle {
1696        self.counts[frame]
1697    }
1698
1699    /// Every host-written table the draw-argument pass reads, in one buffer —
1700    /// the bucket table, the per-bucket cluster counts and
1701    /// topic 25's three selection tables.
1702    ///
1703    /// Shared by every frame, because all five are decided when a mesh becomes
1704    /// resident. Exposed for the reason the per-frame buffers are: the cluster
1705    /// counts are the only CPU-side half of an extent that is otherwise the
1706    /// GPU's, so a test with no GPU can still check the pass copied each
1707    /// bucket's own — [`table_offsets`](Self::table_offsets) is where each
1708    /// region starts.
1709    #[must_use]
1710    pub fn tables(&self) -> BufferHandle {
1711        self.tables
1712    }
1713
1714    /// Where each region of [`tables`](Self::tables) begins, in words.
1715    #[must_use]
1716    pub const fn table_offsets(&self) -> draw_gen::TableOffsets {
1717        self.table_offsets
1718    }
1719
1720    /// `frame`'s per-bucket mesh-dispatch arguments, at
1721    /// [`mesh_args_offset`](Self::mesh_args_offset)`(bucket)` in the buffer
1722    /// [`GeneratedDraws::counts`] names — the thing a test reads back to see that
1723    /// the extent the mesh path dispatched is the count culling produced rather
1724    /// than the instance pool's size.
1725    ///
1726    /// The same buffer [`DrawGen::counts`] hands back. **Not at offset zero**:
1727    /// the draw counts are in front of it.
1728    ///
1729    /// # Panics
1730    ///
1731    /// If `frame` is not a slot this was built with.
1732    #[must_use]
1733    pub fn mesh_args(&self, frame: usize) -> BufferHandle {
1734        self.counts[frame]
1735    }
1736
1737    /// Topic 25's hysteresis state, for a caller binding it into a
1738    /// mesh pipeline that reads it.
1739    ///
1740    /// One buffer for every frame in flight, unlike everything else here that a
1741    /// caller binds — see [`DrawGen::group_state`](Self::group_state)'s field
1742    /// docs, which is where that is argued.
1743    #[must_use]
1744    pub fn group_state(&self) -> BufferHandle {
1745        self.group_state
1746    }
1747
1748    /// The stride between two instances in that buffer, which is what
1749    /// [`ClusterDrawConstants::group_stride`] has to carry for the amplification
1750    /// stage to index it the same way this pass does.
1751    ///
1752    /// [`ClusterDrawConstants::group_stride`]: crcbl_shaders::meshlet::ClusterDrawConstants::group_stride
1753    #[must_use]
1754    pub const fn group_stride(&self) -> u32 {
1755        self.group_stride
1756    }
1757
1758    /// Writes `frame`'s cull parameters — this frame's frustum, how much of the
1759    /// instance array to test, and the camera topic 25's uniform
1760    /// cut selects a level from.
1761    ///
1762    /// The three counters both dispatches add to are **not** zeroed here: that
1763    /// is the clearing pass [`DrawGen::add_passes`] schedules, and the module
1764    /// docs say why it has to be a dispatch inside the frame rather than a host
1765    /// write before it.
1766    ///
1767    /// Call once per frame, before [`DrawGen::add_passes`], against the frame
1768    /// slot the instance pool rotated to — the buffer written here is the one
1769    /// that slot's bind groups name.
1770    ///
1771    /// `instance_count` is how many elements of the instance array the cull
1772    /// dispatch tests, which is
1773    /// [`InstancePool::slot_count`](crate::instance_pool::InstancePool::slot_count)
1774    /// and **not** its live count: an array with a hole in it still has live
1775    /// instances above the hole.
1776    ///
1777    /// # Errors
1778    ///
1779    /// [`HalError`] if the write failed.
1780    ///
1781    /// # Panics
1782    ///
1783    /// If `frame` is not a slot this was built with.
1784    /// `camera_position` and `lod_params` are the two the drawing pass writes
1785    /// into [`FrameUniforms`](crcbl_shaders::mesh::FrameUniforms) — passed in
1786    /// rather than re-derived here for the reason the frustum is: a pass that
1787    /// selects detail against one camera while another draws is a difference
1788    /// nothing in a frame can see.
1789    ///
1790    /// **Which is why the one caller allowed to break that is a deliberate
1791    /// setting rather than an accident of what was in scope.**
1792    /// [`ForwardRenderer::set_frozen_selection_eye`] hands this a pinned eye
1793    /// while the frame block keeps the live camera, so the cut a reviewer is
1794    /// looking at is the one chosen for somewhere they are no longer standing —
1795    /// which is the only vantage point a cut can be judged from.
1796    ///
1797    /// [`ForwardRenderer::set_frozen_selection_eye`]: crate::ForwardRenderer::set_frozen_selection_eye
1798    pub fn begin_frame(
1799        &self,
1800        device: &dyn Device,
1801        frame: usize,
1802        frustum: &Frustum,
1803        instance_count: u32,
1804        camera_position: [f32; 3],
1805        lod_params: [f32; 3],
1806    ) -> Result<(), HalError> {
1807        self.begin_frame_with(
1808            device,
1809            frame,
1810            frustum,
1811            instance_count,
1812            Selection {
1813                camera_position,
1814                lod_params,
1815            },
1816            &FrameCull::Plain,
1817        )
1818    }
1819
1820    /// [`begin_frame`](Self::begin_frame), with what the cull does beyond the
1821    /// frustum this frame.
1822    ///
1823    /// The mode written here is what [`add_passes`](Self::add_passes) and
1824    /// [`add_occlusion_passes`](Self::add_occlusion_passes) check against, so a
1825    /// frame whose passes disagree with the block its dispatches read is a panic
1826    /// rather than a frame that scatters into regions nothing draws.
1827    ///
1828    /// # Errors
1829    ///
1830    /// [`HalError`] if a write failed.
1831    ///
1832    /// # Panics
1833    ///
1834    /// If `frame` is not a slot this was built with, or `cull` asks for a mode
1835    /// this generator was not built for.
1836    pub fn begin_frame_with(
1837        &self,
1838        device: &dyn Device,
1839        frame: usize,
1840        frustum: &Frustum,
1841        instance_count: u32,
1842        selection: Selection,
1843        cull: &FrameCull<'_>,
1844    ) -> Result<(), HalError> {
1845        let Selection {
1846            camera_position,
1847            lod_params,
1848        } = selection;
1849        let mut params = cull_shader::Params {
1850            planes: frustum.planes.map(|plane| plane.to_array()),
1851            instance_count,
1852            capacity: self.capacity,
1853            hidden_view: self.hidden_view,
1854            ..cull_shader::Params::default()
1855        };
1856        let mode = match cull {
1857            FrameCull::Plain => DrawMode::Plain,
1858            FrameCull::Faces(faces) => {
1859                assert_eq!(
1860                    self.mode,
1861                    DrawMode::Faces,
1862                    "a point light's face culls need a generator built with its face regions"
1863                );
1864                params.features = cull_shader::Features::FACES;
1865                for (face, planes) in faces.iter().enumerate() {
1866                    for (plane, value) in planes.iter().enumerate() {
1867                        params.face_planes[face * cull_shader::FACE_PLANES + plane] =
1868                            value.to_array();
1869                    }
1870                }
1871                DrawMode::Faces
1872            }
1873            FrameCull::Occlusion(occlusion) => {
1874                assert_eq!(
1875                    self.mode,
1876                    DrawMode::Occlusion,
1877                    "the occlusion culls need a generator built with the occlusion regions"
1878                );
1879                let mut features = cull_shader::Features::NONE;
1880                if occlusion.occlusion && occlusion.history {
1881                    features = features.union(cull_shader::Features::OCCLUSION_HISTORY);
1882                }
1883                if occlusion.small_feature_pixels.is_some() {
1884                    features = features.union(cull_shader::Features::SMALL_FEATURE);
1885                }
1886                params.features = features;
1887                params.view_proj = occlusion.view_projection.to_cols_array();
1888                params.previous_view_proj = occlusion.previous_view_projection.to_cols_array();
1889                params.target_extent = [occlusion.target.0, occlusion.target.1];
1890                params.pyramid_levels = occlusion
1891                    .pyramid_levels
1892                    .min(cull_shader::OCCLUSION_MAX_LEVELS);
1893                params.small_feature_pixels = occlusion.small_feature_pixels.unwrap_or(0.0);
1894                if occlusion.occlusion {
1895                    DrawMode::Occlusion
1896                } else {
1897                    DrawMode::Plain
1898                }
1899            }
1900        };
1901        device.write_buffer(
1902            self.gen_params[frame],
1903            0,
1904            &draw_gen::Params {
1905                bucket_count: self.bucket_count,
1906                visible_capacity: self.capacity,
1907                group_stride: self.group_stride,
1908                bucket_modes_at: self.table_offsets.bucket_modes_at,
1909                bucket_clusters_at: self.table_offsets.bucket_clusters_at,
1910                mesh_levels_at: self.table_offsets.mesh_levels_at,
1911                level_groups_at: self.table_offsets.level_groups_at,
1912                level_meshes_at: self.table_offsets.level_meshes_at,
1913                camera_position,
1914                lod_params,
1915                mode,
1916                draw_regions: self.mode.regions(),
1917                face_runs_at: draw_gen::face_runs_at(self.capacity, self.bucket_count),
1918                bucket_lookup_at: self.table_offsets.bucket_lookup_at,
1919                task_lanes: self.task_lanes,
1920                flat_segments_at: self.table_offsets.flat_segments_at,
1921            }
1922            .to_bytes(),
1923        )?;
1924        device.write_buffer(self.cull_params[frame], 0, &params.to_bytes())?;
1925        // A frame whose occlusion culls are off but whose small-feature test is
1926        // on still dispatches the occlusion entry point — it is where that test
1927        // lives — and scatters plainly.
1928        let cull_word = match cull {
1929            FrameCull::Occlusion(occlusion)
1930                if !occlusion.occlusion && occlusion.small_feature_pixels.is_some() =>
1931            {
1932                SMALL_FEATURE_ONLY
1933            }
1934            _ => mode.word(),
1935        };
1936        self.frame_modes[frame].store(cull_word, Ordering::Relaxed);
1937        Ok(())
1938    }
1939
1940    /// The maximum number of passes [`add_passes`](Self::add_passes) adds to a
1941    /// frame: the clear, the cull, and the route, prefix-sum and scatter passes.
1942    ///
1943    /// A ceiling rather than an exact count: a frame that tests no instance
1944    /// omits the cull and scatter passes and adds only the clear, route and
1945    /// prefix-sum ones. This upper bound is what a caller sizing
1946    /// [`PassTimers`](crate::timing::PassTimers) adds up — see
1947    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES).
1948    pub const MAX_PASSES: u32 = 5;
1949
1950    /// How many dispatches [`add_passes`](Self::add_passes) records for a frame
1951    /// that tests at least one instance: the clear, the cull, and the
1952    /// draw-argument pass's route, prefix sum and scatter.
1953    ///
1954    /// One per pass of [`MAX_PASSES`](Self::MAX_PASSES), which is the same
1955    /// number: a frame that tests no instance records neither the cull's nor
1956    /// the scatter's, since a dispatch of no workgroups is one Metal rejects.
1957    pub const DISPATCHES: u32 = 5;
1958
1959    /// Passes [`add_late_passes`](Self::add_late_passes) adds at most: the
1960    /// second occlusion phase, the late scatter and the finish.
1961    pub const LATE_PASSES: u32 = 3;
1962
1963    /// Adds the cull and draw-argument passes to `graph` and returns what the
1964    /// caller's render pass draws from.
1965    ///
1966    /// The barriers between the three — including the transition into
1967    /// [`ResourceState::IndirectArgument`] — are the graph's, computed from the
1968    /// accesses declared here and the ones the caller declares on the
1969    /// [`GeneratedDraws`] ids.
1970    ///
1971    /// # Panics
1972    ///
1973    /// If `frame` is not a slot this was built with.
1974    pub fn add_passes(
1975        &self,
1976        graph: &mut RenderGraph<'_>,
1977        frame: usize,
1978        instance_count: u32,
1979    ) -> GeneratedDraws {
1980        let word = self.frame_modes[frame].load(Ordering::Relaxed);
1981        assert!(
1982            word != DrawMode::Occlusion.word() && word != SMALL_FEATURE_ONLY,
1983            "frame {frame} was begun with the occlusion culls, whose passes are \
1984             `add_occlusion_passes`"
1985        );
1986        self.record_passes(graph, frame, instance_count, None)
1987    }
1988
1989    /// [`add_passes`](Self::add_passes) for a frame
1990    /// [`begin_frame_with`](Self::begin_frame_with) began with
1991    /// [`FrameCull::Occlusion`]: the cull is the first occlusion phase against
1992    /// `pyramid`, which it reads before this frame's reduction passes write it.
1993    ///
1994    /// The draws it returns are the **early** ones — region
1995    /// [`draw_gen::EARLY_REGION`] — until [`add_late_passes`](Self::add_late_passes)
1996    /// has closed the frame; a frame whose occlusion is off and whose
1997    /// small-feature test is on draws region 0 from here directly.
1998    ///
1999    /// # Panics
2000    ///
2001    /// If `frame` is not a slot this was built with, or was not begun with
2002    /// [`FrameCull::Occlusion`].
2003    pub fn add_occlusion_passes(
2004        &self,
2005        graph: &mut RenderGraph<'_>,
2006        frame: usize,
2007        instance_count: u32,
2008        pyramid: &PyramidInputs<'_>,
2009    ) -> GeneratedDraws {
2010        let word = self.frame_modes[frame].load(Ordering::Relaxed);
2011        assert!(
2012            word == DrawMode::Occlusion.word() || word == SMALL_FEATURE_ONLY,
2013            "frame {frame} was not begun with the occlusion culls"
2014        );
2015        let occlusion = self
2016            .occlusion()
2017            .unwrap_or_else(|| unreachable!("begin_frame_with checked the generator's mode"));
2018        self.record_passes(
2019            graph,
2020            frame,
2021            instance_count,
2022            Some((occlusion.early, occlusion.cull_pipeline_layout, pyramid)),
2023        )
2024    }
2025
2026    /// The second occlusion phase and the late draw arguments, after this
2027    /// frame's farthest-depth pyramid has been reduced from the early prepass.
2028    ///
2029    /// Three passes: `cull.slang`'s `lateMain` tests every survivor the first
2030    /// phase marked against `pyramid`, `draw_gen.slang`'s late scatter appends
2031    /// the ones it rescued behind each bucket's early run, and its finish writes
2032    /// region [`draw_gen::LATE_REGION`]'s counts and region 0's — the early and
2033    /// late draws together, which is what the forward pass draws. A frame that
2034    /// tests no instance records the finish alone, because region 0 still needs
2035    /// its zeroes written.
2036    ///
2037    /// # Panics
2038    ///
2039    /// If `frame` is not a slot this was built with, or was not begun with
2040    /// occlusion on.
2041    pub fn add_late_passes(
2042        &self,
2043        graph: &mut RenderGraph<'_>,
2044        frame: usize,
2045        instance_count: u32,
2046        draws: &GeneratedDraws,
2047        pyramid: &PyramidInputs<'_>,
2048    ) {
2049        assert_eq!(
2050            self.frame_modes[frame].load(Ordering::Relaxed),
2051            DrawMode::Occlusion.word(),
2052            "frame {frame} was not begun with the occlusion culls on"
2053        );
2054        let occlusion = self
2055            .occlusion()
2056            .unwrap_or_else(|| unreachable!("begin_frame_with checked the generator's mode"));
2057        let groups = instance_count.div_ceil(cull_shader::WORKGROUP_SIZE);
2058        if groups != 0 {
2059            let cull_group = self.cull_groups[frame];
2060            let pyramid_group = pyramid.group;
2061            let layout = occlusion.cull_pipeline_layout;
2062            let pipeline = occlusion.late;
2063            let mut pass = graph
2064                .add_compute_pass("occlusion-late")
2065                .use_buffer(draws.runs_id, ResourceState::ShaderReadWrite)
2066                .use_buffer(draws.visible_count_id, ResourceState::ShaderReadWrite);
2067            for &level in pyramid.levels {
2068                pass = pass.read_image(level);
2069            }
2070            pass.execute(move |ctx| {
2071                let encoder = ctx.encoder();
2072                encoder.bind_compute_pipeline(pipeline);
2073                encoder.bind_group(0, cull_group, &[], layout);
2074                encoder.bind_group(1, pyramid_group, &[], layout);
2075                encoder.dispatch(groups, 1, 1);
2076            });
2077        }
2078        let gen_layout = self.pipelines.gen_pipeline_layout;
2079        let gen_group = self.gen_groups[frame];
2080        for (label, pipeline, groups) in [
2081            (
2082                "draw-late-scatter",
2083                occlusion.late_scatter,
2084                instance_count.div_ceil(draw_gen::WORKGROUP_SIZE),
2085            ),
2086            ("draw-late-finish", occlusion.late_finish, 1),
2087        ] {
2088            if groups == 0 {
2089                continue;
2090            }
2091            graph
2092                .add_compute_pass(label)
2093                .read_buffer(draws.visible_count_id)
2094                .use_buffer(draws.runs_id, ResourceState::ShaderReadWrite)
2095                .use_buffer(draws.args_id, ResourceState::ShaderReadWrite)
2096                .use_buffer(draws.counts_id, ResourceState::ShaderReadWrite)
2097                .use_buffer(draws.group_state_id, ResourceState::ShaderReadWrite)
2098                .execute(move |ctx| {
2099                    let encoder = ctx.encoder();
2100                    encoder.bind_compute_pipeline(pipeline);
2101                    encoder.bind_group(0, gen_group, &[], gen_layout);
2102                    encoder.dispatch(groups, 1, 1);
2103                });
2104        }
2105    }
2106
2107    /// The clear, the cull and the three draw-argument passes, with the cull
2108    /// either `cull.slang`'s frustum entry point or `occlusion`'s first phase
2109    /// over the pyramid it names.
2110    fn record_passes(
2111        &self,
2112        graph: &mut RenderGraph<'_>,
2113        frame: usize,
2114        instance_count: u32,
2115        occlusion: Option<(
2116            ComputePipelineHandle,
2117            PipelineLayoutHandle,
2118            &PyramidInputs<'_>,
2119        )>,
2120    ) -> GeneratedDraws {
2121        // Each buffer arrives in the state the *previous* frame that used this
2122        // slot left it in, which is the state declared as final below. Vacuous
2123        // on the first frame, when nothing has been written and there is nothing
2124        // to order against, and the real prior use on every later one.
2125        let import = |graph: &mut RenderGraph<'_>, label: &str, buffer, state| {
2126            graph.import_buffer(
2127                label,
2128                ImportedBuffer {
2129                    buffer,
2130                    initial: state,
2131                    final_state: state,
2132                },
2133            )
2134        };
2135        let visible_count = import(
2136            graph,
2137            "cull-count",
2138            self.visible_count[frame],
2139            ResourceState::ShaderRead,
2140        );
2141        // The survivor list and the per-bucket runs are one buffer, so they are
2142        // one id: importing it twice would give the graph two independent
2143        // histories of one resource and a barrier computed from half of it.
2144        let runs = import(
2145            graph,
2146            "visible-and-bucket-runs",
2147            self.runs[frame],
2148            ResourceState::ShaderRead,
2149        );
2150        let args = import(
2151            graph,
2152            "draw-args",
2153            self.args[frame],
2154            ResourceState::IndirectArgument,
2155        );
2156        // The draw counts and the mesh-dispatch extents, likewise.
2157        let counts = import(
2158            graph,
2159            "draw-counts-and-mesh-dispatch-args",
2160            self.counts[frame],
2161            ResourceState::IndirectArgument,
2162        );
2163        // **Not indexed by `frame`**, and that is the point: this one buffer is
2164        // what carries a decision from the previous frame into this one. It
2165        // arrives in `ShaderReadWrite` because that is what the last frame left
2166        // it in — and on the very first frame because that is what
2167        // the start-up fill left it in, which is why that copy ends with a
2168        // barrier rather than in `TransferDst`. `ResourceState::needs_barrier`
2169        // answers `true` for any
2170        // transition touching a write — so the first barrier of this frame
2171        // carries a source scope covering that frame's writes and the mesh
2172        // stage's reads of them, whether or not that frame is still in flight.
2173        let group_state = import(
2174            graph,
2175            "lod-group-state",
2176            self.group_state,
2177            ResourceState::ShaderReadWrite,
2178        );
2179
2180        // The zero every atomic below counts up from, and the first thing in the
2181        // frame that touches any of the three. Its barrier into the cull pass is
2182        // the graph's, out of the `ShaderReadWrite` declared on both sides.
2183        let clear_pipeline = self.pipelines.clear_pipeline;
2184        let clear_layout = self.pipelines.clear_pipeline_layout;
2185        let clear_group = self.clear_groups[frame];
2186        // The longest of the three buffers: the arguments, one structure per
2187        // bucket per region, or for a small table the counts and extents with
2188        // the flat task dispatches behind them. `new` refuses a table with no
2189        // buckets, so this is never the empty dispatch Metal rejects.
2190        let regions = self.mode.regions();
2191        let clear_groups = (regions * self.bucket_count * draw_gen::DRAW_ARGS_WORDS as u32)
2192            .max(draw_gen::flat_args_word(
2193                self.bucket_count,
2194                regions,
2195                regions,
2196                0,
2197                0,
2198            ))
2199            .div_ceil(clear_counters::WORKGROUP_SIZE);
2200        graph
2201            .add_compute_pass("clear-counters")
2202            .use_buffer(visible_count, ResourceState::ShaderReadWrite)
2203            .use_buffer(args, ResourceState::ShaderReadWrite)
2204            // Both regions of it: the counts and the mesh-dispatch extents are
2205            // one buffer and therefore one declaration.
2206            .use_buffer(counts, ResourceState::ShaderReadWrite)
2207            .execute(move |ctx| {
2208                let encoder = ctx.encoder();
2209                encoder.bind_compute_pipeline(clear_pipeline);
2210                encoder.bind_group(0, clear_group, &[], clear_layout);
2211                encoder.dispatch(clear_groups, 1, 1);
2212            });
2213
2214        let (cull_pipeline, cull_layout, pyramid_group) = match occlusion {
2215            Some((pipeline, layout, pyramid)) => (pipeline, layout, Some(pyramid.group)),
2216            None => (
2217                self.pipelines.cull_pipeline,
2218                self.pipelines.cull_pipeline_layout,
2219                None,
2220            ),
2221        };
2222        let cull_group = self.cull_groups[frame];
2223        let cull_groups = instance_count.div_ceil(cull_shader::WORKGROUP_SIZE);
2224        // Omit an empty pass, not just its dispatch: Metal still creates an
2225        // encoder for a graph pass, and strict validation rejects ending one
2226        // without work. The clear and argument-generation passes remain needed
2227        // to erase the preceding frame's counts and populate zero draws.
2228        if cull_groups != 0 {
2229            let mut pass = graph
2230                .add_compute_pass("cull")
2231                // `ShaderReadWrite` rather than a write-only state for both: a
2232                // storage-buffer descriptor permits reads whatever the shader does
2233                // with it, and the counter is genuinely read-modify-written.
2234                .use_buffer(runs, ResourceState::ShaderReadWrite)
2235                .use_buffer(visible_count, ResourceState::ShaderReadWrite);
2236            // The previous frame's pyramid, read before this frame's reduction
2237            // writes over it: the declaration is what orders the two.
2238            for &level in occlusion.map_or(&[][..], |(_, _, pyramid)| pyramid.levels) {
2239                pass = pass.read_image(level);
2240            }
2241            pass.execute(move |ctx| {
2242                let encoder = ctx.encoder();
2243                encoder.bind_compute_pipeline(cull_pipeline);
2244                encoder.bind_group(0, cull_group, &[], cull_layout);
2245                if let Some(group) = pyramid_group {
2246                    encoder.bind_group(1, group, &[], cull_layout);
2247                }
2248                encoder.dispatch(cull_groups, 1, 1);
2249            });
2250        }
2251
2252        let gen_layout = self.pipelines.gen_pipeline_layout;
2253        let gen_group = self.gen_groups[frame];
2254        // One `binMain` invocation owns bucket `i` *and* routes visible instance
2255        // `i`, so its dispatch covers the larger of the two — and is never empty,
2256        // because the static half of every bucket's arguments has to be written
2257        // even for a frame that culled everything.
2258        let bin_groups = instance_count
2259            .max(self.bucket_count)
2260            .div_ceil(draw_gen::WORKGROUP_SIZE);
2261        // `scatterMain` only scatters, and the survivors are at most the tested
2262        // instances.
2263        let scatter_groups = instance_count.div_ceil(draw_gen::WORKGROUP_SIZE);
2264        // **Three passes, not three dispatches in one**, and the difference is
2265        // the whole of whether this works on every device. Each stage reads what
2266        // the one before it wrote — `startsMain` the routes and counts
2267        // `binMain` finished, `scatterMain` the starts — and a dependency a pass
2268        // does not declare is one the device is not told about: `crcbl-vk`
2269        // records explicit pipeline barriers, and a driver may run commands with
2270        // no barrier between them in any order it likes. Recorded as one pass,
2271        // an NVIDIA GeForce MX550 (615.71.09) ran the prefix sum and the scatter
2272        // against buffers the routing dispatch had not written yet, so every
2273        // bucket's start collapsed onto the run region's first word — while
2274        // lavapipe, which runs commands in order, passed every check. As three
2275        // passes over the same declarations the graph puts a barrier on each
2276        // buffer between them, as it does between the cull and this.
2277        //
2278        // Every pass declares all four written buffers, because every pass binds
2279        // the one group that names them.
2280        let passes = [
2281            ("draw-args", self.pipelines.bin_pipeline, bin_groups),
2282            ("draw-starts", self.pipelines.starts_pipeline, 1),
2283            (
2284                "draw-scatter",
2285                self.pipelines.scatter_pipeline,
2286                scatter_groups,
2287            ),
2288        ];
2289        for (label, pipeline, groups) in passes {
2290            // No instances tested is no survivors to scatter: omit that pass
2291            // for the same reason as the cull's.
2292            if groups == 0 {
2293                continue;
2294            }
2295            graph
2296                .add_compute_pass(label)
2297                .read_buffer(visible_count)
2298                // Read for the survivor list and written for the routes, the runs
2299                // and their starts, which share it — one declaration, and
2300                // `ShaderReadWrite` is what it really is.
2301                .use_buffer(runs, ResourceState::ShaderReadWrite)
2302                .use_buffer(args, ResourceState::ShaderReadWrite)
2303                .use_buffer(counts, ResourceState::ShaderReadWrite)
2304                .use_buffer(group_state, ResourceState::ShaderReadWrite)
2305                .execute(move |ctx| {
2306                    let encoder = ctx.encoder();
2307                    encoder.bind_compute_pipeline(pipeline);
2308                    encoder.bind_group(0, gen_group, &[], gen_layout);
2309                    encoder.dispatch(groups, 1, 1);
2310                });
2311        }
2312
2313        GeneratedDraws {
2314            args: self.args[frame],
2315            args_id: args,
2316            counts: self.counts[frame],
2317            counts_id: counts,
2318            flat_args_offset: self.flat_args_offset(0, 0),
2319            runs_id: runs,
2320            group_state_id: group_state,
2321            visible_count_id: visible_count,
2322        }
2323    }
2324
2325    /// Releases everything it owns, in dependency order, and gives back its
2326    /// reference to the shared [`DrawGenPipelines`] — which this destroys only
2327    /// if it was the last. The device must be idle.
2328    pub fn destroy(self, device: &dyn Device) {
2329        for group in self
2330            .gen_groups
2331            .into_iter()
2332            .chain(self.cull_groups)
2333            .chain(self.clear_groups)
2334        {
2335            device.destroy_bind_group(group);
2336        }
2337        DrawGenPipelines::release(self.pipelines, device);
2338        for buffer in [self.tables, self.clear_params, self.group_state]
2339            .into_iter()
2340            .chain(self.gen_params)
2341            .chain(self.cull_params)
2342            .chain(self.visible_count)
2343            .chain(self.runs)
2344            .chain(self.args)
2345            .chain(self.counts)
2346        {
2347            device.destroy_buffer(buffer);
2348        }
2349    }
2350}
2351
2352/// A uniform-buffer layout entry for the compute stage.
2353///
2354/// Shared with [`crate::light_grid`], which builds a compute pass on exactly
2355/// these terms: one uniform block of parameters and a handful of storage
2356/// buffers, in the shader's declaration order.
2357pub(crate) const fn uniform(binding: u32) -> BindGroupLayoutEntry {
2358    BindGroupLayoutEntry {
2359        binding,
2360        visibility: ShaderStages::COMPUTE,
2361        kind: BindingKind::UniformBuffer { dynamic: false },
2362        count: 1,
2363        flags: BindingFlags::empty(),
2364    }
2365}
2366
2367/// A `uint` element's stride — the element of every counter, index and bitmask
2368/// buffer these compute passes declare.
2369pub(crate) const UINT_STRIDE: u32 = size_of::<u32>() as u32;
2370
2371/// A storage-buffer layout entry for the compute stage. `read_only` is the
2372/// shader's own `StructuredBuffer` versus `RWStructuredBuffer`, so it is the
2373/// truth rather than a hint, and `stride` is the byte size of that buffer's
2374/// element type — `crcbl-vk` and `crcbl-dx12` both refuse a pipeline whose
2375/// shader disagrees.
2376pub(crate) const fn storage(binding: u32, read_only: bool, stride: u32) -> BindGroupLayoutEntry {
2377    BindGroupLayoutEntry {
2378        binding,
2379        visibility: ShaderStages::COMPUTE,
2380        kind: BindingKind::StorageBuffer {
2381            read_only,
2382            dynamic: false,
2383            stride,
2384        },
2385        count: 1,
2386        flags: BindingFlags::empty(),
2387    }
2388}
2389
2390/// A whole-buffer bind group entry.
2391pub(crate) const fn bound(binding: u32, buffer: BufferHandle) -> BindGroupEntry {
2392    BindGroupEntry {
2393        binding,
2394        array_index: 0,
2395        resource: BindingResource::whole_buffer(buffer),
2396    }
2397}
2398
2399/// Creates a compute pipeline from `shader`'s single compute entry point,
2400/// destroying the module whether or not the pipeline was created.
2401pub(crate) fn compute_pipeline(
2402    device: &dyn Device,
2403    label: &str,
2404    shader: &crcbl_shaders::Shader,
2405    layout: PipelineLayoutHandle,
2406    workgroup_size: u32,
2407) -> Result<ComputePipelineHandle, HalError> {
2408    // Resolved before the module exists, for `crate::forward`'s reason: a
2409    // manifest that disagreed with the artifact would otherwise fail inside the
2410    // descriptor literal, with the module already created and nothing holding
2411    // it.
2412    let entry_point = shader.entry_point(Stage::Compute).ok_or_else(|| {
2413        HalError::ShaderCompilation(format!(
2414            "{}.slang exposes no unambiguous compute entry point; the committed SPIR-V and its \
2415             manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
2416            shader.name()
2417        ))
2418    })?;
2419    compute_pipeline_entry(device, label, shader, entry_point, layout, workgroup_size)
2420}
2421
2422/// [`compute_pipeline`] for a module with **more than one** compute entry
2423/// point, which is a thing Slang compiles and [`Shader::entry_point`] refuses
2424/// to guess between.
2425///
2426/// `crate::volumetric` is the caller that needs it: its scatter and integrate
2427/// kernels are two entry points of one module because they share the froxel
2428/// arithmetic and there is no `#include` to share it any other way.
2429///
2430/// The name is not checked against the module here — a wrong one fails at
2431/// pipeline creation, which is where every backend reports it.
2432///
2433/// [`Shader::entry_point`]: crcbl_shaders::Shader::entry_point
2434pub(crate) fn compute_pipeline_entry(
2435    device: &dyn Device,
2436    label: &str,
2437    shader: &crcbl_shaders::Shader,
2438    entry_point: &str,
2439    layout: PipelineLayoutHandle,
2440    workgroup_size: u32,
2441) -> Result<ComputePipelineHandle, HalError> {
2442    compute_pipeline_entry_with_workgroup(
2443        device,
2444        label,
2445        shader,
2446        entry_point,
2447        layout,
2448        [workgroup_size, 1, 1],
2449    )
2450}
2451
2452/// [`compute_pipeline_entry`] with the complete three-dimensional workgroup
2453/// shape for kernels whose lanes form a tile rather than a row.
2454pub(crate) fn compute_pipeline_entry_with_workgroup(
2455    device: &dyn Device,
2456    label: &str,
2457    shader: &crcbl_shaders::Shader,
2458    entry_point: &str,
2459    layout: PipelineLayoutHandle,
2460    workgroup_size: [u32; 3],
2461) -> Result<ComputePipelineHandle, HalError> {
2462    let module = device.create_shader_module(&ShaderModuleDesc {
2463        label: Some(shader.name()),
2464        spirv: shader.spirv(),
2465        wgsl: shader.wgsl(),
2466        msl: shader.msl(),
2467        // One DXIL container per entry point, all of them, exactly as the
2468        // two-stage graphics modules pass theirs — the backend picks the one
2469        // `entry_point` names below.
2470        dxil: &shader.dxil_containers(),
2471    })?;
2472    let pipeline = device.create_compute_pipeline(&ComputePipelineDesc {
2473        label: Some(label),
2474        layout,
2475        compute: ShaderEntry {
2476            module,
2477            entry_point,
2478        },
2479        // The shader's own shape rather than literals: a dispatch sized against
2480        // a different one tests part of the array and reads as a cull.
2481        workgroup_size,
2482    });
2483    device.destroy_shader_module(module);
2484    pipeline
2485}
2486
2487/// What a partly-built [`DrawGen`] or [`DrawGenPipelines`] has to give back.
2488///
2489/// Each `build` creates its objects with `?` between them and the seam's
2490/// `destroy_*` is explicit, so a failure half way through would otherwise leak
2491/// everything created before it. A generator's holds buffers and bind groups;
2492/// the shared set's holds layouts and pipelines.
2493#[derive(Debug, Default)]
2494struct Rollback {
2495    buffers: Vec<BufferHandle>,
2496    bind_groups: Vec<BindGroupHandle>,
2497    bind_group_layouts: Vec<BindGroupLayoutHandle>,
2498    pipeline_layouts: Vec<PipelineLayoutHandle>,
2499    pipelines: Vec<ComputePipelineHandle>,
2500}
2501
2502impl Rollback {
2503    /// Forgets everything, once the objects have an owner that will destroy
2504    /// them.
2505    fn disarm(&mut self) {
2506        *self = Self::default();
2507    }
2508
2509    /// Releases everything: pipelines before their layouts, bind groups before
2510    /// theirs, and buffers last — the order [`DrawGen::destroy`] and
2511    /// [`DrawGenPipelines`]' own release follow between them.
2512    fn run(self, device: &dyn Device) {
2513        for handle in self.pipelines {
2514            device.destroy_compute_pipeline(handle);
2515        }
2516        for handle in self.pipeline_layouts {
2517            device.destroy_pipeline_layout(handle);
2518        }
2519        for handle in self.bind_groups {
2520            device.destroy_bind_group(handle);
2521        }
2522        for handle in self.bind_group_layouts {
2523            device.destroy_bind_group_layout(handle);
2524        }
2525        for handle in self.buffers {
2526            device.destroy_buffer(handle);
2527        }
2528    }
2529}
2530
2531// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
2532#[cfg(all(test, not(target_arch = "wasm32")))]
2533mod tests {
2534    use super::*;
2535    use crcbl_hal::null::{NullInstance, Recorder};
2536    use crcbl_hal::{DeviceDesc, Instance, QueueHandle, QueueKind};
2537    use crcbl_shaders::level_select::MeshLevels;
2538
2539    fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
2540        let recorder = Recorder::new();
2541        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
2542        let adapter = instance.adapters().remove(0);
2543        let device = instance
2544            .create_device(&DeviceDesc::for_adapter(adapter.id))
2545            .expect("the null backend always opens");
2546        let queue = device.queue(QueueKind::Graphics).expect("always present");
2547        (recorder, device, queue)
2548    }
2549
2550    /// A generator over `buckets` buckets of `capacity` instances, every bucket
2551    /// drawing its own flat mesh — the smallest table that is still a table of
2552    /// that length.
2553    fn generator(device: &dyn Device, queue: QueueHandle, capacity: u32, buckets: u32) -> DrawGen {
2554        generator_in(device, queue, capacity, buckets, DrawMode::Plain)
2555    }
2556
2557    /// [`generator`], built for `mode`.
2558    fn generator_in(
2559        device: &dyn Device,
2560        queue: QueueHandle,
2561        capacity: u32,
2562        buckets: u32,
2563        mode: DrawMode,
2564    ) -> DrawGen {
2565        let storage = |label: &str, size: u64| {
2566            device
2567                .create_buffer(&BufferDesc {
2568                    label: Some(label),
2569                    size,
2570                    usage: BufferUsage::STORAGE,
2571                    memory: MemoryLocation::HostUpload,
2572                })
2573                .expect("a storage buffer")
2574        };
2575        let instances = [storage("instances", 4)];
2576        let mesh_table = storage("mesh table", 4);
2577        let bucket_meshes: Vec<u32> = (0..buckets).collect();
2578        let zeroes = vec![0u32; bucket_meshes.len()];
2579        let mesh_levels: Vec<MeshLevels> = bucket_meshes
2580            .iter()
2581            .map(|mesh| MeshLevels {
2582                first_level: *mesh,
2583                ..MeshLevels::FLAT
2584            })
2585            .collect();
2586        let mut uploads = UploadBatch::new(device, queue, "draw gen test");
2587        let pipelines = DrawGenPipelines::new(device, mode == DrawMode::Occlusion, &mut || {})
2588            .expect("the null backend builds the pipelines");
2589        let draws = DrawGen::new(
2590            device,
2591            &mut uploads,
2592            &pipelines,
2593            &DrawGenDesc {
2594                label: Some("draw gen test"),
2595                instances: &instances,
2596                mesh_table,
2597                bucket_meshes: &bucket_meshes,
2598                bucket_modes: &zeroes,
2599                bucket_clusters: &zeroes,
2600                bucket_cluster_bases: &zeroes,
2601                mesh_levels: &mesh_levels,
2602                level_groups: &[],
2603                level_meshes: &bucket_meshes,
2604                instance_capacity: capacity,
2605                hidden_view: 0,
2606                mode,
2607                task_lanes: 0,
2608            },
2609        )
2610        .expect("the null backend builds a generator");
2611        uploads.submit().expect("the hysteresis state fills");
2612        // The generator holds the only reference now, so its own `destroy`
2613        // releases the set.
2614        DrawGenPipelines::release(pipelines, device);
2615        draws
2616    }
2617
2618    /// **The runs buffer costs two words per bucket per draw region — its run
2619    /// start and its task chunks' start — and one for the bucket's mesh, not a
2620    /// capacity per bucket.**
2621    ///
2622    /// Two generators of one capacity and very different bucket counts, and the
2623    /// size the device was actually asked for — read off the allocation rather
2624    /// than off [`DrawGen::runs_size`], which a build that sized the buffer some
2625    /// other way would still answer correctly. When each bucket reserved its own
2626    /// run this difference was `capacity` words a bucket, so the second
2627    /// generator's buffer was sixty-four times the first's.
2628    #[test]
2629    fn the_runs_buffer_grows_by_a_word_per_bucket() {
2630        const CAPACITY: u32 = 1000;
2631        let (recorder, device, queue) = open();
2632        let device = device.as_ref();
2633        let few = generator(device, queue, CAPACITY, 1);
2634        let many = generator(device, queue, CAPACITY, 64);
2635        let size = |draws: &DrawGen| {
2636            recorder
2637                .buffer_size(draws.runs(0))
2638                .expect("the runs buffer is live")
2639        };
2640
2641        let regions = u64::from(draw_gen::DRAW_REGIONS);
2642        assert_eq!(
2643            size(&many) - size(&few),
2644            u64::from(many.bucket_count() - few.bucket_count()) * (2 * regions + 1) * 4,
2645            "sixty-three more buckets cost sixty-three more words of run start and of chunk \
2646             start a region, and of mesh, and nothing else"
2647        );
2648        assert_eq!(
2649            size(&few),
2650            (3 * u64::from(CAPACITY) + regions + 1 + 2 * regions) * 4,
2651            "one bucket's generator holds the survivors, their routes, one capacity of runs, \
2652             one start per region, its mesh, and its chunk start and the region's end per region"
2653        );
2654        for draws in [&few, &many] {
2655            assert_eq!(
2656                draws.runs_size(),
2657                size(draws),
2658                "and the accessor a reader sizes a copy by is the size that was allocated"
2659            );
2660        }
2661
2662        few.destroy(device);
2663        many.destroy(device);
2664        recorder.assert_valid();
2665    }
2666
2667    /// **Every start word is past the runs and inside the buffer**, and bucket
2668    /// zero's run opens the run region.
2669    ///
2670    /// The words a constant block names are fixed at build and read by the
2671    /// geometry stages every frame, so two buckets sharing one would draw one
2672    /// bucket's run twice, and a word past the end is a read of nothing. The
2673    /// last region's chunk end, behind every start, mesh and chunk start, is
2674    /// the buffer's last.
2675    #[test]
2676    fn every_bucket_start_is_a_word_of_its_own_behind_the_runs() {
2677        const CAPACITY: u32 = 100;
2678        let (recorder, device, queue) = open();
2679        let device = device.as_ref();
2680        let draws = generator(device, queue, CAPACITY, 5);
2681
2682        assert_eq!(
2683            draws.runs_at(),
2684            2 * CAPACITY,
2685            "past the survivors and their routes"
2686        );
2687        let starts: Vec<u32> = (0..draws.bucket_count())
2688            .map(|bucket| draws.bucket_start_word(bucket))
2689            .collect();
2690        assert_eq!(
2691            starts,
2692            (0..5)
2693                .map(|bucket| 3 * CAPACITY + bucket)
2694                .collect::<Vec<_>>(),
2695            "one word per bucket, in bucket order, behind one capacity of runs"
2696        );
2697        assert_eq!(
2698            draws.region_start_word(1, 0),
2699            starts[starts.len() - 1] + 1,
2700            "region 1's starts directly behind region 0's"
2701        );
2702        assert_eq!(
2703            draws.bucket_mesh_word(0),
2704            draws.region_start_word(draw_gen::DRAW_REGIONS - 1, draws.bucket_count() - 1) + 1,
2705            "the buckets' meshes directly behind the last region's starts"
2706        );
2707        assert_eq!(
2708            draws.chunk_start_word(0, 0),
2709            draws.bucket_mesh_word(draws.bucket_count() - 1) + 1,
2710            "the chunk starts directly behind the last bucket's mesh"
2711        );
2712        assert_eq!(
2713            draws.chunk_start_word(1, 0),
2714            draws.chunk_start_word(0, draws.bucket_count()) + 1,
2715            "each region's chunk starts, its end word included, directly behind the one before"
2716        );
2717        assert_eq!(
2718            u64::from(draws.chunk_start_word(draw_gen::DRAW_REGIONS - 1, draws.bucket_count()) + 1)
2719                * 4,
2720            draws.runs_size(),
2721            "and the last region's chunk end is the buffer's last word"
2722        );
2723
2724        draws.destroy(device);
2725        recorder.assert_valid();
2726    }
2727
2728    /// **The scene that ran a 2 GiB device out of memory**, through the layout
2729    /// each bucket used to reserve and through the one it has now.
2730    ///
2731    /// 17219 instances and 938 buckets are the measured `ew` scene
2732    /// `docs/backlog.md`'s performance review records; the numbers here are its
2733    /// byte sizes, asserted rather than written into a comment, so the module
2734    /// docs' claim moves with the formula.
2735    #[test]
2736    fn the_measured_scene_pays_a_word_per_bucket_rather_than_a_capacity() {
2737        const CAPACITY: u32 = 17219;
2738        const BUCKETS: u32 = 938;
2739        let per_bucket_runs = u64::from(CAPACITY) * (1 + u64::from(BUCKETS)) * 4;
2740        let shared_runs = u64::from(
2741            draw_gen::runs_words(CAPACITY, BUCKETS, false).expect("the scene's layout addresses"),
2742        ) * 4;
2743        assert_eq!(
2744            per_bucket_runs, 64_674_564,
2745            "61.7 MiB a buffer, as measured"
2746        );
2747        assert_eq!(
2748            shared_runs, 262_936,
2749            "256.8 KiB a buffer, with a run start and a chunk start per bucket for every draw \
2750             region, a chunk end per region, and a mesh word per bucket"
2751        );
2752    }
2753
2754    /// **What the draw regions cost one frame in flight**, per generator and per
2755    /// renderer, in the measured scene of
2756    /// [`the_measured_scene_pays_a_word_per_bucket_rather_than_a_capacity`] —
2757    /// read off the allocations the device was asked for, so the figures a
2758    /// report quotes are these assertions' and not arithmetic beside them.
2759    ///
2760    /// A renderer holds a camera generator built for [`DrawMode::Occlusion`],
2761    /// [`crate::shadow::CASCADES`] built for [`DrawMode::Plain`] and
2762    /// [`crate::shadow::LIGHT_SLOTS`] built for [`DrawMode::Faces`] — the point
2763    /// light's face culls, whose face runs are most of the cost.
2764    #[test]
2765    fn the_regions_cost_what_their_layout_says_in_the_measured_scene() {
2766        const CAPACITY: u32 = 17219;
2767        const BUCKETS: u32 = 938;
2768        let (recorder, device, queue) = open();
2769        let device = device.as_ref();
2770        let size = |buffer| recorder.buffer_size(buffer).expect("live");
2771        let per_frame = |mode| {
2772            let draws = generator_in(device, queue, CAPACITY, BUCKETS, mode);
2773            let bytes = size(draws.runs(0)) + size(draws.args(0)) + size(draws.counts(0));
2774            draws.destroy(device);
2775            bytes
2776        };
2777        let [plain, occlusion, faces] =
2778            [DrawMode::Plain, DrawMode::Occlusion, DrawMode::Faces].map(per_frame);
2779        assert_eq!(
2780            plain, 296_776,
2781            "runs, one region of arguments and one of counts, and its flat dispatches"
2782        );
2783        assert_eq!(
2784            occlusion, 364_456,
2785            "three regions of arguments, counts and flat dispatches"
2786        );
2787        assert_eq!(
2788            faces, 913_076,
2789            "seven regions and six capacities of face runs"
2790        );
2791        // What a generator cost before there were regions: the runs with one
2792        // start per bucket, one argument structure and one count region.
2793        let before = (3 * u64::from(CAPACITY) + u64::from(BUCKETS)) * 4
2794            + u64::from(BUCKETS) * (draw_gen::DRAW_ARGS_SIZE as u64 + 16);
2795        assert_eq!(before, 244_148);
2796        let cascades = crate::shadow::CASCADES as u64;
2797        let slots = crate::shadow::LIGHT_SLOTS as u64;
2798        let renderer_before = before * (1 + cascades + slots);
2799        let renderer_after = occlusion + plain * cascades + faces * slots;
2800        assert_eq!(renderer_before, 1_709_036);
2801        assert_eq!(
2802            renderer_after, 4_610_312,
2803            "4.40 MiB a frame in flight, against 1.63 MiB before"
2804        );
2805        recorder.assert_valid();
2806    }
2807}