Skip to main content

crcbl_render/
sprite_pass.rs

1//! Sprite pass: instanced, world-space, alpha-blended quads cut out of sheets.
2//!
3//! ```text
4//! SpriteRenderer ──register_sheet──▶ uploads a sheet, returns a SheetId
5//!      │
6//!      ├──create_atlas───▶ a sheet of cells a rendered image is copied into,
7//!      │                   or host pixels written into; see [`atlas`] for
8//!      │                   slots and when one may be freed
9//!      │
10//!      ├──begin_frame──▶ batches consecutive sprites sharing a sheet, uploads
11//!      │                 one instance per sprite and one constant block per
12//!      │                 batch
13//!      │
14//!      └──add_pass────▶ inserts an alpha-blended render pass into the graph:
15//!                       one draw(0..6, 0..count) per batch, with the batch's
16//!                       place in the instance buffer arriving as a dynamic
17//!                       offset into the constants — see `add_pass` for why it
18//!                       cannot be the draw's own firstInstance
19//! ```
20//!
21//! # Why this exists
22//!
23//! `docs/plan/ROADMAP.md`'s S1B finding 1: **`ForwardRenderer` draws exactly one
24//! instance**, so both samples put their world through [`crate::ui_pass`] — a
25//! path that takes screen pixels, merges every quad into one vertex buffer and
26//! re-triangulates all of it on the CPU every frame. Breakout did it for forty
27//! bricks and flappy for its pipes, independently, for the same reason. This is
28//! the instance path that finding asks for: one instance per sprite, the quad
29//! from `SV_VertexID`, the per-sprite data from a storage buffer indexed by
30//! `SV_InstanceID`, and world coordinates rather than pixels.
31//!
32//! # One shader, no tier split
33//!
34//! `sprite.slang` takes its constants from a uniform buffer on *every* tier, so
35//! there is one artifact, one code path, and nothing here to pick between. A
36//! push constant would save one indirection per vertex where they exist, and
37//! cost a permutation axis: WebGPU has none at all, and an entry point reads
38//! either a push-constant block or a bound one, so a second shader source is the
39//! only way to serve both. [`crate::ui_pass`] paid that — a `ConstantDelivery`
40//! enum and a `ui_tier_b.slang` kept in step by hand — until it took this
41//! pass's trade instead.
42//!
43//! # Sample modes, and where the mode lives
44//!
45//! There is **one sampler**, linear, and every sheet's bind group names it. The
46//! mode is not in the bind group at all: it rides on the instance, in
47//! [`SpriteInstance::sheet`], alongside the sheet's size in texels.
48//!
49//! That is forced by what [`SampleMode::Pixel`] actually is.
50//! `crcbl_sprite::SampleMode`'s own docs say it is *not* nearest-neighbour: at a
51//! non-integer scale — a 320-wide field across a 1366-wide canvas — nearest
52//! makes some art pixels four screen pixels across and their neighbours five,
53//! and the unevenness crawls as the sprite moves. What it is instead is
54//! **sharp-bilinear**: sample *linearly*, with the UV bent so the blend happens
55//! only inside a one-fragment band at each texel boundary, plus the quad's
56//! screen rectangle snapped to whole device pixels so its edges cannot straddle
57//! a fragment. Both halves need a linear sampler and both need numbers — the
58//! sheet's texel size, and the target's size in pixels — that a
59//! `SamplerState` cannot supply. So the sampler stops being the carrier: one
60//! sampler, one pipeline, one shader, and two `float4` lanes on a buffer that
61//! was already written once per sprite per frame.
62//!
63//! [`SampleMode::Smooth`] samples the vertex stage's UV unchanged and is not
64//! snapped, which is what art that is not pixel art wants.
65//! `sprite.slang`'s `sharpen` carries the derivation of the band's width.
66//!
67//! # What the tests below are and are not
68//!
69//! They are recorder assertions: the instance bytes, the batching, the draw
70//! coverage, the teardown. The evidence that this draws the right *picture* is
71//! `crates/crcbl/tests/sprite_e2e`'s sprite goldens, which run the real pass
72//! against a real driver and read the pixels back — including the one assertion
73//! that pins the sharp-bilinear arithmetic, that a `Pixel` sprite at a whole
74//! scale is exactly flat inside each texel.
75
76use core::ops::Range;
77
78use crcbl_hal::{
79    BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
80    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BlendState, BufferDesc,
81    BufferHandle, BufferUsage, ColorTargetState, ColorWrites, DepthStencilState, Device,
82    FilterMode, Format, GraphicsPipelineDesc, GraphicsPipelineHandle, HalError, ImageViewType,
83    LoadOp, MemoryLocation, PipelineLayoutDesc, PipelineLayoutHandle, PrimitiveState, QueueHandle,
84    SampleType, SamplerAddressMode, SamplerDesc, SamplerHandle, ShaderEntry, ShaderModuleDesc,
85    ShaderStages, StoreOp, check_portable_storage_buffers,
86};
87use crcbl_shaders::{SPRITE, Stage};
88use crcbl_sprite::SampleMode;
89use glam::Mat4;
90
91use crate::counters::FrameCounters;
92use crate::graph::{ImageId, RenderGraph};
93use crate::texture::{UploadedTexture, upload_texture};
94
95pub mod atlas;
96
97pub use atlas::{ATLAS_FORMAT, ATLAS_FORMATS, AtlasDesc, AtlasSlot, SheetError, SlotCopy};
98
99// ---------------------------------------------------------------------------
100// The shader ABI
101// ---------------------------------------------------------------------------
102
103/// One sprite, in the byte layout `struct SpriteInstance` in
104/// `crates/crcbl-shaders/shaders/sprite.slang` declares.
105///
106/// Four `[f32; 4]`s: 64 bytes, no padding under any layout rule, and every
107/// element of the array 16-byte aligned because 64 is a multiple of 16. A
108/// `[f32; 2]` pair here would acquire alignment padding in the shader that this
109/// side would have to reproduce exactly, which is a layout that drifts silently.
110///
111/// Public because it is an ABI, and an ABI with one private spelling is an ABI
112/// nobody can check.
113#[repr(C)]
114#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
115pub struct SpriteInstance {
116    /// World-space rectangle: `[x, y, w, h]` with `x, y` the **minimum** corner.
117    /// Y is up.
118    pub rect: [f32; 4],
119    /// Normalised sheet UVs: `[u0, v0, u1, v1]` with `u0, v0` the **top-left**
120    /// corner, in image order.
121    pub uv: [f32; 4],
122    /// Straight-alpha RGBA multiplied into the sampled texel.
123    pub tint: [f32; 4],
124    /// The sheet's texel size, its sample mode, and **this sprite's rotation**:
125    /// `[width, height, mode, radians]`.
126    ///
127    /// The first three are [`sheet_lane`]'s packing; the fourth is
128    /// [`Sprite::rotation`], stamped on by [`Sprite::instance`] because it is the
129    /// one component of this lane that belongs to the sprite rather than to the
130    /// sheet.
131    ///
132    /// **The size and the mode are properties of the sheet, and they travel per
133    /// sprite anyway.** The shader cannot get them anywhere else: set 1 binds one
134    /// image and one sampler, and a shader has no way to ask a `SamplerState`
135    /// which filter it was created with. See `sprite.slang`'s
136    /// `SpriteInstance::sheet` for the alternatives that were not taken — a third
137    /// descriptor set, or a second pipeline — and why sixteen bytes on a buffer
138    /// that is written per frame anyway is the cheaper one.
139    ///
140    /// **The fourth component was padding.** `sprite.slang` read `sheet.z` for
141    /// the mode and handed `sheet.xyz` to the fragment stage, and nothing —
142    /// neither the Slang source, nor the compiled WGSL, nor the compiled SPIR-V,
143    /// where the only two uses of the loaded lane are a `CompositeExtract … 2`
144    /// and a `VectorShuffle … 0 1 2` — ever touched `w`. So the angle cost no
145    /// bytes: the instance is still four `float4`s and still
146    /// [`INSTANCE_STRIDE`] 64.
147    pub sheet: [f32; 4],
148}
149
150/// Bytes per instance. Named so the buffer arithmetic and the tests read the
151/// same number rather than each spelling 64.
152pub const INSTANCE_STRIDE: usize = size_of::<SpriteInstance>();
153
154/// [`SpriteInstance::sheet`]`[2]` for [`SampleMode::Pixel`]: sharp-bilinear
155/// sampling and a pixel-snapped quad.
156///
157/// The shader uses it as a `lerp` weight rather than as a branch, so the two
158/// values must be exactly `1.0` and exactly `0.0` and nothing else.
159pub const SAMPLE_PIXEL: f32 = 1.0;
160
161/// [`SpriteInstance::sheet`]`[2]` for [`SampleMode::Smooth`]: plain linear
162/// sampling of the UV the vertex stage produced, and no snapping.
163pub const SAMPLE_SMOOTH: f32 = 0.0;
164
165/// The [`SpriteInstance::sheet`] lane for a sheet of this size and mode.
166///
167/// A named function rather than a literal inside `register_sheet`, because it is
168/// the one place the mode is turned into a number and the shader's `lerp` weight
169/// is only a selection while that number is exactly 0 or 1.
170///
171/// The fourth component is left `0.0`: it is the *sprite's* rotation, not the
172/// sheet's, and [`Sprite::instance`] writes it when the instance is built.
173#[must_use]
174pub fn sheet_lane(width: u32, height: u32, mode: SampleMode) -> [f32; 4] {
175    let sample = match mode {
176        SampleMode::Pixel => SAMPLE_PIXEL,
177        SampleMode::Smooth => SAMPLE_SMOOTH,
178    };
179    [width as f32, height as f32, sample, 0.0]
180}
181
182/// The per-**batch** constant block, matching `struct SpriteConstants` in
183/// `sprite.slang`.
184///
185/// A uniform buffer on every tier — see this module's docs. One block per batch
186/// rather than one per frame, addressed by a dynamic offset: only
187/// [`base`](Self::base) differs between the blocks of one frame, and
188/// [`SpriteRenderer::add_pass`] explains why it cannot be the draw's
189/// `firstInstance` instead.
190#[repr(C)]
191#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
192pub struct SpriteConstants {
193    /// World → clip, column-major, exactly as [`Mat4::to_cols_array`] produces
194    /// it. `sprite.slang`'s header records why no transpose is needed.
195    pub view_proj: [f32; 16],
196    /// The target's size in device pixels.
197    ///
198    /// Read by the vertex stage, which needs the map from NDC to the pixel grid
199    /// to round a [`SampleMode::Pixel`] quad's corners onto it.
200    pub viewport: [f32; 2],
201    /// **This batch's first sprite, as an index into the frame's instance
202    /// buffer.** The vertex stage adds it to `SV_InstanceID`.
203    ///
204    /// Every draw this pass emits starts at instance 0, so `SV_InstanceID` means
205    /// the same thing on SPIR-V and on WGSL — which it does *not* when
206    /// `firstInstance` is non-zero. [`SpriteRenderer::add_pass`] and
207    /// `sprite.slang`'s header both carry the whole story.
208    pub base: u32,
209    /// Pads the block to 80 bytes. `std140` rounds a uniform block's size up to
210    /// a multiple of 16, and naga *enforces* that where a Vulkan driver would
211    /// quietly accept the short binding.
212    pub pad: u32,
213}
214
215/// Bytes in one constant block: 64 for the matrix, 8 for the viewport, 4 for the
216/// base and 4 of padding.
217///
218/// This is the *binding* size, not the stride between one batch's block and the
219/// next — see [`SpriteRenderer::constant_stride`], which rounds it up to the
220/// device's dynamic-offset alignment.
221pub const CONSTANTS_SIZE: u64 = size_of::<SpriteConstants>() as u64;
222
223// ---------------------------------------------------------------------------
224// The caller's vocabulary
225// ---------------------------------------------------------------------------
226
227/// A sheet registered with a [`SpriteRenderer`].
228///
229/// Opaque and per-renderer: an id from one renderer means nothing to another,
230/// and [`SpriteRenderer::begin_frame`] rejects one it does not know rather than
231/// binding whatever is at that index.
232///
233/// The field is `pub(crate)` rather than private so that [`crate::nine_slice`]
234/// and [`crate::layers`] — which build [`Sprite`]s without a device — can be
235/// tested against an id at all. It stays opaque to every caller outside this
236/// crate, and [`SpriteRenderer::begin_frame`] still refuses an id it did not
237/// hand out, so nothing about the guarantee changes.
238#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
239pub struct SheetId(pub(crate) u32);
240
241impl SheetId {
242    /// The index this id addresses, for tests and diagnostics.
243    #[must_use]
244    pub const fn index(self) -> u32 {
245        self.0
246    }
247}
248
249/// A sheet image to register: its pixels, its size, and how it is sampled.
250///
251/// A struct rather than five positional arguments, for the reason
252/// [`crate::texture`]'s `UploadArgs` is one: two adjacent `u32`s that can be
253/// swapped at the call site are a bug the compiler cannot see.
254#[derive(Clone, Copy, Debug)]
255pub struct SheetDesc<'a> {
256    /// Names the image, its view and its staging buffer, so a capture says which
257    /// sheet an upload belonged to.
258    pub label: &'a str,
259    /// The sheet image's width in texels — `crcbl_sprite::Sheet::width`.
260    pub width: u32,
261    /// The sheet image's height in texels — `crcbl_sprite::Sheet::height`.
262    pub height: u32,
263    /// Which sampler this sheet's bind group names.
264    pub sample: SampleMode,
265    /// Decoded, tightly packed, straight-alpha RGBA8 — exactly
266    /// `width * height * 4` bytes.
267    pub pixels: &'a [u8],
268}
269
270/// One sprite to draw this frame.
271///
272/// The submission order of a `&[Sprite]` **is** the compositing order. Nothing
273/// here sorts, by sheet or by anything else: a caller that interleaves two
274/// sheets gets two batches, which is the price of the ordering it asked for.
275///
276/// Layer and parallax ordering live above this, in [`crate::layers`]: a
277/// [`LayerStack`](crate::layers::LayerStack) groups sprites into bands and
278/// flattens them back to front when the *caller* asks it to, so the frame this
279/// slice receives is still exactly the order it was handed.
280///
281/// # Building one, and why there is no literal
282///
283/// [`Sprite::new`] takes the three things a sprite cannot be drawn without — the
284/// sheet, the rectangle and the UVs — and the two that mean something specific
285/// when left alone arrive through [`with_rotation`](Self::with_rotation) and
286/// [`with_tint`](Self::with_tint).
287///
288/// The type is `#[non_exhaustive]`, so a caller outside this crate cannot write
289/// the struct literal or use functional-update syntax. That is deliberate:
290/// `rotation` was added to a five-field literal and broke every construction in
291/// the workspace, none of which had anything to do with turning, and the next
292/// field would break them all again. The fields stay `pub`, so reading and
293/// assigning one is unchanged; it is only *construction* that now goes through
294/// the constructor, which is what makes the field after this one a non-event.
295#[derive(Clone, Copy, Debug, PartialEq)]
296#[non_exhaustive]
297pub struct Sprite {
298    /// Which registered sheet this sprite samples.
299    pub sheet: SheetId,
300    /// World-space rectangle **before rotation**: `[x, y, w, h]`, minimum corner
301    /// first, Y up.
302    pub rect: [f32; 4],
303    /// Rotation in **radians, counter-clockwise, about the centre of
304    /// [`rect`](Self::rect)** — `0.0` for a sprite that does not turn.
305    ///
306    /// # The pivot is the centre, and only the centre
307    ///
308    /// A ship, a rock and a bullet all turn about themselves, so the centre is
309    /// the case every rotating sprite actually wants. An arbitrary pivot is two
310    /// more floats on a lane that has one component left, and it is not needed to
311    /// express one: rotating a rectangle about an outside point gives the same
312    /// rectangle turned about its own centre and then translated, so a caller
313    /// that wants an orbit computes the translated `rect` and gets it exactly.
314    /// **A pivot offset is deliberately not half-built here** — see
315    /// `docs/backlog.md`.
316    ///
317    /// # What it does to [`SampleMode`]
318    ///
319    /// Nothing, where it is `0.0`: `sprite.slang` branches on the angle and the
320    /// zero case is the arithmetic that was there before rotation existed, not a
321    /// general formula that happens to reduce to it, so a `Smooth` or an
322    /// unrotated `Pixel` sprite is bit-for-bit what it always was.
323    ///
324    /// Where it is not zero, [`SampleMode::Pixel`]'s snap stops rounding each
325    /// corner — a rotated quad has no axis-aligned rectangle to round onto, and
326    /// rounding its corners independently shears it — and instead translates the
327    /// whole quad rigidly so its *centre* lands on the pixel grid. Sharp-bilinear
328    /// itself needs no change at all; `sprite.slang`'s `sharpen` records why.
329    pub rotation: f32,
330    /// Normalised sheet UVs: `[u0, v0, u1, v1]`, top-left corner first.
331    pub uv: [f32; 4],
332    /// Straight-alpha RGBA multiplied into the sampled texel. `[1.0; 4]` is
333    /// "the sheet as authored".
334    pub tint: [f32; 4],
335}
336
337impl Sprite {
338    /// A sprite that draws `uv` of `sheet` into `rect`, unrotated and untinted.
339    ///
340    /// [`rotation`](Self::rotation) starts at `0.0` and [`tint`](Self::tint) at
341    /// `[1.0; 4]` — both the value that means "do nothing", so a sprite built
342    /// here and drawn is the sheet as authored, at the rectangle asked for.
343    ///
344    /// # Two `[f32; 4]`s the compiler cannot tell apart
345    ///
346    /// `rect` is **world units**, minimum corner first and Y up; `uv` is
347    /// **normalised sheet coordinates**, top-left corner first. Swapping them at
348    /// a call site compiles and draws a wrong picture — the hazard
349    /// [`SheetDesc`] became a struct to avoid. Nothing here can catch it. What
350    /// does is the golden images under `crates/crcbl/tests/golden/`, and the
351    /// sample suites that assert on a
352    /// resolved sprite's `rect` and `uv` — so a sprite call site is not a place
353    /// to take the argument order on trust.
354    #[must_use]
355    pub const fn new(sheet: SheetId, rect: [f32; 4], uv: [f32; 4]) -> Self {
356        Self {
357            sheet,
358            rect,
359            rotation: 0.0,
360            uv,
361            tint: [1.0; 4],
362        }
363    }
364
365    /// The same sprite, turned by `radians` — [`rotation`](Self::rotation)'s
366    /// units, pivot and effect on [`SampleMode`] in full.
367    #[must_use]
368    pub const fn with_rotation(mut self, radians: f32) -> Self {
369        self.rotation = radians;
370        self
371    }
372
373    /// The same sprite, with [`tint`](Self::tint) multiplied into every texel it
374    /// samples.
375    #[must_use]
376    pub const fn with_tint(mut self, tint: [f32; 4]) -> Self {
377        self.tint = tint;
378        self
379    }
380
381    /// The bytes the shader reads for this sprite.
382    ///
383    /// `sheet` is the [`sheet_lane`] of the sheet this sprite names, which the
384    /// [`Sprite`] itself does not carry — a caller writes a [`SheetId`] and the
385    /// renderer holds the size and the mode it was registered with, so there is
386    /// exactly one place either can be wrong.
387    ///
388    /// The lane's fourth component is *not* the one `sheet_lane` produced: it is
389    /// this sprite's [`rotation`](Self::rotation), because the angle is the one
390    /// thing in that `float4` that belongs to the sprite. A zero rotation writes
391    /// the `0.0` that was already there, so the bytes are unchanged.
392    #[must_use]
393    pub const fn instance(&self, sheet: [f32; 4]) -> SpriteInstance {
394        SpriteInstance {
395            rect: self.rect,
396            uv: self.uv,
397            tint: self.tint,
398            sheet: [sheet[0], sheet[1], sheet[2], self.rotation],
399        }
400    }
401}
402
403// ---------------------------------------------------------------------------
404// The renderer
405// ---------------------------------------------------------------------------
406
407/// How many frames of instance and constant buffers to keep in flight.
408const FRAMES_IN_FLIGHT: usize = 2;
409
410/// Starting size of the instance ring, in bytes. Sixteen sprites; a frame
411/// that wants more grows it once.
412const INITIAL_RING_BYTES: u64 = 1024;
413
414/// How many per-batch constant blocks the ring starts with.
415///
416/// Eight, because a batch is a *sheet change* and not a sprite: both shipped
417/// samples draw four, so eight is a frame's worth of headroom for one 2 KiB
418/// allocation on Tier B and 1 KiB on Tier A. A frame with more grows it once.
419const INITIAL_BATCH_BLOCKS: u64 = 8;
420
421/// Set 0: the frame. Constants at binding 0, instances at binding 1.
422const FRAME_SET: u32 = 0;
423
424/// Set 1: the sheet. Image view at binding 0, sampler at binding 1.
425const SHEET_SET: u32 = 1;
426
427/// Vertices in the quad the vertex stage expands from `SV_VertexID`.
428///
429/// Six, not four plus an index buffer — `sprite.slang`'s `CORNERS` records the
430/// trade.
431const QUAD_VERTICES: u32 = 6;
432
433/// Triangles one instance covers: [`QUAD_VERTICES`] of a triangle list.
434///
435/// A constant rather than a division at the one place it is used, because it is
436/// the fact [`SpriteRenderer::counters`] reports and the pipeline's
437/// `PrimitiveState::default()` — a triangle list — is what makes it true.
438const TRIANGLES_PER_QUAD: u64 = QUAD_VERTICES as u64 / 3;
439
440/// The size the instance ring grows to when `needed` bytes no longer fit.
441///
442/// Doubling rather than fitting exactly, so a scene that gains a sprite a frame
443/// reallocates a handful of times rather than every frame.
444fn grown(needed: u64) -> u64 {
445    needed
446        .max(INITIAL_RING_BYTES)
447        .next_power_of_two()
448        .next_multiple_of(256)
449}
450
451/// One consecutive run of sprites sharing a sheet: exactly one draw call.
452#[derive(Clone, Debug, PartialEq, Eq)]
453struct Batch {
454    sheet: SheetId,
455    /// Where this batch's sprites are in the **frame's** instance buffer.
456    ///
457    /// Deliberately *not* what `draw` is handed — see
458    /// [`SpriteRenderer::add_pass`]. The draw covers `0..count()`, and
459    /// `instances.start` reaches the shader as [`SpriteConstants::base`].
460    instances: Range<u32>,
461    /// Byte offset of this batch's constant block, and the dynamic offset set 0
462    /// is bound with. `n * SpriteRenderer::constant_stride()`.
463    constant_offset: u32,
464}
465
466impl Batch {
467    /// How many instances this batch draws.
468    const fn count(&self) -> u32 {
469        self.instances.end - self.instances.start
470    }
471}
472
473/// A registered sheet: the uploaded image, the bind group naming it, and the
474/// instance lane every sprite drawn from it carries.
475#[derive(Clone, Copy, Debug)]
476struct RegisteredSheet {
477    texture: UploadedTexture,
478    group: BindGroupHandle,
479    /// [`sheet_lane`] for this sheet's size and [`SampleMode`], computed once at
480    /// registration and copied into every instance that names it.
481    lane: [f32; 4],
482}
483
484/// The sprite renderer.
485///
486/// Created once, sheets registered once, then `begin_frame` + `add_pass` per
487/// frame.
488#[derive(Debug)]
489pub struct SpriteRenderer {
490    // Pipeline state
491    pipeline_layout: PipelineLayoutHandle,
492    pipeline: GraphicsPipelineHandle,
493    frame_layout: BindGroupLayoutHandle,
494    sheet_layout: BindGroupLayoutHandle,
495
496    /// **One sampler, linear, for every sheet whatever its [`SampleMode`].**
497    ///
498    /// Slice 3 created a nearest one beside it and gave it to
499    /// [`SampleMode::Pixel`]; sharp-bilinear *is* linear sampling of a bent UV,
500    /// so a nearest sampler would flatten the bend and undo the whole thing. The
501    /// mode now travels on the instance instead — see [`SpriteInstance::sheet`].
502    sampler: SamplerHandle,
503
504    /// Registered sheets, indexed by [`SheetId::index`].
505    sheets: Vec<RegisteredSheet>,
506    /// The sheets that are atlases, with their cells — see [`atlas`]. Each
507    /// one's image is also in [`sheets`](Self::sheets), which is what
508    /// destroys it.
509    atlases: Vec<atlas::Atlas>,
510    /// The staging buffers [`write_slot`](Self::write_slot) copies from, kept
511    /// until the frames that copy from them have retired.
512    atlas_staging: atlas::WriteStaging,
513    /// The queue every sheet upload is submitted to.
514    ///
515    /// Taken once at construction rather than per `register_sheet`, so two
516    /// sheets cannot be uploaded on two different queues and then be read by one
517    /// pass — which the graph's barriers would not describe.
518    queue: QueueHandle,
519
520    // Per frame in flight.
521    frame_groups: Vec<BindGroupHandle>,
522    instance_buffers: Vec<BufferHandle>,
523    constant_buffers: Vec<BufferHandle>,
524    /// How many **bytes** each instance buffer holds. Compared against the bytes
525    /// a frame needs — never against a sprite *count*, which is the comparison
526    /// that made [`crate::ui_pass`] destroy and recreate both its rings and its
527    /// bind group on every steady-state frame.
528    instance_capacity: Vec<u64>,
529    /// How many **bytes** each constant buffer holds, on the same terms. The
530    /// constants are one [`constant_stride`](Self::constant_stride)-sized block
531    /// per batch now, so this grows with the number of batches a frame draws.
532    constant_capacity: Vec<u64>,
533    /// Bytes between one batch's constant block and the next.
534    ///
535    /// [`CONSTANTS_SIZE`] rounded up to the device's
536    /// `min_uniform_buffer_offset_alignment`, because a dynamic offset must be a
537    /// multiple of it — 256 on WebGPU, 64 on a typical desktop Vulkan driver.
538    /// Read from the device at construction rather than assumed: a hard-coded
539    /// 256 wastes memory on Tier A and a hard-coded 64 is a validation error on
540    /// Tier B.
541    ///
542    /// `u32` because that is what `bind_group` takes a dynamic offset as, so the
543    /// conversion happens once here rather than at every bind.
544    constant_stride: u32,
545    /// This frame's draw calls, in submission order.
546    batches: Vec<Vec<Batch>>,
547    frame: usize,
548
549    /// The format the pipeline was built for. Dynamic rendering checks the
550    /// pipeline's colour-target format against the attachment at pass-begin, so
551    /// a swapchain in a different format needs a different pipeline.
552    target_format: Format,
553
554    destroyed: bool,
555}
556
557impl SpriteRenderer {
558    /// Creates the sprite pipeline, both samplers, and the per-frame buffers.
559    ///
560    /// `target_format` must be the format of the image the pass composites onto
561    /// — normally the swapchain's. As [`crate::ui_pass::UiRenderer::new`], a
562    /// pipeline built for the wrong one fails the frame at pass-begin rather
563    /// than this constructor.
564    ///
565    /// No sheets are registered; a renderer with none draws nothing and is not
566    /// an error.
567    ///
568    /// # Errors
569    ///
570    /// [`HalError`] from any seam call. A failure part-way through releases
571    /// everything already created, so a caller that retries or exits leaves
572    /// nothing behind.
573    pub fn new(
574        device: &dyn Device,
575        queue: QueueHandle,
576        target_format: Format,
577    ) -> Result<Self, HalError> {
578        let mut rollback = Rollback::default();
579        match Self::build(device, queue, target_format, &mut rollback) {
580            Ok(renderer) => Ok(renderer),
581            Err(error) => {
582                rollback.run(device);
583                Err(error)
584            }
585        }
586    }
587
588    /// The body of [`SpriteRenderer::new`], recording what it has created into
589    /// `rollback` as it goes.
590    fn build(
591        device: &dyn Device,
592        queue: QueueHandle,
593        target_format: Format,
594        rollback: &mut Rollback,
595    ) -> Result<Self, HalError> {
596        let sampler = device.create_sampler(&SamplerDesc {
597            label: Some("sprite linear"),
598            mag_filter: FilterMode::Linear,
599            min_filter: FilterMode::Linear,
600            mip_filter: FilterMode::Nearest,
601            address_mode: [SamplerAddressMode::ClampToEdge; 3],
602            ..SamplerDesc::default()
603        })?;
604        rollback.samplers.push(sampler);
605
606        let frame_layout_entries = [
607            BindGroupLayoutEntry {
608                binding: 0,
609                visibility: ShaderStages::VERTEX,
610                // `dynamic: true`, unlike `ui_pass`'s equivalent binding.
611                // This is the one thing that lets a batch say where its
612                // instances start without the draw's `firstInstance` — which
613                // `add_pass` explains cannot be used, because the two
614                // shading languages disagree about what it does to
615                // `SV_InstanceID`. One buffer, one block per batch, one
616                // offset at bind time.
617                kind: BindingKind::UniformBuffer { dynamic: true },
618                count: 1,
619                flags: BindingFlags::empty(),
620            },
621            BindGroupLayoutEntry {
622                binding: 1,
623                visibility: ShaderStages::VERTEX,
624                kind: BindingKind::StorageBuffer {
625                    read_only: true,
626                    dynamic: false,
627                    stride: INSTANCE_STRIDE as u32,
628                },
629                count: 1,
630                flags: BindingFlags::empty(),
631            },
632        ];
633        let frame_desc = BindGroupLayoutDesc {
634            label: Some("sprite frame"),
635            entries: &frame_layout_entries,
636        };
637
638        let sheet_layout_entries = [
639            BindGroupLayoutEntry {
640                binding: 0,
641                visibility: ShaderStages::FRAGMENT,
642                kind: BindingKind::SampledImage {
643                    view_type: ImageViewType::D2,
644                    sample_type: SampleType::Float,
645                },
646                count: 1,
647                flags: BindingFlags::empty(),
648            },
649            BindGroupLayoutEntry {
650                binding: 1,
651                visibility: ShaderStages::FRAGMENT,
652                kind: BindingKind::Sampler { comparison: false },
653                count: 1,
654                flags: BindingFlags::empty(),
655            },
656        ];
657        let sheet_desc = BindGroupLayoutDesc {
658            label: Some("sprite sheet"),
659            entries: &sheet_layout_entries,
660        };
661
662        // **Both sets in one call, in the order the pipeline layout below names
663        // them.** The guaranteed limit is a sum over a whole pipeline layout
664        // rather than a per-set budget, so checking either set on its own would
665        // under-count — see [`crcbl_hal::check_portable_storage_buffers`].
666        check_portable_storage_buffers(Some("sprite"), &[&frame_desc, &sheet_desc])?;
667        let frame_layout = device.create_bind_group_layout(&frame_desc)?;
668        rollback.bind_group_layouts.push(frame_layout);
669        let sheet_layout = device.create_bind_group_layout(&sheet_desc)?;
670        rollback.bind_group_layouts.push(sheet_layout);
671
672        // A dynamic offset must be a multiple of the device's alignment, and the
673        // block has to fit inside one stride. `u32` because that is what a
674        // dynamic offset is; an alignment that did not fit would be a device
675        // nobody can bind a dynamic uniform on at all.
676        let alignment = device.caps().limits.min_uniform_buffer_offset_alignment;
677        let constant_stride =
678            u32::try_from(CONSTANTS_SIZE.next_multiple_of(alignment)).map_err(|_| {
679                HalError::InvalidDescriptor(format!(
680                    "min_uniform_buffer_offset_alignment is {alignment}, which no dynamic \
681                     offset can express"
682                ))
683            })?;
684        let initial_constant_bytes = u64::from(constant_stride) * INITIAL_BATCH_BLOCKS;
685
686        let mut frame_groups = Vec::with_capacity(FRAMES_IN_FLIGHT);
687        let mut instance_buffers = Vec::with_capacity(FRAMES_IN_FLIGHT);
688        let mut constant_buffers = Vec::with_capacity(FRAMES_IN_FLIGHT);
689        let mut instance_capacity = Vec::with_capacity(FRAMES_IN_FLIGHT);
690        let mut constant_capacity = Vec::with_capacity(FRAMES_IN_FLIGHT);
691        let mut batches = Vec::with_capacity(FRAMES_IN_FLIGHT);
692        for _ in 0..FRAMES_IN_FLIGHT {
693            let instances = device.create_buffer(&BufferDesc {
694                label: Some("sprite instances"),
695                size: INITIAL_RING_BYTES,
696                usage: BufferUsage::STORAGE,
697                memory: MemoryLocation::HostUpload,
698            })?;
699            rollback.buffers.push(instances);
700            let constants = device.create_buffer(&BufferDesc {
701                label: Some("sprite constants"),
702                size: initial_constant_bytes,
703                usage: BufferUsage::UNIFORM,
704                memory: MemoryLocation::HostUpload,
705            })?;
706            rollback.buffers.push(constants);
707            let group = device.create_bind_group(&BindGroupDesc {
708                label: Some("sprite frame"),
709                layout: frame_layout,
710                entries: &frame_entries(constants, instances),
711                variable_count: None,
712            })?;
713            rollback.bind_groups.push(group);
714
715            instance_buffers.push(instances);
716            constant_buffers.push(constants);
717            frame_groups.push(group);
718            instance_capacity.push(INITIAL_RING_BYTES);
719            constant_capacity.push(initial_constant_bytes);
720            batches.push(Vec::new());
721        }
722
723        let set_layouts = [frame_layout, sheet_layout];
724        let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
725            label: Some("sprite"),
726            bind_group_layouts: &set_layouts,
727            // None on every tier. That is the whole of "one shader, no tier
728            // split" on this side of the seam.
729            push_constants: None,
730        })?;
731        rollback.pipeline_layouts.push(pipeline_layout);
732
733        // Entry points resolved before the module exists, as in `ui_pass`: a
734        // manifest that disagreed with the artifact would otherwise fail inside
735        // the descriptor literal with the module created and nothing holding it.
736        let vertex_entry = entry(Stage::Vertex)?;
737        let fragment_entry = entry(Stage::Fragment)?;
738        let module = device.create_shader_module(&ShaderModuleDesc {
739            label: Some("sprite.slang"),
740            spirv: SPRITE.spirv(),
741            wgsl: SPRITE.wgsl(),
742            msl: SPRITE.msl(),
743            // One container per entry point, both of them, in one module; see
744            // `crcbl_render::forward`.
745            dxil: &SPRITE.dxil_containers(),
746        })?;
747        let targets = [color_target(target_format)];
748        let created = device.create_graphics_pipeline(&GraphicsPipelineDesc {
749            label: Some("sprite"),
750            layout: pipeline_layout,
751            vertex: ShaderEntry {
752                module,
753                entry_point: vertex_entry,
754            },
755            fragment: Some(ShaderEntry {
756                module,
757                entry_point: fragment_entry,
758            }),
759            primitive: PrimitiveState::default(), // TriangleList, no culling
760            depth_stencil: SPRITE_DEPTH_STENCIL,
761            multisample: Default::default(),
762            color_targets: &targets,
763        });
764        device.destroy_shader_module(module);
765        let pipeline = created?;
766        rollback.pipelines.push(pipeline);
767
768        Ok(Self {
769            pipeline_layout,
770            pipeline,
771            frame_layout,
772            sheet_layout,
773            sampler,
774            sheets: Vec::new(),
775            atlases: Vec::new(),
776            atlas_staging: atlas::WriteStaging::default(),
777            queue,
778            frame_groups,
779            instance_buffers,
780            constant_buffers,
781            instance_capacity,
782            constant_capacity,
783            constant_stride,
784            batches,
785            frame: 0,
786            target_format,
787            destroyed: false,
788        })
789    }
790
791    /// The format the sprite pass composites into.
792    #[must_use]
793    pub const fn target_format(&self) -> Format {
794        self.target_format
795    }
796
797    /// Bytes between one batch's constant block and the next, and therefore the
798    /// dynamic offset [`add_pass`](Self::add_pass) binds set 0 with for batch
799    /// `n`: `n * constant_stride()`.
800    ///
801    /// [`CONSTANTS_SIZE`] rounded up to the device's
802    /// `min_uniform_buffer_offset_alignment`. Public so a test can predict the
803    /// offsets rather than restate a number the device chose.
804    #[must_use]
805    pub const fn constant_stride(&self) -> u32 {
806        self.constant_stride
807    }
808
809    /// How many sheets are registered.
810    #[must_use]
811    pub fn sheet_count(&self) -> usize {
812        self.sheets.len()
813    }
814
815    /// What the last [`begin_frame`](Self::begin_frame) left this pass to draw.
816    ///
817    /// **Read off the batches themselves**, which is the same list
818    /// [`add_pass`](Self::add_pass) walks — so a draw this reports is a draw the
819    /// frame records, and a batching change moves both together. That is the
820    /// point of it existing: topic 40's complaint is that a
821    /// consumer keeping its own copy of a count is a copy that drifts, and this
822    /// is the pass's own answer.
823    ///
824    /// Every counter is known here. Nothing on this path draws indirectly and
825    /// nothing culls, so [`FrameCounters::drawn`] equals
826    /// [`FrameCounters::instances`] and the triangles are exact:
827    /// [`add_pass`](Self::add_pass) expands the same triangle-list quad per
828    /// instance, so the count is that quad's own and not an estimate.
829    ///
830    /// A frame with no sprites reports nothing recorded, because
831    /// [`add_pass`](Self::add_pass) adds no pass at all.
832    #[must_use]
833    pub fn counters(&self) -> FrameCounters {
834        let batches = &self.batches[self.frame];
835        let instances = u64::from(batches.iter().map(Batch::count).sum::<u32>());
836        FrameCounters {
837            draws: batches.len() as u64,
838            instances,
839            drawn: Some(instances),
840            triangles: Some(instances * TRIANGLES_PER_QUAD),
841            // A quad is not cluster geometry, so this pass drew no clusters and
842            // says so as a number. `None` would be "nothing counted", which
843            // would make the panel's cluster row unknown on every sprite frame.
844            clusters: Some(0),
845            // Nothing here came off the GPU: these are this frame's own counts,
846            // on the one lag the whole section shares.
847            cull_frame: None,
848        }
849    }
850
851    /// Uploads a sheet image and returns the id a [`Sprite`] names it by.
852    ///
853    /// The upload is a staging copy that blocks on `wait_idle` — a **startup**
854    /// path, like [`crate::ui_pass`]'s glyph atlas and [`crate::forward`]'s
855    /// cube, and like both it must not be called between `begin_frame` and the
856    /// graph's `execute`.
857    ///
858    /// The image is created as [`Format::Rgba8UnormSrgb`], so the sampler
859    /// decodes to linear and the blend below happens in linear light. Sprite art
860    /// comes out of a PNG sRGB-encoded, and the target this composites onto is
861    /// an sRGB swapchain; taking the decode off the sampler would mean blending
862    /// encoded values, which darkens every half-transparent edge.
863    ///
864    /// # Errors
865    ///
866    /// [`HalError`] from the upload or from bind-group creation. `pixels` must
867    /// be exactly `width * height * 4` bytes; [`upload_texture`] says so by name
868    /// when it is not. A failure leaves nothing behind and no id allocated.
869    pub fn register_sheet(
870        &mut self,
871        device: &dyn Device,
872        desc: &SheetDesc<'_>,
873    ) -> Result<SheetId, HalError> {
874        let texture = upload_texture(
875            device,
876            self.queue,
877            desc.label,
878            Format::Rgba8UnormSrgb,
879            desc.width,
880            desc.height,
881            desc.pixels,
882        )?;
883        self.adopt(
884            device,
885            desc.label,
886            texture,
887            (desc.width, desc.height),
888            desc.sample,
889        )
890    }
891
892    /// Makes an already-created sheet image drawable: its bind group, its
893    /// instance lane, and the id that names it.
894    ///
895    /// The half [`register_sheet`](Self::register_sheet) and
896    /// [`create_atlas`](Self::create_atlas) share. It owns `texture` from the
897    /// moment it is called: on failure the image is destroyed here, and no id
898    /// is allocated.
899    fn adopt(
900        &mut self,
901        device: &dyn Device,
902        label: &str,
903        texture: UploadedTexture,
904        extent: (u32, u32),
905        sample: SampleMode,
906    ) -> Result<SheetId, HalError> {
907        // Before the group exists, so a refusal has only the image to give back.
908        let Ok(index) = u32::try_from(self.sheets.len()) else {
909            texture.destroy(device);
910            return Err(HalError::InvalidDescriptor(
911                "more than u32::MAX sprite sheets".to_string(),
912            ));
913        };
914        let group = match device.create_bind_group(&BindGroupDesc {
915            label: Some(label),
916            layout: self.sheet_layout,
917            entries: &[
918                BindGroupEntry {
919                    binding: 0,
920                    array_index: 0,
921                    resource: BindingResource::ImageView(texture.view),
922                },
923                BindGroupEntry {
924                    binding: 1,
925                    array_index: 0,
926                    resource: BindingResource::Sampler(self.sampler),
927                },
928            ],
929            variable_count: None,
930        }) {
931            Ok(group) => group,
932            Err(error) => {
933                // The image exists by now, and nothing else will ever hold it.
934                texture.destroy(device);
935                return Err(error);
936            }
937        };
938
939        self.sheets.push(RegisteredSheet {
940            texture,
941            group,
942            lane: sheet_lane(extent.0, extent.1, sample),
943        });
944        Ok(SheetId(index))
945    }
946
947    /// [`register_sheet`](Self::register_sheet) for a decoded
948    /// [`Loaded`](crcbl_sprite::load::Loaded).
949    ///
950    /// The mapping from what a sheet decoded to onto what an upload needs —
951    /// size off the image, sampler off the sheet, pixels off the image — is the
952    /// engine's to know, and it was written out at every site that loaded art
953    /// through [`crcbl_sprite::load`]. The two halves come apart in the source
954    /// (`Loaded::image` carries the size the *picture* is, `Loaded::sheet` the
955    /// size the *sidecar claims*), and `load` is what already reconciled them,
956    /// so reading the width back off the sheet here would undo that check.
957    ///
958    /// # Errors
959    ///
960    /// Whatever [`register_sheet`](Self::register_sheet) returns.
961    pub fn register_baked(
962        &mut self,
963        device: &dyn Device,
964        label: &str,
965        loaded: &crcbl_sprite::load::Loaded,
966    ) -> Result<SheetId, HalError> {
967        self.register_sheet(
968            device,
969            &SheetDesc {
970                label,
971                width: loaded.image.width,
972                height: loaded.image.height,
973                sample: loaded.sheet.sample,
974                pixels: &loaded.image.pixels,
975            },
976        )
977    }
978
979    /// Uploads this frame's sprites and constants, and advances the ring.
980    ///
981    /// `view_projection` is world → clip, normally
982    /// [`Camera::view_projection`](crate::Camera::view_projection) with an
983    /// [`Orthographic`](crate::Projection::Orthographic) projection. `extent` is
984    /// the target's size in pixels.
985    ///
986    /// **`extent` is taken here and not in [`add_pass`](Self::add_pass)**, which
987    /// is the one place this pass departs from [`crate::ui_pass`]'s shape.
988    /// `ui_pass` takes it at `add_pass` because that is its *only* source of the
989    /// constants; here `view_projection` is already computed from an aspect
990    /// ratio, and an extent taken a second time somewhere else is a second thing
991    /// that can disagree with the matrix it has to match. The graph sets the
992    /// viewport and the scissor from the pass's own render area either way, so
993    /// `add_pass` has no use for it.
994    ///
995    /// Sprites are batched into draws here, not at `add_pass`: consecutive
996    /// sprites sharing a sheet become one draw, and **nothing is sorted**.
997    ///
998    /// # Errors
999    ///
1000    /// [`HalError::InvalidDescriptor`] if any sprite names a sheet this renderer
1001    /// did not register — refused by name rather than binding whatever group is
1002    /// at that index. [`HalError`] from any buffer call otherwise.
1003    pub fn begin_frame(
1004        &mut self,
1005        device: &dyn Device,
1006        sprites: &[Sprite],
1007        view_projection: Mat4,
1008        extent: (u32, u32),
1009    ) -> Result<(), HalError> {
1010        // Checked before anything is written, so a bad sheet id leaves the
1011        // previous frame's buffers untouched rather than half-overwritten.
1012        for (index, sprite) in sprites.iter().enumerate() {
1013            if sprite.sheet.index() as usize >= self.sheets.len() {
1014                return Err(HalError::InvalidDescriptor(format!(
1015                    "sprite {index} names sheet {}, but only {} are registered with this renderer",
1016                    sprite.sheet.index(),
1017                    self.sheets.len()
1018                )));
1019            }
1020        }
1021
1022        self.frame = (self.frame + 1) % FRAMES_IN_FLIGHT;
1023        let idx = self.frame;
1024        self.atlas_staging.advance(device);
1025
1026        // The sheet's size and mode are stamped onto the instance here, from the
1027        // sheet the sprite named — the loop above has already established that
1028        // every one of those indices is registered.
1029        let instances: Vec<SpriteInstance> = sprites
1030            .iter()
1031            .map(|sprite| sprite.instance(self.sheets[sprite.sheet.index() as usize].lane))
1032            .collect();
1033
1034        // Grow only when this frame genuinely needs more room. Both sides are
1035        // **bytes**.
1036        let needed = (instances.len() * INSTANCE_STRIDE) as u64;
1037        let mut buffer_replaced = false;
1038        if needed > self.instance_capacity[idx] {
1039            let size = grown(needed);
1040            // Create before destroying: a creation that fails must not leave a
1041            // destroyed handle in the struct for `destroy` to hand back twice.
1042            let fresh = device.create_buffer(&BufferDesc {
1043                label: Some("sprite instances"),
1044                size,
1045                usage: BufferUsage::STORAGE,
1046                memory: MemoryLocation::HostUpload,
1047            })?;
1048            device.destroy_buffer(core::mem::replace(&mut self.instance_buffers[idx], fresh));
1049            self.instance_capacity[idx] = size;
1050            buffer_replaced = true;
1051        }
1052
1053        if !instances.is_empty() {
1054            let bytes: &[u8] = bytemuck::cast_slice(&instances);
1055            device.write_buffer(self.instance_buffers[idx], 0, bytes)?;
1056        }
1057
1058        // Batched here rather than at `add_pass`, and now before the constants
1059        // are written rather than after: there is one constant block per batch,
1060        // so the batching has to have happened before there is anything to write.
1061        let batches = batch(sprites, self.constant_stride);
1062        let blocks = constant_blocks(view_projection, extent, &batches, self.constant_stride);
1063        if blocks.len() as u64 > self.constant_capacity[idx] {
1064            let size = grown_constants(blocks.len() as u64, self.constant_stride);
1065            let fresh = device.create_buffer(&BufferDesc {
1066                label: Some("sprite constants"),
1067                size,
1068                usage: BufferUsage::UNIFORM,
1069                memory: MemoryLocation::HostUpload,
1070            })?;
1071            device.destroy_buffer(core::mem::replace(&mut self.constant_buffers[idx], fresh));
1072            self.constant_capacity[idx] = size;
1073            buffer_replaced = true;
1074        }
1075        device.write_buffer(self.constant_buffers[idx], 0, &blocks)?;
1076
1077        // A frame that grew *either* buffer needs the group rewritten; a
1078        // steady-state frame writes no descriptors, which is still true now that
1079        // the constants can move too — a scene draws the same batch count frame
1080        // after frame.
1081        if buffer_replaced {
1082            let fresh = device.create_bind_group(&BindGroupDesc {
1083                label: Some("sprite frame"),
1084                layout: self.frame_layout,
1085                entries: &frame_entries(self.constant_buffers[idx], self.instance_buffers[idx]),
1086                variable_count: None,
1087            })?;
1088            device.destroy_bind_group(core::mem::replace(&mut self.frame_groups[idx], fresh));
1089        }
1090
1091        self.batches[idx] = batches;
1092        Ok(())
1093    }
1094
1095    /// The most passes [`add_pass`](Self::add_pass) adds to a frame.
1096    ///
1097    /// The most rather than the count: a frame with no sprites adds none, as the
1098    /// method's docs say. What a caller sizing
1099    /// [`PassTimers`](crate::timing::PassTimers) adds up — see
1100    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES).
1101    pub const MAX_PASSES: u32 = 1;
1102
1103    /// Adds the sprite pass to `graph`, drawing on top of `target`.
1104    ///
1105    /// One `draw(0..6, 0..count)` per batch, in submission order, with **both**
1106    /// sets rebound between batches: set 1 for the sheet, and set 0 at the
1107    /// dynamic offset of that batch's constant block. A frame with no sprites
1108    /// adds **no pass at all** rather than an empty one: a render pass that draws
1109    /// nothing still costs a load and a store of the whole target.
1110    ///
1111    /// # Every draw starts at instance 0, and that is load-bearing
1112    ///
1113    /// The obvious spelling is `draw(0..6, batch.instances)` — point the draw at
1114    /// its slice of the frame's instance buffer with `firstInstance` and let the
1115    /// shader index the buffer absolutely. That is what this pass did, and it
1116    /// drew **every batch after the first from the first batch's instances**: a
1117    /// four-sheet frame put one rectangle on screen in the last sheet's colours
1118    /// and left the other three empty. Both shipped samples registered four
1119    /// sheets, so both were rendering wrong.
1120    ///
1121    /// The reason is that `SV_InstanceID` is not the same number on the two
1122    /// targets `sprite.slang` is compiled for. `slangc` lowers it to
1123    /// `InstanceIndex - BaseInstance` on SPIR-V, which is HLSL's definition —
1124    /// relative to the draw — and straight to `@builtin(instance_index)` on
1125    /// WGSL, which WebGPU defines to *start at* `firstInstance`. No shader source
1126    /// is correct on both while `firstInstance` is non-zero.
1127    ///
1128    /// So it is always zero, the two lowerings agree because with a zero base
1129    /// they are the same number, and the batch's offset into the buffer travels
1130    /// in [`SpriteConstants::base`] instead. The cost is one extra `bind_group`
1131    /// per batch, against a bind this pass was already doing for the sheet.
1132    ///
1133    /// `extent` is deliberately absent — see [`begin_frame`](Self::begin_frame).
1134    pub fn add_pass<'a>(&'a self, graph: &mut RenderGraph<'a>, target: ImageId) {
1135        let batches = &self.batches[self.frame];
1136        if batches.is_empty() {
1137            return;
1138        }
1139
1140        let pipeline = self.pipeline;
1141        let pipeline_layout = self.pipeline_layout;
1142        let frame_group = self.frame_groups[self.frame];
1143        let sheets = &self.sheets;
1144
1145        // **Every atlas this frame samples is declared as a read**, so a copy
1146        // [`add_slot_copies`](Self::add_slot_copies) added earlier in the graph
1147        // is followed by the transfer-to-sampled barrier before any fragment
1148        // reads the cell. Without a copy this frame the import is `ShaderRead`
1149        // to `ShaderRead` and costs no barrier. An uploaded sheet is not in the
1150        // graph at all: nothing but its upload ever writes it.
1151        let atlases: Vec<ImageId> = self
1152            .atlases
1153            .iter()
1154            .filter(|atlas| batches.iter().any(|batch| batch.sheet == atlas.sheet))
1155            .map(|atlas| atlas.import(graph))
1156            .collect();
1157
1158        let mut pass = graph.add_render_pass("sprites").color(
1159            target,
1160            LoadOp::Load,
1161            StoreOp::Store,
1162            Default::default(),
1163        );
1164        for atlas in atlases {
1165            pass = pass.read_image(atlas);
1166        }
1167        pass.execute(move |ctx| {
1168            let encoder = ctx.encoder();
1169            encoder.bind_graphics_pipeline(pipeline);
1170            for batch in batches {
1171                // The block `begin_frame` wrote for this batch, and the only
1172                // thing that tells the shader where the batch's instances
1173                // start.
1174                encoder.bind_group(
1175                    FRAME_SET,
1176                    frame_group,
1177                    &[batch.constant_offset],
1178                    pipeline_layout,
1179                );
1180                // Indexing is safe by construction: `begin_frame` refuses a
1181                // sprite naming an unregistered sheet, and sheets are never
1182                // removed.
1183                let group = sheets[batch.sheet.index() as usize].group;
1184                encoder.bind_group(SHEET_SET, group, &[], pipeline_layout);
1185                encoder.draw(0..QUAD_VERTICES, 0..batch.count());
1186            }
1187        });
1188    }
1189
1190    /// Destroys all GPU resources, including every registered sheet.
1191    ///
1192    /// The device must be idle.
1193    pub fn destroy(mut self, device: &dyn Device) {
1194        if self.destroyed {
1195            return;
1196        }
1197        self.destroyed = true;
1198        for sheet in core::mem::take(&mut self.sheets) {
1199            device.destroy_bind_group(sheet.group);
1200            sheet.texture.destroy(device);
1201        }
1202        for group in self.frame_groups.drain(..) {
1203            device.destroy_bind_group(group);
1204        }
1205        for buffer in self.instance_buffers.drain(..) {
1206            device.destroy_buffer(buffer);
1207        }
1208        for buffer in self.constant_buffers.drain(..) {
1209            device.destroy_buffer(buffer);
1210        }
1211        self.atlas_staging.destroy(device);
1212        device.destroy_sampler(self.sampler);
1213        device.destroy_graphics_pipeline(self.pipeline);
1214        device.destroy_pipeline_layout(self.pipeline_layout);
1215        device.destroy_bind_group_layout(self.frame_layout);
1216        device.destroy_bind_group_layout(self.sheet_layout);
1217    }
1218}
1219
1220impl Drop for SpriteRenderer {
1221    fn drop(&mut self) {
1222        if !self.destroyed {
1223            crcbl_core::log::warn!(
1224                "SpriteRenderer dropped without calling destroy() — GPU resources leaked"
1225            );
1226        }
1227    }
1228}
1229
1230// ---------------------------------------------------------------------------
1231// Helpers
1232// ---------------------------------------------------------------------------
1233
1234/// The pipeline's colour target: straight alpha, all channels.
1235///
1236/// A named function rather than a literal inside `build` because the recorder
1237/// cannot see a pipeline descriptor — [`crcbl_hal::null::Event::Created`] keeps
1238/// a kind and a label and nothing else — so this is the only thing a test can
1239/// assert the pass's blend state against. It is the *same* value `build` hands
1240/// to `create_graphics_pipeline`, which is what makes the assertion worth
1241/// anything.
1242const fn color_target(format: Format) -> ColorTargetState {
1243    ColorTargetState {
1244        format,
1245        // `src * a + dst * (1 - a)`, spelled once in `crcbl_hal`.
1246        blend: Some(BlendState::alpha()),
1247        write_mask: ColorWrites::ALL,
1248    }
1249}
1250
1251/// The pipeline's depth state: **none**.
1252///
1253/// No test and no write. Sprites composite in submission order, which is a
1254/// property of the draw order and of alpha blending being order-dependent; a
1255/// depth test would discard the half-transparent fragments that make a sprite a
1256/// sprite. Named for the same reason [`color_target`] is.
1257const SPRITE_DEPTH_STENCIL: Option<DepthStencilState> = None;
1258
1259/// One frame's bind-group entries: constants at 0, instances at 1.
1260///
1261/// One function rather than the two copies `build` and `begin_frame` would
1262/// otherwise carry — they build the *same* group, and a binding added to one and
1263/// forgotten in the other is a group that stops matching its layout the first
1264/// time the ring grows.
1265const fn frame_entries(constants: BufferHandle, instances: BufferHandle) -> [BindGroupEntry; 2] {
1266    [
1267        BindGroupEntry {
1268            binding: 0,
1269            array_index: 0,
1270            // **One block, not the whole buffer.** The binding is dynamic, so
1271            // the offset the bind adds is on top of this one, and both Vulkan
1272            // and WebGPU require `offset + dynamic + size` to stay inside the
1273            // buffer. Bound whole, the very first non-zero dynamic offset would
1274            // be out of range — which is a validation error rather than a wrong
1275            // picture, but only on a machine running the layer.
1276            resource: BindingResource::Buffer {
1277                buffer: constants,
1278                offset: 0,
1279                size: CONSTANTS_SIZE,
1280            },
1281        },
1282        BindGroupEntry {
1283            binding: 1,
1284            array_index: 0,
1285            resource: BindingResource::whole_buffer(instances),
1286        },
1287    ]
1288}
1289
1290/// How many draw calls `sprites` will cost this pass.
1291///
1292/// The batching rule without the batches: a run of consecutive sprites naming
1293/// one sheet is one draw, so `A A B A` is **three** and a distinct-sheet count
1294/// would say two. Pure, so a caller can ask before there is a device — which is
1295/// the point, because the alternative is what `apps/horde` used to do: restate
1296/// the rule in its own module and count with that. A second copy of a rule is
1297/// where the number stays right while the picture goes wrong.
1298///
1299/// It delegates to the pass's own batcher rather than walking the slice again,
1300/// so there is one implementation and this cannot drift from it. The
1301/// `Vec` it allocates is why this is a diagnostic and a test's question rather
1302/// than something to call every frame; the pass itself uses `batch` directly.
1303#[must_use]
1304pub fn batch_count(sprites: &[Sprite]) -> usize {
1305    // Stride zero: it only sets each batch's constant offset, which no count
1306    // depends on.
1307    batch(sprites, 0).len()
1308}
1309
1310/// Splits `sprites` into runs of consecutive sprites sharing a sheet, giving
1311/// each run the byte offset of its constant block.
1312///
1313/// **Consecutive, not grouped.** `A A B A` is three batches, not two: the
1314/// submission order is the caller's compositing order, and reordering it behind
1315/// their back to save a bind is how a sprite ends up behind the thing it was
1316/// drawn after. Pure and free of a device, so the batching rule is testable
1317/// without one.
1318fn batch(sprites: &[Sprite], stride: u32) -> Vec<Batch> {
1319    let mut batches: Vec<Batch> = Vec::new();
1320    for (index, sprite) in sprites.iter().enumerate() {
1321        let index = index as u32;
1322        match batches.last_mut() {
1323            Some(last) if last.sheet == sprite.sheet => last.instances.end = index + 1,
1324            _ => batches.push(Batch {
1325                sheet: sprite.sheet,
1326                instances: index..index + 1,
1327                // Saturating rather than wrapping: an offset that wrapped would
1328                // bind a *valid-looking* block belonging to some other batch,
1329                // which is the failure mode this whole arrangement exists to
1330                // remove. A saturated one is out of the buffer and the layer
1331                // says so. Reaching it needs about 17 million batches.
1332                constant_offset: (batches.len() as u32).saturating_mul(stride),
1333            }),
1334        }
1335    }
1336    batches
1337}
1338
1339/// The bytes of one frame's constant buffer: one [`SpriteConstants`] per batch,
1340/// laid out at `stride`.
1341///
1342/// Pure, so the one thing a recorder cannot see — that batch `n`'s block
1343/// actually carries batch `n`'s first instance — is assertable without a device.
1344/// **A frame with no batches still gets one block**, so a frame that draws
1345/// nothing writes the same number of buffers as one that draws something and the
1346/// buffer is never zero-sized.
1347fn constant_blocks(
1348    view_projection: Mat4,
1349    extent: (u32, u32),
1350    batches: &[Batch],
1351    stride: u32,
1352) -> Vec<u8> {
1353    let stride = stride as usize;
1354    let blocks = batches.len().max(1);
1355    let mut bytes = vec![0u8; blocks * stride];
1356    let view_proj = view_projection.to_cols_array();
1357    let viewport = [extent.0 as f32, extent.1 as f32];
1358    for index in 0..blocks {
1359        let constants = SpriteConstants {
1360            view_proj,
1361            viewport,
1362            // The empty-frame block draws nothing, so its base is 0 by the same
1363            // arithmetic rather than by a special case.
1364            base: batches.get(index).map_or(0, |batch| batch.instances.start),
1365            pad: 0,
1366        };
1367        bytes[index * stride..index * stride + CONSTANTS_SIZE as usize]
1368            .copy_from_slice(bytemuck::bytes_of(&constants));
1369    }
1370    bytes
1371}
1372
1373/// The size the constant ring grows to when `needed` bytes no longer fit.
1374///
1375/// Doubling in **blocks** rather than in bytes, so the result stays a whole
1376/// number of `stride`-sized blocks and the offset arithmetic above never lands
1377/// past the end.
1378fn grown_constants(needed: u64, stride: u32) -> u64 {
1379    let stride = u64::from(stride);
1380    needed.div_ceil(stride).next_power_of_two() * stride
1381}
1382
1383/// `sprite.slang`'s entry point for `stage`.
1384fn entry(stage: Stage) -> Result<&'static str, HalError> {
1385    SPRITE.entry_point(stage).ok_or_else(|| {
1386        HalError::ShaderCompilation(format!(
1387            "sprite.slang exposes no unambiguous {stage:?} entry point"
1388        ))
1389    })
1390}
1391
1392/// What a partly-built [`SpriteRenderer`] has to give back.
1393///
1394/// `build` creates a dozen objects with `?` between them and the seam's
1395/// `destroy_*` is explicit, so a failure half way through would otherwise leak
1396/// everything created before it. [`crate::ui_pass`] and [`crate::forward`] carry
1397/// the same shape for the same reason.
1398#[derive(Default)]
1399struct Rollback {
1400    buffers: Vec<BufferHandle>,
1401    bind_groups: Vec<BindGroupHandle>,
1402    bind_group_layouts: Vec<BindGroupLayoutHandle>,
1403    pipeline_layouts: Vec<PipelineLayoutHandle>,
1404    pipelines: Vec<GraphicsPipelineHandle>,
1405    samplers: Vec<SamplerHandle>,
1406}
1407
1408impl Rollback {
1409    /// Releases everything, in the same dependency order as
1410    /// [`SpriteRenderer::destroy`].
1411    fn run(self, device: &dyn Device) {
1412        for handle in self.bind_groups {
1413            device.destroy_bind_group(handle);
1414        }
1415        for handle in self.buffers {
1416            device.destroy_buffer(handle);
1417        }
1418        for handle in self.samplers {
1419            device.destroy_sampler(handle);
1420        }
1421        for handle in self.pipelines {
1422            device.destroy_graphics_pipeline(handle);
1423        }
1424        for handle in self.pipeline_layouts {
1425            device.destroy_pipeline_layout(handle);
1426        }
1427        for handle in self.bind_group_layouts {
1428            device.destroy_bind_group_layout(handle);
1429        }
1430    }
1431}
1432
1433// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
1434#[cfg(all(test, not(target_arch = "wasm32")))]
1435mod tests {
1436    use super::*;
1437    use crcbl_hal::null::{Command, Event, NullInstance, Recorder};
1438    use crcbl_hal::{
1439        CommandEncoderDesc, DeviceCaps, DeviceDesc, Extent3d, Features, ImageDesc,
1440        ImageSubresourceRange, ImageType, ImageUsage, ImageViewDesc, ImageViewType, Instance,
1441        Limits, QueueKind, ResourceState,
1442    };
1443
1444    use crate::graph::{ImportedImage, InitialClaim};
1445    use crate::transient::TransientPool;
1446
1447    const TARGET: Format = Format::Bgra8UnormSrgb;
1448    const EXTENT: (u32, u32) = (256, 192);
1449
1450    pub(super) fn open(recorder: &Recorder) -> (Box<dyn Device>, QueueHandle) {
1451        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
1452        let adapter = instance.adapters().remove(0);
1453        let device = instance
1454            .create_device(&DeviceDesc {
1455                label: Some("sprite pass"),
1456                adapter: adapter.id,
1457                required_features: Features::GPU_DRIVEN,
1458                optional_features: Features::empty(),
1459                compatible_surface: None,
1460            })
1461            .expect("the null backend always opens");
1462        let queue = device.queue(QueueKind::Graphics).expect("always present");
1463        (device, queue)
1464    }
1465
1466    /// A 2×2 opaque RGBA sheet — the smallest thing `upload_texture` accepts.
1467    fn sheet_desc<'a>(label: &'a str, pixels: &'a [u8], sample: SampleMode) -> SheetDesc<'a> {
1468        SheetDesc {
1469            label,
1470            width: 2,
1471            height: 2,
1472            sample,
1473            pixels,
1474        }
1475    }
1476
1477    fn register(renderer: &mut SpriteRenderer, device: &dyn Device, label: &str) -> SheetId {
1478        let pixels = [255u8; 2 * 2 * 4];
1479        renderer
1480            .register_sheet(device, &sheet_desc(label, &pixels, SampleMode::Pixel))
1481            .expect("the null backend accepts this upload")
1482    }
1483
1484    fn sprite(sheet: SheetId) -> Sprite {
1485        Sprite::new(sheet, [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0])
1486    }
1487
1488    /// A stand-in for a swapchain image, imported exactly as an acquired frame
1489    /// would be.
1490    pub(super) fn target(device: &dyn Device) -> ImportedImage {
1491        let image = device
1492            .create_image(&ImageDesc {
1493                label: Some("fake swapchain image"),
1494                image_type: ImageType::D2,
1495                extent: Extent3d::d2(EXTENT.0, EXTENT.1),
1496                format: TARGET,
1497                mip_levels: 1,
1498                samples: 1,
1499                usage: ImageUsage::COLOR_ATTACHMENT | ImageUsage::PRESENT,
1500            })
1501            .expect("an image");
1502        let view = device
1503            .create_image_view(&ImageViewDesc {
1504                label: Some("fake swapchain view"),
1505                image,
1506                view_type: ImageViewType::D2,
1507                format: TARGET,
1508                range: ImageSubresourceRange::all(TARGET),
1509            })
1510            .expect("a view");
1511        ImportedImage {
1512            image,
1513            view,
1514            format: TARGET,
1515            extent: EXTENT,
1516            // `Load`, so the sprite pass composites onto something rather than
1517            // being the first writer.
1518            initial: ResourceState::ColorAttachment,
1519            // No swapchain and no semaphore: this is an image the test made and
1520            // hands to one frame, so it is the checked kind. The ledger has
1521            // nothing on a freshly created handle, which is what makes the
1522            // declaration above legal rather than exempt.
1523            claim: InitialClaim::Tracked,
1524            final_state: ResourceState::Present,
1525        }
1526    }
1527
1528    /// Runs one frame's sprite pass all the way to recorded HAL commands.
1529    fn run_pass(device: &dyn Device, queue: QueueHandle, renderer: &SpriteRenderer) {
1530        let imported = target(device);
1531        let mut pool = TransientPool::new();
1532        let mut graph = RenderGraph::new(queue);
1533        let swap = graph.import_image("swapchain", imported);
1534        renderer.add_pass(&mut graph, swap);
1535        let compiled = graph.compile(&pool).expect("a legal frame");
1536        let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
1537            label: Some("sprite frame"),
1538            queue,
1539        });
1540        compiled
1541            .execute(device, &mut pool, encoder.as_mut(), None)
1542            .expect("execution succeeded");
1543        let commands = encoder.finish().expect("recording succeeded");
1544        device.destroy_command_buffer(commands);
1545        pool.destroy(device);
1546        device.destroy_image_view(imported.view);
1547        device.destroy_image(imported.image);
1548    }
1549
1550    fn draws(recorder: &Recorder) -> Vec<Range<u32>> {
1551        recorder
1552            .commands()
1553            .into_iter()
1554            .filter_map(|command| match command {
1555                Command::Draw {
1556                    vertices,
1557                    instances,
1558                } => {
1559                    assert_eq!(
1560                        vertices,
1561                        0..QUAD_VERTICES,
1562                        "every sprite draw expands the same six-vertex quad"
1563                    );
1564                    Some(instances)
1565                }
1566                _ => None,
1567            })
1568            .collect()
1569    }
1570
1571    /// The bind groups bound to set 1, in order — one per batch.
1572    fn sheet_binds(recorder: &Recorder) -> Vec<BindGroupHandle> {
1573        recorder
1574            .commands()
1575            .into_iter()
1576            .filter_map(|command| match command {
1577                Command::BindGroup { slot, group, .. } if slot == SHEET_SET => Some(group),
1578                _ => None,
1579            })
1580            .collect()
1581    }
1582
1583    /// The dynamic offsets each set-0 bind carried, in order.
1584    fn frame_bind_offsets(recorder: &Recorder) -> Vec<Vec<u32>> {
1585        recorder
1586            .commands()
1587            .into_iter()
1588            .filter_map(|command| match command {
1589                Command::BindGroup {
1590                    slot,
1591                    dynamic_offsets,
1592                    ..
1593                } if slot == FRAME_SET => Some(dynamic_offsets),
1594                _ => None,
1595            })
1596            .collect()
1597    }
1598
1599    fn as_floats(bytes: &[u8]) -> Vec<f32> {
1600        bytes
1601            .as_chunks::<4>()
1602            .0
1603            .iter()
1604            .map(|word| f32::from_le_bytes(*word))
1605            .collect()
1606    }
1607
1608    // -----------------------------------------------------------------------
1609    // The ABI
1610    // -----------------------------------------------------------------------
1611
1612    /// **The field-reordering test.** A `rect`/`uv`/`tint`/`sheet` permutation
1613    /// between Rust and Slang is the kind of mistake that renders *something*,
1614    /// so both sides are pinned here as well as in the goldens.
1615    ///
1616    /// The Rust half is the actual bytes, decoded back to floats at named
1617    /// offsets. The Slang half is the *compiled* WGSL, which `build.rs`
1618    /// hash-checks against the committed `.slang`, so a reorder on either side
1619    /// moves one of the two and this fails.
1620    #[test]
1621    fn an_instance_is_four_float4s_in_the_order_the_shader_reads() {
1622        assert_eq!(INSTANCE_STRIDE, 64);
1623        assert_eq!(align_of::<SpriteInstance>(), 4);
1624        assert_eq!(
1625            INSTANCE_STRIDE % 16,
1626            0,
1627            "every element of the array must land on a 16-byte boundary, or the \
1628             shader's float4 alignment is violated from element one onwards"
1629        );
1630
1631        // Distinct in every lane, so a transposed or rotated field cannot
1632        // compare equal by accident — and, because it is built through
1633        // `Sprite::new`, a `rect` and a `uv` swapped inside the constructor
1634        // fail here too. The call sites are still on their own; see `new`.
1635        let sprite = Sprite::new(SheetId(0), [-3.5, 12.0, 64.0, 32.0], [0.25, 0.5, 0.75, 1.0])
1636            .with_rotation(1.25)
1637            .with_tint([0.1, 0.2, 0.3, 0.4]);
1638        let instance = sprite.instance(sheet_lane(16, 8, SampleMode::Pixel));
1639        let bytes = bytemuck::bytes_of(&instance);
1640        assert_eq!(bytes.len(), INSTANCE_STRIDE);
1641        let floats = as_floats(bytes);
1642        assert_eq!(&floats[0..4], &[-3.5, 12.0, 64.0, 32.0], "rect at byte 0");
1643        assert_eq!(&floats[4..8], &[0.25, 0.5, 0.75, 1.0], "uv at byte 16");
1644        assert_eq!(&floats[8..12], &[0.1, 0.2, 0.3, 0.4], "tint at byte 32");
1645        assert_eq!(
1646            &floats[12..16],
1647            &[16.0, 8.0, SAMPLE_PIXEL, 1.25],
1648            "sheet size, sample mode and rotation at byte 48 — the angle is the \
1649             fourth component and nothing else is"
1650        );
1651
1652        // And the shader really does read them in that order. `slangc` names the
1653        // members and emits their alignment, so this is the compiled artifact's
1654        // own account of the layout rather than a restatement of the source.
1655        let wgsl = crcbl_shaders::SPRITE
1656            .wgsl()
1657            .expect("sprite has a WGSL half");
1658        let declared = wgsl
1659            .split_once("struct SpriteInstance_std430_0")
1660            .expect("the instance struct survives to WGSL")
1661            .1
1662            .split_once("};")
1663            .expect("and it is closed")
1664            .0;
1665        let members: Vec<&str> = declared
1666            .lines()
1667            .filter_map(|line| line.trim().strip_suffix(','))
1668            .collect();
1669        assert_eq!(
1670            members,
1671            [
1672                "@align(16) rect_0 : vec4<f32>",
1673                "@align(16) uv_0 : vec4<f32>",
1674                "@align(16) tint_0 : vec4<f32>",
1675                "@align(16) sheet_0 : vec4<f32>",
1676            ],
1677            "the shader's instance layout no longer matches SpriteInstance"
1678        );
1679    }
1680
1681    /// The mode reaches the shader as an exact `lerp` weight, and the sheet's
1682    /// texel size reaches it at all.
1683    ///
1684    /// `sprite.slang` selects between the plain and the bent UV with
1685    /// `lerp(plain, sharp, sheet.z)` rather than a branch — the fragment stage
1686    /// must stay in uniform control flow — so a mode that arrived as anything
1687    /// other than exactly 0 or exactly 1 would silently blend the two filters.
1688    #[test]
1689    fn the_sample_mode_is_an_exact_zero_or_one_and_the_size_rides_beside_it() {
1690        assert_eq!(SAMPLE_PIXEL, 1.0);
1691        assert_eq!(SAMPLE_SMOOTH, 0.0);
1692        assert_eq!(
1693            sheet_lane(64, 32, SampleMode::Pixel),
1694            [64.0, 32.0, 1.0, 0.0]
1695        );
1696        assert_eq!(
1697            sheet_lane(64, 32, SampleMode::Smooth),
1698            [64.0, 32.0, 0.0, 0.0]
1699        );
1700        // Width and height in that order, and not swapped: a square sheet is the
1701        // one that cannot tell.
1702        let lane = sheet_lane(7, 3, SampleMode::Smooth);
1703        assert_eq!((lane[0], lane[1]), (7.0, 3.0));
1704
1705        // The shader reads `sheet.xy` as the size and `sheet.z` as the mode, and
1706        // hands `xyz` on to the fragment stage flat — the compiled artifact's own
1707        // account of it, so a renamed or reordered varying fails here.
1708        let wgsl = crcbl_shaders::SPRITE
1709            .wgsl()
1710            .expect("sprite has a WGSL half");
1711        assert!(
1712            wgsl.contains("output_0.sheet_2 = s_0.sheet_0.xyz;"),
1713            "the vertex stage must pass the sheet lane through: {wgsl}"
1714        );
1715        assert!(
1716            wgsl.contains("@interpolate(flat)"),
1717            "the mode is a lerp weight and must not be interpolated: {wgsl}"
1718        );
1719        assert!(
1720            wgsl.contains("fwidth("),
1721            "sharp-bilinear's ramp width is a screen-space derivative; without \
1722             fwidth there is no ramp: {wgsl}"
1723        );
1724        assert!(
1725            wgsl.contains("round(pixels_0)"),
1726            "the vertex stage must snap the quad to the pixel grid: {wgsl}"
1727        );
1728        assert!(
1729            wgsl.contains("constants_0.viewport_0"),
1730            "and the snap must read the viewport rather than guess it: {wgsl}"
1731        );
1732    }
1733
1734    /// **A zero angle writes the bytes the pass wrote before rotation existed.**
1735    ///
1736    /// The angle rides in the fourth component of the sheet lane, which was
1737    /// padding and was already `0.0`, so a sprite that does not turn produces
1738    /// exactly the sixty-four bytes it always did. That is what makes the eight
1739    /// golden images in `crates/crcbl/tests/golden/` a regression check for
1740    /// this slice rather than eight pictures that had to be re-blessed: none of
1741    /// them draws a rotated sprite, and none of their instances changed.
1742    #[test]
1743    fn a_zero_rotation_writes_the_same_instance_bytes_as_a_sprite_without_one() {
1744        let lane = sheet_lane(16, 8, SampleMode::Pixel);
1745        let flat = Sprite::new(SheetId(0), [-3.5, 12.0, 64.0, 32.0], [0.25, 0.5, 0.75, 1.0])
1746            .with_tint([0.1, 0.2, 0.3, 0.4]);
1747        // What `instance` built before this slice: the sheet lane copied
1748        // verbatim, trailing pad and all.
1749        let before = SpriteInstance {
1750            rect: flat.rect,
1751            uv: flat.uv,
1752            tint: flat.tint,
1753            sheet: lane,
1754        };
1755        assert_eq!(
1756            bytemuck::bytes_of(&flat.instance(lane)),
1757            bytemuck::bytes_of(&before),
1758            "an unrotated sprite's instance must be byte-identical to the one \
1759             this pass produced before it could rotate at all"
1760        );
1761
1762        // And a turned one differs in the last four bytes and nowhere else — so
1763        // the angle cost no space and displaced nothing.
1764        let turned = flat.with_rotation(core::f32::consts::FRAC_PI_2);
1765        let turned_instance = turned.instance(lane);
1766        let turned_bytes = bytemuck::bytes_of(&turned_instance);
1767        let flat_bytes = bytemuck::bytes_of(&before);
1768        assert_eq!(
1769            &turned_bytes[..60],
1770            &flat_bytes[..60],
1771            "rect, uv, tint and the sheet's own size and mode must not move"
1772        );
1773        assert_eq!(
1774            f32::from_le_bytes(turned_bytes[60..64].try_into().expect("four bytes")),
1775            core::f32::consts::FRAC_PI_2,
1776            "and the angle must land at byte 60, which is `sheet.w`"
1777        );
1778        assert_eq!(
1779            f32::from_le_bytes(flat_bytes[60..64].try_into().expect("four bytes")),
1780            0.0,
1781            "where an unrotated sprite leaves the zero that was already there"
1782        );
1783    }
1784
1785    /// **The compiled shader reads the angle from where this side writes it, and
1786    /// the fragment stage never sees it.**
1787    ///
1788    /// The Rust half above is bytes; this is the *artifact's* account of what is
1789    /// done with them, so a `.slang` edited without regenerating, or regenerated
1790    /// without the rotation, fails here rather than only in a golden image.
1791    ///
1792    /// **The SPIR-V half was checked by hand rather than here**, because
1793    /// `crcbl_shaders::SPRITE::spirv` is a byte blob with no disassembler behind
1794    /// it. `spirv-dis` on the committed `spirv/sprite.spv` shows the same shape
1795    /// as the WGSL below: an `OpCompositeExtract %float … 3` for the angle, an
1796    /// `OpBranchConditional` on `angle != 0`, `GLSL.std.450 Sin`/`Cos` inside it,
1797    /// and — the part that matters — an untaken path whose instructions are the
1798    /// same `OpFMul`/`OpFAdd` pair the pass emitted before this slice.
1799    #[test]
1800    fn the_compiled_shader_turns_the_quad_from_the_lanes_fourth_component() {
1801        let wgsl = crcbl_shaders::SPRITE
1802            .wgsl()
1803            .expect("sprite has a WGSL half");
1804        assert!(
1805            wgsl.contains("s_0.sheet_0.w"),
1806            "the vertex stage must read the angle from the sheet lane's fourth \
1807             component: {wgsl}"
1808        );
1809        assert!(
1810            wgsl.contains("sin(angle_0)") && wgsl.contains("cos(angle_0)"),
1811            "and actually build a rotation from it: {wgsl}"
1812        );
1813        assert!(
1814            wgsl.contains("output_0.sheet_2 = s_0.sheet_0.xyz;"),
1815            "the varying is still xyz — rotation is a vertex-stage concern and \
1816             the fragment stage must not have grown a fourth component: {wgsl}"
1817        );
1818        assert!(
1819            wgsl.contains("round(pixels_0)"),
1820            "an unrotated Pixel quad still rounds its own corners: {wgsl}"
1821        );
1822        assert!(
1823            wgsl.contains("round(centrePixels_0)"),
1824            "and a rotated one snaps its centre instead — rounding four turned \
1825             corners independently shears the quad: {wgsl}"
1826        );
1827    }
1828
1829    /// The same for the constant block: the matrix first, then the viewport the
1830    /// vertex stage snaps against, then the batch's base instance, then the
1831    /// padding `std140` insists on.
1832    #[test]
1833    fn the_constants_are_the_matrix_then_the_viewport_then_the_base() {
1834        assert_eq!(CONSTANTS_SIZE, 80);
1835        assert_eq!(
1836            CONSTANTS_SIZE % 16,
1837            0,
1838            "naga rejects a uniform block whose size is not a multiple of 16"
1839        );
1840
1841        let constants = SpriteConstants {
1842            view_proj: Mat4::from_scale(glam::Vec3::new(2.0, 3.0, 4.0)).to_cols_array(),
1843            viewport: [1280.0, 720.0],
1844            base: 0x0102_0304,
1845            pad: 0,
1846        };
1847        let bytes = bytemuck::bytes_of(&constants);
1848        let floats = as_floats(bytes);
1849        assert_eq!(floats.len(), 20);
1850        assert_eq!(floats[0], 2.0, "m00 in the first four bytes");
1851        assert_eq!(floats[5], 3.0, "m11 twenty bytes in — column-major");
1852        assert_eq!(floats[10], 4.0, "m22");
1853        assert_eq!(&floats[16..18], &[1280.0, 720.0], "viewport at byte 64");
1854        assert_eq!(
1855            u32::from_le_bytes(bytes[72..76].try_into().expect("four bytes")),
1856            0x0102_0304,
1857            "the base instance sits at byte 72, which is `Offset 72` in the SPIR-V"
1858        );
1859
1860        let wgsl = crcbl_shaders::SPRITE
1861            .wgsl()
1862            .expect("sprite has a WGSL half");
1863        let declared = wgsl
1864            .split_once("struct SpriteConstants_std140_0")
1865            .expect("the constant block survives to WGSL")
1866            .1
1867            .split_once("};")
1868            .expect("and it is closed")
1869            .0;
1870        let members: Vec<&str> = declared
1871            .lines()
1872            .filter_map(|line| line.trim().strip_suffix(','))
1873            .collect();
1874        assert_eq!(
1875            members,
1876            [
1877                "@align(16) view_proj_0 : _MatrixStorage_float4x4_ColMajorstd140_0",
1878                "@align(16) viewport_0 : vec2<f32>",
1879                "@align(8) base_0 : u32",
1880                "@align(4) pad_0 : u32",
1881            ],
1882            "the shader's constant layout no longer matches SpriteConstants"
1883        );
1884    }
1885
1886    /// And `begin_frame` really writes that layout: one stride per sprite, at
1887    /// offset zero, into *this* frame's instance buffer.
1888    #[test]
1889    fn begin_frame_writes_one_stride_per_sprite_at_offset_zero() {
1890        let recorder = Recorder::new();
1891        let (device, queue) = open(&recorder);
1892        let mut renderer = SpriteRenderer::new(device.as_ref(), queue, TARGET).expect("built");
1893        let sheet = register(&mut renderer, device.as_ref(), "sheet");
1894
1895        let sprites = vec![sprite(sheet); 3];
1896        recorder.clear();
1897        renderer
1898            .begin_frame(device.as_ref(), &sprites, Mat4::IDENTITY, EXTENT)
1899            .expect("upload");
1900
1901        let instance_buffer = renderer.instance_buffers[renderer.frame];
1902        let constant_buffer = renderer.constant_buffers[renderer.frame];
1903        let writes: Vec<(BufferHandle, u64, usize)> = recorder
1904            .events()
1905            .into_iter()
1906            .filter_map(|event| match event {
1907                Event::BufferWritten {
1908                    buffer,
1909                    offset,
1910                    len,
1911                } => Some((buffer, offset, len)),
1912                _ => None,
1913            })
1914            .collect();
1915        assert_eq!(
1916            writes,
1917            [
1918                (instance_buffer, 0, 3 * INSTANCE_STRIDE),
1919                // Three sprites on one sheet is one batch, so one block.
1920                (constant_buffer, 0, renderer.constant_stride as usize),
1921            ],
1922            "a frame writes exactly its instances and its constants, once each"
1923        );
1924
1925        renderer.destroy(device.as_ref());
1926    }
1927
1928    // -----------------------------------------------------------------------
1929    // Batching
1930    // -----------------------------------------------------------------------
1931
1932    /// **Submission order is the contract.** `A B A` is three batches, not two:
1933    /// grouping the two `A`s would put the second one on top of `B`, which the
1934    /// caller did not ask for.
1935    #[test]
1936    fn interleaving_two_sheets_makes_three_batches_not_two() {
1937        let (a, b) = (SheetId(0), SheetId(1));
1938        assert_eq!(
1939            batch(&[sprite(a), sprite(a), sprite(b), sprite(a)], 256),
1940            [
1941                Batch {
1942                    sheet: a,
1943                    instances: 0..2,
1944                    constant_offset: 0,
1945                },
1946                Batch {
1947                    sheet: b,
1948                    instances: 2..3,
1949                    constant_offset: 256,
1950                },
1951                Batch {
1952                    sheet: a,
1953                    instances: 3..4,
1954                    constant_offset: 512,
1955                },
1956            ]
1957        );
1958        // The consecutive case still collapses.
1959        assert_eq!(
1960            batch(&[sprite(a), sprite(a), sprite(a)], 256),
1961            [Batch {
1962                sheet: a,
1963                instances: 0..3,
1964                constant_offset: 0,
1965            }]
1966        );
1967        assert!(batch(&[], 256).is_empty());
1968    }
1969
1970    /// The public count answers what the pass records, at every shape the rule
1971    /// distinguishes.
1972    ///
1973    /// [`batch_count`] exists so a consumer can stop keeping its own copy of the
1974    /// batching rule — `apps/horde` did, to put a number on its debug panel —
1975    /// and a count that could disagree with the batcher would be the same
1976    /// defect in a new place. It delegates, so this is a guard against someone
1977    /// later deciding the delegation is wasteful and walking the slice twice.
1978    #[test]
1979    fn the_public_batch_count_is_the_batchers_own_answer() {
1980        let (a, b) = (SheetId(0), SheetId(1));
1981        for sprites in [
1982            vec![],
1983            vec![sprite(a)],
1984            vec![sprite(a), sprite(a), sprite(a)],
1985            vec![sprite(a), sprite(b)],
1986            vec![sprite(a), sprite(a), sprite(b), sprite(a)],
1987            vec![sprite(a), sprite(b), sprite(a), sprite(b)],
1988        ] {
1989            assert_eq!(
1990                batch_count(&sprites),
1991                batch(&sprites, 256).len(),
1992                "{} sprites",
1993                sprites.len(),
1994            );
1995        }
1996        // And the value itself, so this is not two wrongs agreeing: `A A B A`
1997        // is the case a distinct-sheet count gets wrong.
1998        assert_eq!(
1999            batch_count(&[sprite(a), sprite(a), sprite(b), sprite(a)]),
2000            3
2001        );
2002        assert_eq!(batch_count(&[]), 0);
2003    }
2004
2005    /// **The counters are what the pass recorded**, checked against the recorded
2006    /// stream rather than against a restatement of the batching rule.
2007    ///
2008    /// Two scenes whose answers differ in every field, so a counter wired to a
2009    /// constant, to the sprite count, or to the sheet count fails on one of
2010    /// them: `A A A` is one draw of three instances and `A A B A` is three draws
2011    /// of four. And the numbers are compared with the `Draw` commands the null
2012    /// backend actually saw, so a `counters` that stopped agreeing with
2013    /// `add_pass` fails here rather than reading plausibly on a panel.
2014    #[test]
2015    fn the_counters_are_the_draws_the_pass_records() {
2016        let recorder = Recorder::default();
2017        let (device, queue) = open(&recorder);
2018        let mut renderer =
2019            SpriteRenderer::new(device.as_ref(), queue, TARGET).expect("the null backend builds");
2020        let a = register(&mut renderer, device.as_ref(), "a");
2021        let b = register(&mut renderer, device.as_ref(), "b");
2022
2023        // A scene of one run, and a scene the same rule splits into three.
2024        for (sprites, expected) in [
2025            (vec![sprite(a), sprite(a), sprite(a)], (1u64, 3u64)),
2026            (
2027                vec![sprite(a), sprite(a), sprite(b), sprite(a)],
2028                (3u64, 4u64),
2029            ),
2030        ] {
2031            recorder.clear();
2032            renderer
2033                .begin_frame(device.as_ref(), &sprites, Mat4::IDENTITY, EXTENT)
2034                .expect("the null backend accepts the upload");
2035            let counters = renderer.counters();
2036            run_pass(device.as_ref(), queue, &renderer);
2037
2038            let recorded = draws(&recorder);
2039            let (draw_count, instance_count) = expected;
2040            assert_eq!(counters.draws, draw_count, "{} sprites", sprites.len());
2041            assert_eq!(
2042                counters.draws,
2043                recorded.len() as u64,
2044                "the counter and the recorded stream disagree",
2045            );
2046            assert_eq!(counters.instances, instance_count);
2047            assert_eq!(
2048                counters.instances,
2049                recorded
2050                    .iter()
2051                    .map(|range| u64::from(range.end))
2052                    .sum::<u64>(),
2053                "every draw covers 0..count, so the ends sum to the instances",
2054            );
2055            // Nothing here culls and nothing here is indirect, so both of the
2056            // `Option`s are answers rather than `indirect`.
2057            assert_eq!(counters.drawn, Some(instance_count));
2058            assert_eq!(counters.triangles, Some(instance_count * 2));
2059        }
2060
2061        // A frame with no sprites adds no pass, so it recorded nothing — and
2062        // says so as a zero it knows, not as an unknown.
2063        recorder.clear();
2064        renderer
2065            .begin_frame(device.as_ref(), &[], Mat4::IDENTITY, EXTENT)
2066            .expect("an empty frame is legal");
2067        assert_eq!(renderer.counters(), FrameCounters::default());
2068        run_pass(device.as_ref(), queue, &renderer);
2069        assert!(draws(&recorder).is_empty());
2070
2071        renderer.destroy(device.as_ref());
2072    }
2073
2074    /// **Batch `n` gets batch `n`'s first sprite, and every block gets the same
2075    /// camera.** The recorder can see that a constant buffer was written and how
2076    /// long the write was; it cannot see what was *in* it, and what is in it is
2077    /// the entire fix — a block whose `base` was wrong would record identically.
2078    ///
2079    /// So the layout function is pure and this reads it directly.
2080    #[test]
2081    fn each_batchs_constant_block_carries_that_batchs_first_instance() {
2082        let (a, b) = (SheetId(0), SheetId(1));
2083        let stride = 256u32;
2084        let batches = batch(&[sprite(a), sprite(a), sprite(b), sprite(a)], stride);
2085        let blocks = constant_blocks(Mat4::IDENTITY, (640, 480), &batches, stride);
2086
2087        assert_eq!(
2088            blocks.len(),
2089            3 * stride as usize,
2090            "one stride-sized block per batch"
2091        );
2092        let base_at = |index: usize| {
2093            let start = index * stride as usize + 72;
2094            u32::from_le_bytes(blocks[start..start + 4].try_into().expect("four bytes"))
2095        };
2096        assert_eq!(
2097            [base_at(0), base_at(1), base_at(2)],
2098            [0, 2, 3],
2099            "the bases must be the batches' own instance starts — all-zero here is \
2100             exactly the bug, every batch drawing the first batch's sprites"
2101        );
2102        // And every block still carries the frame's camera and viewport, which a
2103        // per-batch block is easy to leave stale in.
2104        for index in 0..3 {
2105            let start = index * stride as usize;
2106            let floats = as_floats(&blocks[start..start + CONSTANTS_SIZE as usize]);
2107            assert_eq!(floats[0], 1.0, "block {index} lost the identity matrix");
2108            assert_eq!(
2109                &floats[16..18],
2110                &[640.0, 480.0],
2111                "block {index} lost the viewport"
2112            );
2113        }
2114
2115        // A frame with nothing to draw still writes one block, so the buffer is
2116        // never zero-sized and the write count does not depend on the scene.
2117        assert_eq!(
2118            constant_blocks(Mat4::IDENTITY, (640, 480), &[], stride).len(),
2119            stride as usize
2120        );
2121    }
2122
2123    /// The constant ring grows in whole blocks, so an offset can never point
2124    /// past the end of the buffer that was allocated for it.
2125    ///
2126    /// **80 is in the list of strides on purpose.** A device whose
2127    /// `min_uniform_buffer_offset_alignment` is 16 gets a stride of exactly
2128    /// [`CONSTANTS_SIZE`], which is not a power of two — and rounding the *byte*
2129    /// count to a power of two instead of the block count passes every check at
2130    /// 128 and 256 and lands on a partial block there. `Limits::desktop` reports
2131    /// 64 and WebGPU reports 256, so nothing else in this suite would notice.
2132    #[test]
2133    fn the_constant_ring_grows_in_whole_blocks() {
2134        assert_eq!(grown_constants(256, 256), 256);
2135        assert_eq!(grown_constants(257, 256), 512);
2136        assert_eq!(grown_constants(5 * 256, 256), 8 * 256);
2137        for stride in [80u32, 128, 256] {
2138            for blocks in 1u64..40 {
2139                let needed = blocks * u64::from(stride);
2140                let size = grown_constants(needed, stride);
2141                assert_eq!(
2142                    size % u64::from(stride),
2143                    0,
2144                    "{blocks} blocks of {stride} rounded to a partial block: {size}"
2145                );
2146                assert!(
2147                    size >= needed,
2148                    "{blocks} blocks of {stride} shrank to {size}"
2149                );
2150            }
2151        }
2152    }
2153
2154    /// And that reaches the command stream: three draws, in that order, each
2155    /// preceded by its own set-1 bind, with the first and third naming the
2156    /// *same* sheet group and the second a different one.
2157    #[test]
2158    fn three_batches_record_three_draws_over_the_ranges_they_claim() {
2159        let recorder = Recorder::new();
2160        let (device, queue) = open(&recorder);
2161        let mut renderer = SpriteRenderer::new(device.as_ref(), queue, TARGET).expect("built");
2162        let a = register(&mut renderer, device.as_ref(), "a");
2163        let b = register(&mut renderer, device.as_ref(), "b");
2164
2165        let sprites = [sprite(a), sprite(a), sprite(b), sprite(a)];
2166        renderer
2167            .begin_frame(device.as_ref(), &sprites, Mat4::IDENTITY, EXTENT)
2168            .expect("upload");
2169
2170        recorder.clear();
2171        run_pass(device.as_ref(), queue, &renderer);
2172
2173        // **Every draw starts at instance 0.** Not `0..2, 2..3, 3..4`, which is
2174        // what this recorded until the multi-sheet bug was found: a non-zero
2175        // `firstInstance` means one thing to SPIR-V's `SV_InstanceID` and the
2176        // opposite to WGSL's, so no shader can read it correctly on both. The
2177        // batch's place in the buffer travels in the constants instead — see the
2178        // dynamic offsets below and `add_pass`.
2179        assert_eq!(draws(&recorder), [0..2, 0..1, 0..1]);
2180
2181        let offsets = frame_bind_offsets(&recorder);
2182        let stride = renderer.constant_stride;
2183        assert_eq!(
2184            offsets,
2185            [vec![0], vec![stride], vec![2 * stride]],
2186            "set 0 is rebound per batch at that batch's block; one bind for the \
2187             whole pass, or the same offset twice, is every batch reading the \
2188             first batch's instances again"
2189        );
2190
2191        let binds = sheet_binds(&recorder);
2192        assert_eq!(binds.len(), 3, "one set-1 bind per batch");
2193        assert_eq!(
2194            binds[0], binds[2],
2195            "the first and third batches share a sheet"
2196        );
2197        assert_ne!(binds[0], binds[1], "the middle batch is the other sheet");
2198        assert_eq!(binds[0], renderer.sheets[a.index() as usize].group);
2199        assert_eq!(binds[1], renderer.sheets[b.index() as usize].group);
2200
2201        renderer.destroy(device.as_ref());
2202        recorder.assert_valid();
2203    }
2204
2205    /// **Layer 0 draws behind layer 1, all the way to the command stream.**
2206    ///
2207    /// The ordering slice 6 adds is [`crate::layers::LayerStack::resolve`]'s and
2208    /// nothing else's: this pass still batches consecutive sprites and still
2209    /// never sorts, so the evidence that back-to-front happened is that the
2210    /// *recorded draws* come out in layer order.
2211    ///
2212    /// Each layer gets its own sheet, so the two are distinguishable in the
2213    /// command stream — a draw range on its own cannot say which layer it came
2214    /// from. The submission is deliberately interleaved across layers, which is
2215    /// what a game does: a stack that appended to one flat list would record the
2216    /// two sheets alternating instead of two clean batches.
2217    #[test]
2218    fn the_back_layer_is_drawn_before_the_front_one() {
2219        use crate::layers::{LayerStack, Parallax};
2220
2221        let recorder = Recorder::new();
2222        let (device, queue) = open(&recorder);
2223        let mut renderer = SpriteRenderer::new(device.as_ref(), queue, TARGET).expect("built");
2224        let back_sheet = register(&mut renderer, device.as_ref(), "background");
2225        let front_sheet = register(&mut renderer, device.as_ref(), "foreground");
2226
2227        let mut stack = LayerStack::new();
2228        let back = stack.push_layer(Parallax::new(0.5).expect("finite"));
2229        let front = stack.push_layer(Parallax::WORLD);
2230        for (layer, sheet) in [
2231            (front, front_sheet),
2232            (back, back_sheet),
2233            (front, front_sheet),
2234            (back, back_sheet),
2235            (back, back_sheet),
2236        ] {
2237            stack.push(layer, sprite(sheet));
2238        }
2239
2240        renderer
2241            .begin_frame(
2242                device.as_ref(),
2243                stack.resolve([0.0, 0.0]),
2244                Mat4::IDENTITY,
2245                EXTENT,
2246            )
2247            .expect("upload");
2248
2249        recorder.clear();
2250        run_pass(device.as_ref(), queue, &renderer);
2251
2252        assert_eq!(
2253            draws(&recorder),
2254            [0..3, 0..2],
2255            "the back layer's three sprites, then the front layer's two — five \
2256             draws would mean the stack never grouped, and one would mean the \
2257             pass sorted"
2258        );
2259        assert_eq!(
2260            frame_bind_offsets(&recorder),
2261            [vec![0], vec![renderer.constant_stride]],
2262            "and the front layer's draw reads the *front* layer's block — the \
2263             draw ranges above both start at zero, so this is the only thing \
2264             that says the second draw is not the first three sprites again"
2265        );
2266        let binds = sheet_binds(&recorder);
2267        assert_eq!(
2268            binds,
2269            [
2270                renderer.sheets[back_sheet.index() as usize].group,
2271                renderer.sheets[front_sheet.index() as usize].group,
2272            ],
2273            "and the first draw is the *back* layer's sheet"
2274        );
2275
2276        renderer.destroy(device.as_ref());
2277        recorder.assert_valid();
2278    }
2279
2280    /// **No sprite dropped, none drawn twice.** The batching arithmetic is the
2281    /// one place an off-by-one silently deletes the last sprite of every run.
2282    #[test]
2283    fn every_draw_together_covers_every_sprite_exactly_once() {
2284        let recorder = Recorder::new();
2285        let (device, queue) = open(&recorder);
2286        let mut renderer = SpriteRenderer::new(device.as_ref(), queue, TARGET).expect("built");
2287        let sheets = [
2288            register(&mut renderer, device.as_ref(), "a"),
2289            register(&mut renderer, device.as_ref(), "b"),
2290            register(&mut renderer, device.as_ref(), "c"),
2291        ];
2292        // An awkward interleaving rather than a tidy one: runs of 1, 2 and 3,
2293        // starting and ending on different sheets.
2294        let order = [0usize, 1, 1, 2, 2, 2, 0, 1, 0, 0];
2295        let sprites: Vec<Sprite> = order.iter().map(|&i| sprite(sheets[i])).collect();
2296        renderer
2297            .begin_frame(device.as_ref(), &sprites, Mat4::IDENTITY, EXTENT)
2298            .expect("upload");
2299
2300        recorder.clear();
2301        run_pass(device.as_ref(), queue, &renderer);
2302
2303        // **A draw's range is no longer the sprites it covers.** Every draw
2304        // starts at instance 0; which sprites it lands on is the draw's count
2305        // *plus* the constant block the set-0 bind selected. So the absolute
2306        // range is reconstructed the way the shader reconstructs it — the block
2307        // the recorded dynamic offset names, plus the recorded count.
2308        //
2309        // That the block at offset `n * stride` really holds batch `n`'s first
2310        // sprite is `each_batchs_constant_block_carries_that_batchs_first_instance`,
2311        // which reads the bytes the recorder cannot.
2312        let stride = renderer.constant_stride;
2313        let batches = &renderer.batches[renderer.frame];
2314        let absolute: Vec<Range<u32>> = frame_bind_offsets(&recorder)
2315            .into_iter()
2316            .zip(draws(&recorder))
2317            .map(|(offsets, drawn)| {
2318                assert_eq!(offsets.len(), 1, "set 0 has exactly one dynamic binding");
2319                let block = (offsets[0] / stride) as usize;
2320                let base = batches[block].instances.start;
2321                assert_eq!(
2322                    offsets[0] % stride,
2323                    0,
2324                    "an offset that is not a whole block"
2325                );
2326                base + drawn.start..base + drawn.end
2327            })
2328            .collect();
2329
2330        let mut covered = vec![0u32; sprites.len()];
2331        for range in &absolute {
2332            for index in range.clone() {
2333                covered[index as usize] += 1;
2334            }
2335        }
2336        assert_eq!(
2337            covered,
2338            vec![1u32; sprites.len()],
2339            "every sprite must be drawn exactly once, and the counts say which are not"
2340        );
2341
2342        // And each draw's sheet is the sheet those sprites actually named.
2343        let binds = sheet_binds(&recorder);
2344        assert_eq!(binds.len(), absolute.len());
2345        for (group, range) in binds.iter().zip(&absolute) {
2346            for index in range.clone() {
2347                let expected =
2348                    renderer.sheets[sprites[index as usize].sheet.index() as usize].group;
2349                assert_eq!(
2350                    *group, expected,
2351                    "sprite {index} was drawn with another sheet"
2352                );
2353            }
2354        }
2355
2356        renderer.destroy(device.as_ref());
2357        recorder.assert_valid();
2358    }
2359
2360    /// An empty frame records no draw — and no pass at all, because a render
2361    /// pass that draws nothing still costs a load and a store of the target.
2362    #[test]
2363    fn an_empty_frame_records_no_draw() {
2364        let recorder = Recorder::new();
2365        let (device, queue) = open(&recorder);
2366        let mut renderer = SpriteRenderer::new(device.as_ref(), queue, TARGET).expect("built");
2367        let _sheet = register(&mut renderer, device.as_ref(), "unused");
2368
2369        renderer
2370            .begin_frame(device.as_ref(), &[], Mat4::IDENTITY, EXTENT)
2371            .expect("an empty frame is not an error");
2372
2373        recorder.clear();
2374        let imported = target(device.as_ref());
2375        let mut pool = TransientPool::new();
2376        let mut graph = RenderGraph::new(queue);
2377        let swap = graph.import_image("swapchain", imported);
2378        renderer.add_pass(&mut graph, swap);
2379        assert_eq!(graph.pass_count(), 0, "an empty frame adds no pass");
2380
2381        // The graph still has the imported target and nothing to do with it,
2382        // which compiles and executes to the final transition alone.
2383        let compiled = graph.compile(&pool).expect("an empty frame is a legal one");
2384        let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
2385            label: Some("empty frame"),
2386            queue,
2387        });
2388        compiled
2389            .execute(device.as_ref(), &mut pool, encoder.as_mut(), None)
2390            .expect("execution succeeded");
2391        let commands = encoder.finish().expect("recording succeeded");
2392        device.destroy_command_buffer(commands);
2393        pool.destroy(device.as_ref());
2394        device.destroy_image_view(imported.view);
2395        device.destroy_image(imported.image);
2396
2397        assert!(draws(&recorder).is_empty(), "an empty frame draws nothing");
2398        renderer.destroy(device.as_ref());
2399        recorder.assert_valid();
2400    }
2401
2402    /// A sprite naming a sheet nobody registered is refused by name, and the
2403    /// frame's buffers are left as they were rather than half-overwritten.
2404    #[test]
2405    fn a_sprite_naming_an_unregistered_sheet_is_refused() {
2406        let recorder = Recorder::new();
2407        let (device, queue) = open(&recorder);
2408        let mut renderer = SpriteRenderer::new(device.as_ref(), queue, TARGET).expect("built");
2409        let sheet = register(&mut renderer, device.as_ref(), "only");
2410
2411        recorder.clear();
2412        let error = renderer
2413            .begin_frame(
2414                device.as_ref(),
2415                &[sprite(sheet), sprite(SheetId(7))],
2416                Mat4::IDENTITY,
2417                EXTENT,
2418            )
2419            .expect_err("sheet 7 does not exist");
2420        let message = error.to_string();
2421        assert!(
2422            message.contains("sprite 1") && message.contains("sheet 7"),
2423            "the error must name the sprite and the sheet, got: {message}"
2424        );
2425        assert!(
2426            !recorder
2427                .events()
2428                .iter()
2429                .any(|event| matches!(event, Event::BufferWritten { .. })),
2430            "a refused frame must not have written anything"
2431        );
2432
2433        renderer.destroy(device.as_ref());
2434    }
2435
2436    // -----------------------------------------------------------------------
2437    // Pipeline state
2438    // -----------------------------------------------------------------------
2439
2440    /// **The recorder cannot see pipeline state.**
2441    /// [`crcbl_hal::null::Event::Created`] keeps an [`ObjectKind`] and a label
2442    /// and discards the descriptor, so there is no command stream to assert the
2443    /// blend mode against — this checks the *value* `build` hands to
2444    /// `create_graphics_pipeline`, which is the strongest thing available
2445    /// without a golden image.
2446    ///
2447    /// [`ObjectKind`]: crcbl_hal::null::ObjectKind
2448    #[test]
2449    fn the_pipeline_blends_straight_alpha_and_never_tests_depth() {
2450        let target = color_target(TARGET);
2451        assert_eq!(target.format, TARGET);
2452        assert_eq!(
2453            target.blend,
2454            Some(BlendState::alpha()),
2455            "sprites composite with src*a + dst*(1-a); premultiplied would double the multiply"
2456        );
2457        assert_ne!(
2458            target.blend,
2459            Some(BlendState::premultiplied()),
2460            "the two differ only in the colour source factor, which is exactly why \
2461             this is asserted rather than eyeballed"
2462        );
2463        assert_eq!(target.write_mask, ColorWrites::ALL);
2464
2465        assert!(
2466            SPRITE_DEPTH_STENCIL.is_none(),
2467            "a depth test would discard the half-transparent fragments that make a \
2468             sprite a sprite, and a depth write would order them by z rather than \
2469             by submission"
2470        );
2471    }
2472
2473    /// **Both modes bind the same linear sampler, and the mode reaches the
2474    /// shader on the instance instead.**
2475    ///
2476    /// This is the test that says the seam moved. Slice 3 gave
2477    /// [`SampleMode::Pixel`] a nearest sampler as a named placeholder; a nearest
2478    /// sampler would flatten sharp-bilinear's bent UV back onto a texel centre
2479    /// and produce exactly the nearest-neighbour picture the mode exists to
2480    /// avoid. So there is one sampler, and the difference between the modes is
2481    /// entirely in the instance bytes — which is what this checks, end to end,
2482    /// through `begin_frame`'s real write.
2483    #[test]
2484    fn both_modes_share_one_linear_sampler_and_differ_only_on_the_instance() {
2485        let recorder = Recorder::new();
2486        let (device, queue) = open(&recorder);
2487        let mut renderer = SpriteRenderer::new(device.as_ref(), queue, TARGET).expect("built");
2488
2489        assert_eq!(
2490            recorder.live_objects(crcbl_hal::null::ObjectKind::Sampler),
2491            1,
2492            "one sampler for the whole pass: a second one would be the nearest \
2493             placeholder coming back"
2494        );
2495
2496        // Two sheets of *different* sizes as well as different modes, so a lane
2497        // taken from the wrong sheet is visible and not just the mode being
2498        // wrong.
2499        let big = vec![255u8; 4 * 2 * 4];
2500        let small = [255u8; 2 * 2 * 4];
2501        let sharp = renderer
2502            .register_sheet(
2503                device.as_ref(),
2504                &SheetDesc {
2505                    label: "pixel sheet",
2506                    width: 4,
2507                    height: 2,
2508                    sample: SampleMode::Pixel,
2509                    pixels: &big,
2510                },
2511            )
2512            .expect("upload");
2513        let smooth = renderer
2514            .register_sheet(
2515                device.as_ref(),
2516                &SheetDesc {
2517                    label: "smooth sheet",
2518                    width: 2,
2519                    height: 2,
2520                    sample: SampleMode::Smooth,
2521                    pixels: &small,
2522                },
2523            )
2524            .expect("upload");
2525
2526        assert_eq!(
2527            recorder.live_objects(crcbl_hal::null::ObjectKind::Sampler),
2528            1,
2529            "registering sheets in two different modes must not create a second \
2530             sampler either"
2531        );
2532        assert_eq!(
2533            renderer.sheets[sharp.index() as usize].lane,
2534            [4.0, 2.0, SAMPLE_PIXEL, 0.0],
2535            "a Pixel sheet's lane is its texel size and mode 1"
2536        );
2537        assert_eq!(
2538            renderer.sheets[smooth.index() as usize].lane,
2539            [2.0, 2.0, SAMPLE_SMOOTH, 0.0],
2540            "a Smooth sheet's lane is its texel size and mode 0"
2541        );
2542
2543        // And that lane is what `begin_frame` stamps onto the instance, from the
2544        // sheet the sprite named rather than from the sprite.
2545        let stamped = sprite(smooth).instance(renderer.sheets[smooth.index() as usize].lane);
2546        assert_eq!(stamped.sheet, [2.0, 2.0, SAMPLE_SMOOTH, 0.0]);
2547
2548        renderer
2549            .begin_frame(
2550                device.as_ref(),
2551                &[sprite(sharp), sprite(smooth)],
2552                Mat4::IDENTITY,
2553                EXTENT,
2554            )
2555            .expect("upload");
2556
2557        renderer.destroy(device.as_ref());
2558        recorder.assert_valid();
2559    }
2560
2561    /// `register_baked` reads the size off the **image** and the mode off the
2562    /// **sheet**, which is the whole content of the mapping it exists to hold.
2563    ///
2564    /// The two are handed sizes that *disagree* — something
2565    /// [`crcbl_sprite::load::load`] rejects outright with `SizeMismatch`, which
2566    /// is exactly why it has to be built by hand here. A version that took the
2567    /// width off `loaded.sheet` would pass every test that goes through `load`,
2568    /// because there the two always agree; it would also be re-deciding a
2569    /// question `load` already answered against the picture.
2570    #[test]
2571    fn a_baked_sheet_is_registered_at_the_size_of_its_image() {
2572        use crcbl_sprite::load::{Loaded, Rgba8};
2573        use crcbl_sprite::{Frame, Rect, Sheet};
2574
2575        let recorder = Recorder::new();
2576        let (device, queue) = open(&recorder);
2577        let mut renderer = SpriteRenderer::new(device.as_ref(), queue, TARGET).expect("built");
2578
2579        let loaded = Loaded {
2580            sheet: Sheet {
2581                width: 2,
2582                height: 2,
2583                frames: vec![Frame {
2584                    name: "default".to_owned(),
2585                    rect: Rect::new(0, 0, 2, 2),
2586                    hold: 1,
2587                }],
2588                clips: Vec::new(),
2589                nine: None,
2590                sample: SampleMode::Pixel,
2591            },
2592            image: Rgba8 {
2593                width: 4,
2594                height: 2,
2595                pixels: vec![255u8; 4 * 2 * 4],
2596            },
2597        };
2598
2599        let id = renderer
2600            .register_baked(device.as_ref(), "baked", &loaded)
2601            .expect("upload");
2602
2603        assert_eq!(
2604            renderer.sheets[id.index() as usize].lane,
2605            [4.0, 2.0, SAMPLE_PIXEL, 0.0],
2606            "the lane is the image's size and the sheet's mode"
2607        );
2608
2609        renderer.destroy(device.as_ref());
2610        recorder.assert_valid();
2611    }
2612
2613    // -----------------------------------------------------------------------
2614    // Lifetime
2615    // -----------------------------------------------------------------------
2616
2617    /// Teardown releases everything, including a registered sheet's image, its
2618    /// view and its bind group — the three objects `destroy` would leak if it
2619    /// only walked the per-frame vectors.
2620    #[test]
2621    fn teardown_releases_every_sheet_as_well_as_the_frame_resources() {
2622        let recorder = Recorder::new();
2623        let (device, queue) = open(&recorder);
2624        let before = recorder.total_live_objects();
2625
2626        let mut renderer = SpriteRenderer::new(device.as_ref(), queue, TARGET).expect("built");
2627        let a = register(&mut renderer, device.as_ref(), "a");
2628        let b = register(&mut renderer, device.as_ref(), "b");
2629        assert_eq!(renderer.sheet_count(), 2);
2630        assert_eq!(
2631            (a.index(), b.index()),
2632            (0, 1),
2633            "ids are handed out in order"
2634        );
2635        assert!(
2636            recorder.live_objects(crcbl_hal::null::ObjectKind::Image) >= 2,
2637            "the test is only meaningful if the sheets really were uploaded"
2638        );
2639
2640        for _ in 0..FRAMES_IN_FLIGHT * 2 {
2641            renderer
2642                .begin_frame(
2643                    device.as_ref(),
2644                    &[sprite(a), sprite(b)],
2645                    Mat4::IDENTITY,
2646                    EXTENT,
2647                )
2648                .expect("upload");
2649        }
2650        renderer.destroy(device.as_ref());
2651
2652        assert_eq!(
2653            recorder.total_live_objects(),
2654            before,
2655            "destroy must release the sheets' images, views and bind groups too"
2656        );
2657        recorder.assert_valid();
2658    }
2659
2660    /// The failure path in `new`. A device that can bind only **one** descriptor
2661    /// set refuses this pass's pipeline layout, which asks for two — after the
2662    /// samplers, both layouts, four buffers and two bind groups already exist.
2663    #[test]
2664    fn a_new_that_fails_part_way_leaks_nothing() {
2665        let recorder = Recorder::new();
2666        let instance = NullInstance::new(DeviceCaps {
2667            features: Features::GPU_DRIVEN,
2668            limits: Limits {
2669                max_bind_groups: 1,
2670                ..Limits::desktop()
2671            },
2672        })
2673        .with_recorder(recorder.clone());
2674        let adapter = instance.adapters().remove(0);
2675        let device = instance
2676            .create_device(&DeviceDesc {
2677                label: Some("one bind group"),
2678                adapter: adapter.id,
2679                required_features: Features::GPU_DRIVEN,
2680                optional_features: Features::empty(),
2681                compatible_surface: None,
2682            })
2683            .expect("the null backend always opens");
2684        let queue = device.queue(QueueKind::Graphics).expect("always present");
2685        let before = recorder.total_live_objects();
2686
2687        let error = SpriteRenderer::new(device.as_ref(), queue, TARGET)
2688            .expect_err("two bind groups do not fit in max_bind_groups 1");
2689        assert!(
2690            error.to_string().contains("max_bind_groups"),
2691            "the failure must be the pipeline layout, not something earlier: {error}"
2692        );
2693        assert!(
2694            recorder
2695                .events()
2696                .iter()
2697                .any(|event| matches!(event, Event::Created { kind, .. } if *kind
2698                    == crcbl_hal::null::ObjectKind::BindGroup)),
2699            "the test is only meaningful if objects really were created before the failure"
2700        );
2701        assert_eq!(
2702            recorder.total_live_objects(),
2703            before,
2704            "everything created before the failure must be handed back"
2705        );
2706        recorder.assert_valid();
2707    }
2708
2709    /// **The bug `ui_pass` had and this must not reinherit.** A scene whose
2710    /// sprite count has not changed must not allocate: the ring is compared in
2711    /// *bytes* against *bytes*, and comparing bytes against a sprite count is
2712    /// what made the UI pass destroy and recreate its buffers and its bind group
2713    /// every single frame.
2714    #[test]
2715    fn a_second_frame_of_the_same_size_creates_no_buffer() {
2716        let recorder = Recorder::new();
2717        let (device, queue) = open(&recorder);
2718        let mut renderer = SpriteRenderer::new(device.as_ref(), queue, TARGET).expect("built");
2719        let sheet = register(&mut renderer, device.as_ref(), "sheet");
2720        let sprites = vec![sprite(sheet); 8];
2721
2722        // Two frames to fill both slots of the ring, then measure.
2723        for _ in 0..FRAMES_IN_FLIGHT {
2724            renderer
2725                .begin_frame(device.as_ref(), &sprites, Mat4::IDENTITY, EXTENT)
2726                .expect("upload");
2727        }
2728        let buffers = renderer.instance_buffers.clone();
2729        let groups = renderer.frame_groups.clone();
2730        let settled = recorder.total_live_objects();
2731        recorder.clear();
2732
2733        for _ in 0..8 {
2734            renderer
2735                .begin_frame(device.as_ref(), &sprites, Mat4::IDENTITY, EXTENT)
2736                .expect("upload");
2737        }
2738        assert!(
2739            !recorder
2740                .events()
2741                .iter()
2742                .any(|event| matches!(event, Event::Created { .. })),
2743            "a steady-state frame must create nothing at all"
2744        );
2745        assert_eq!(recorder.total_live_objects(), settled);
2746        assert_eq!(
2747            renderer.instance_buffers, buffers,
2748            "the instance ring must be reused, not reallocated"
2749        );
2750        assert_eq!(
2751            renderer.frame_groups, groups,
2752            "the frame bind group only changes when its instance buffer does"
2753        );
2754
2755        renderer.destroy(device.as_ref());
2756        recorder.assert_valid();
2757    }
2758
2759    /// It still grows when a frame genuinely needs more room, and the old buffer
2760    /// is released rather than leaked.
2761    #[test]
2762    fn a_bigger_frame_grows_the_ring_and_rebinds_it() {
2763        let recorder = Recorder::new();
2764        let (device, queue) = open(&recorder);
2765        let mut renderer = SpriteRenderer::new(device.as_ref(), queue, TARGET).expect("built");
2766        let sheet = register(&mut renderer, device.as_ref(), "sheet");
2767
2768        let small = vec![sprite(sheet); 4];
2769        renderer
2770            .begin_frame(device.as_ref(), &small, Mat4::IDENTITY, EXTENT)
2771            .expect("upload");
2772        assert_eq!(
2773            renderer.instance_capacity[renderer.frame],
2774            INITIAL_RING_BYTES
2775        );
2776
2777        // 1024 bytes holds 16 instances; 64 needs 4096.
2778        let big = vec![sprite(sheet); 64];
2779        let before_groups = renderer.frame_groups.clone();
2780        for _ in 0..FRAMES_IN_FLIGHT {
2781            renderer
2782                .begin_frame(device.as_ref(), &big, Mat4::IDENTITY, EXTENT)
2783                .expect("upload");
2784        }
2785        let index = renderer.frame;
2786        assert!(
2787            renderer.instance_capacity[index] >= (64 * INSTANCE_STRIDE) as u64,
2788            "the ring must actually fit the frame, got {}",
2789            renderer.instance_capacity[index]
2790        );
2791        assert_ne!(
2792            renderer.frame_groups[index], before_groups[index],
2793            "a replaced instance buffer needs a bind group that names it"
2794        );
2795
2796        renderer.destroy(device.as_ref());
2797        recorder.assert_valid();
2798    }
2799
2800    /// `grown` rounds up rather than fitting exactly, so a scene that gains a
2801    /// sprite a frame reallocates a handful of times rather than every frame.
2802    #[test]
2803    fn the_ring_grows_in_power_of_two_steps() {
2804        assert_eq!(grown(1), INITIAL_RING_BYTES);
2805        assert_eq!(grown(INITIAL_RING_BYTES), INITIAL_RING_BYTES);
2806        assert_eq!(grown(INITIAL_RING_BYTES + 1), 2048);
2807        assert_eq!(grown(3072), 4096);
2808        for needed in [1u64, 49, 1025, 3072, 100_000] {
2809            let size = grown(needed);
2810            assert!(size >= needed);
2811            assert_eq!(size % 256, 0, "{needed} grew to an unaligned {size}");
2812        }
2813    }
2814}