Skip to main content

crcbl_frame/
texture.rs

1//! One texture upload, for every format and every caller.
2//!
3//! ```text
4//! pixels ──pad rows to the device's copy alignment──▶ staging buffer
5//!            │
6//!            └──barrier ▸ copy_buffer_to_image ▸ barrier──▶ sampled image + view
7//! ```
8//!
9//! # One layer or several, one level or a chain
10//!
11//! [`upload_texture`] uploads a single-layer `D2` image, which is what a sprite
12//! sheet and a glyph atlas are. [`upload_texture_layers`] uploads several layers
13//! of the same size into one `D2Array` image, which is
14//! topic 03 §3.2's
15//! [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) page: one image, one
16//! descriptor, and a layer index in the material row selecting between them.
17//! [`upload_texture_mip_layers`] is the same page with every layer's mip chain
18//! behind it — topic 43's filtering rung, whose chain
19//! [`crate::mip`] builds on the host.
20//!
21//! All three go through the same body, and it records **one copy per level of
22//! every layer** rather than one covering all of them. That is not caution: a
23//! copy region's extent is a 2D extent on every backend here — `crcbl-dx12`
24//! refuses a `depth_or_layers` other than 1 by name, because
25//! `CopyTextureRegion` addresses one subresource — so the layer travels in
26//! [`ImageSubresourceLayers::base_layer`], the level in
27//! [`ImageSubresourceLayers::mip`], and the buffer offset says where that
28//! subresource's rows start.
29//!
30//! # A page that starts empty
31//!
32//! [`upload_cleared_texture`] is the same copy for an image that is mostly
33//! zeroes — an atlas when it is created. The zeroes are written by a
34//! [`clear_buffer`](crcbl_hal::CommandEncoder::clear_buffer) on the GPU and
35//! copied into every layer, and only the rectangles written over them are
36//! staged from the host. See that function for why the difference is the wasm
37//! heap's.
38//!
39//! # Several at once
40//!
41//! Each function above is a batch of one: it records its copies, submits them
42//! and waits. A caller with many uploads to make before its first frame records
43//! them all into one [`UploadBatch`] instead, and pays for one submission and
44//! one wait. The batch also carries [`UploadBatch::fill`], the same staging
45//! copy into a device-local *buffer*, so a renderer's start-up state rides the
46//! same submission as its textures. A caller with work of its own to do before
47//! its first frame — [`crate::ui_pass`]'s renderer, and `crcbl_render`'s
48//! forward renderer — submits the batch with
49//! [`UploadBatch::submit_deferred`] instead, which does not wait: the copies
50//! run under that work, and the [`PendingUpload`] it returns frees the staging
51//! once the GPU is past it.
52//!
53//! This is a **startup** path, not a frame path: it records its own barriers
54//! and blocks on [`Device::wait_idle`], which is only legal because no graph
55//! is being recorded while it runs. See this crate's docs on the one rule — the
56//! two staging uploads (`crcbl_render::forward`'s cube and this) are its named
57//! exceptions. Its barriers name only the image it creates, so a caller between
58//! two frames — `ForwardRenderer::replace_page`
59//! reloading a page — touches nothing a frame in flight reads, and the wait
60//! means no frame can bind the image before its copy has landed. A deferred
61//! submit has no wait, and leans on queue order instead: see [`PendingUpload`]
62//! for why that holds for a frame on the same queue.
63//!
64//! # Why it is not in `ui_pass`
65//!
66//! It was, and it was `R8_UNORM` only, with the glyph atlas's labels baked in.
67//! The interesting part is that the old code was *right by coincidence*: it
68//! computed a row pitch from `width`, called it `row_texels`, and handed it to
69//! [`BufferImageCopy::buffer_row_length`] — which really is in texels, and
70//! really did equal the byte count, because `R8Unorm` is one byte per texel.
71//! For `Rgba8Unorm` the two differ by four, so the pitch here is computed in
72//! **bytes** and converted back to texels exactly once, at the copy.
73
74use crcbl_hal::{
75    BufferCopy, BufferDesc, BufferImageCopy, BufferUsage, CommandEncoder, CommandEncoderDesc,
76    Device, Extent3d, Features, Format, HalError, ImageAspect, ImageDesc, ImageHandle,
77    ImageSubresourceLayers, ImageSubresourceRange, ImageType, ImageUsage, ImageViewDesc,
78    ImageViewHandle, ImageViewType, MemoryLocation, Offset3d, QueueHandle, QueueKind,
79    ResourceState, SemaphoreDesc, SemaphoreKind, SemaphoreSignal, SubmitInfo,
80};
81
82use crate::mip::level_extent;
83
84/// A texture that has been uploaded: the image, and the view callers bind.
85///
86/// The two travel together because they die together, and every caller that
87/// kept them as two loose handles has had to remember that on both its failure
88/// path and its teardown path. [`UploadedTexture::destroy`] is the one place
89/// the order lives.
90#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub struct UploadedTexture {
92    /// The device-local image the copy filled.
93    pub image: ImageHandle,
94    /// A full-subresource colour view of [`UploadedTexture::image`]: `D2` from
95    /// [`upload_texture`], `D2Array` from [`upload_texture_layers`] and
96    /// [`upload_texture_mip_layers`].
97    pub view: ImageViewHandle,
98}
99
100impl UploadedTexture {
101    /// Releases the view and then the image. The device must be idle.
102    pub fn destroy(&self, device: &dyn Device) {
103        device.destroy_image_view(self.view);
104        device.destroy_image(self.image);
105    }
106}
107
108/// Uploads a 2D colour texture via a staging-buffer copy, and returns the image
109/// and a view onto it.
110///
111/// `label` names the image and the view, and is the stem of the staging
112/// buffer's and the encoder's names, so a capture shows which texture an
113/// upload belonged to.
114///
115/// `pixels` must be exactly `width * height * texel_size` bytes, tightly
116/// packed; the row padding the device's copy alignment wants is added here.
117/// Padding rather than packing is what makes one upload path work on both
118/// backends: Vulkan takes either, WebGPU requires a 256-byte row pitch and says
119/// so through
120/// [`optimal_buffer_copy_offset_alignment`](crcbl_hal::Limits::optimal_buffer_copy_offset_alignment).
121///
122/// Every object this creates is released on every path out, including the
123/// failing ones: a `?` that dropped the staging buffer on the floor would leak
124/// one per failed startup, and the recorder's leak assertions would only notice
125/// once something actually failed.
126///
127/// # Errors
128///
129/// [`HalError::InvalidDescriptor`] if `format` has no single colour plane, if
130/// either extent is zero, or if `pixels` is not exactly the size the extent and
131/// the format imply — the last of which used to be a `copy_from_slice` panic
132/// naming neither number. [`HalError`] from any seam call otherwise; an extent
133/// past the device's `max_image_2d` is the device's to refuse, not this
134/// function's.
135pub fn upload_texture(
136    device: &dyn Device,
137    queue: QueueHandle,
138    label: &str,
139    format: Format,
140    width: u32,
141    height: u32,
142    pixels: &[u8],
143) -> Result<UploadedTexture, HalError> {
144    upload(
145        device,
146        queue,
147        label,
148        format,
149        (width, height),
150        &[&[pixels]],
151        ImageViewType::D2,
152    )
153}
154
155/// Uploads several equally-sized layers into one `D2Array` colour image, and
156/// returns it with an array view onto every layer.
157///
158/// §3.2's [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) page: the index a
159/// material row carries is a layer of the image this returns. One image rather
160/// than one descriptor per texture is what makes the lookup need no
161/// [`Features::DESCRIPTOR_INDEXING`](crcbl_hal::Features::DESCRIPTOR_INDEXING),
162/// and therefore run on every backend the engine has — see
163/// `crcbl_render::forward`, which builds the page this crate's only caller binds.
164///
165/// Every slice in `layers` must be exactly one tightly packed
166/// `width * height * texel_size` image, and they become layers 0, 1, … in the
167/// order given. [`upload_texture`]'s account of the label, the row padding and
168/// the release-on-every-path rule applies here unchanged. The image has one
169/// mip level; [`upload_texture_mip_layers`] is the form that carries a chain.
170///
171/// # Errors
172///
173/// [`upload_texture`]'s errors, plus [`HalError::InvalidDescriptor`] when
174/// `layers` is empty — a zero-layer image is not a page, and it reaches the
175/// device as a zero extent whose complaint names a different thing. A layer
176/// count past the device's `max_image_array_layers` is the device's to refuse.
177pub fn upload_texture_layers(
178    device: &dyn Device,
179    queue: QueueHandle,
180    label: &str,
181    format: Format,
182    width: u32,
183    height: u32,
184    layers: &[&[u8]],
185) -> Result<UploadedTexture, HalError> {
186    let chains: Vec<[&[u8]; 1]> = layers.iter().map(|pixels| [*pixels]).collect();
187    let layers: Vec<&[&[u8]]> = chains.iter().map(|chain| &chain[..]).collect();
188    upload(
189        device,
190        queue,
191        label,
192        format,
193        (width, height),
194        &layers,
195        ImageViewType::D2Array,
196    )
197}
198
199/// [`upload_texture_layers`] with a mip chain behind every layer: one
200/// `D2Array` image whose level count is the chain's length, and an array view
201/// onto every level of every layer.
202///
203/// `layers[layer][level]` is level `level` of layer `layer`, tightly packed at
204/// that level's extent — `width` and `height` each halved per level and never
205/// below one texel, which is [`crate::mip::level_extent`] and every backend's
206/// own definition. Every layer carries the same number of levels, at least one
207/// and at most the full chain
208/// [`Extent3d::full_mip_levels`](crcbl_hal::Extent3d::full_mip_levels) counts;
209/// a shorter chain is legal and leaves the sampler's `lod_max` to the caller.
210///
211/// # Errors
212///
213/// [`upload_texture_layers`]'s errors, plus [`HalError::InvalidDescriptor`]
214/// when a layer has no levels, when two layers disagree on how many, when the
215/// count exceeds the full chain, or when a level is not exactly its own
216/// extent's worth of texels — each naming the layer and the level.
217pub fn upload_texture_mip_layers(
218    device: &dyn Device,
219    queue: QueueHandle,
220    label: &str,
221    format: Format,
222    width: u32,
223    height: u32,
224    layers: &[&[&[u8]]],
225) -> Result<UploadedTexture, HalError> {
226    upload(
227        device,
228        queue,
229        label,
230        format,
231        (width, height),
232        layers,
233        ImageViewType::D2Array,
234    )
235}
236
237/// Texels written over an [`upload_cleared_texture`] image as it is created: a
238/// `width` by `height` rectangle of layer `layer`, its top-left texel at `x`,
239/// `y`.
240#[derive(Clone, Copy, Debug)]
241pub struct TexturePatch<'a> {
242    /// The array layer the rectangle is written to.
243    pub layer: u32,
244    /// The rectangle's left column.
245    pub x: u32,
246    /// The rectangle's top row.
247    pub y: u32,
248    /// Its width in texels.
249    pub width: u32,
250    /// Its height in texels.
251    pub height: u32,
252    /// Exactly `width * height * texel_size` bytes, tightly packed, rows top to
253    /// bottom.
254    pub pixels: &'a [u8],
255}
256
257/// The image [`upload_cleared_texture`] creates, and what goes on it.
258#[derive(Clone, Copy, Debug)]
259pub struct ClearedTextureDesc<'a> {
260    /// Names the image and the view, and is the stem of the buffers' and the
261    /// encoder's names, as in [`upload_texture`].
262    pub label: &'a str,
263    /// An uncompressed format with a single colour plane.
264    pub format: Format,
265    /// Width of every layer, in texels.
266    pub width: u32,
267    /// Height of every layer, in texels.
268    pub height: u32,
269    /// Array layers in the image; at least one.
270    pub layers: u32,
271    /// `D2` or `D2Array`: the shader's declaration decides, not `layers`.
272    pub view_type: ImageViewType,
273    /// Rectangles written over the zeroes, in order.
274    pub patches: &'a [TexturePatch<'a>],
275}
276
277/// Creates a sampled colour image whose every texel is zero, with `patches`
278/// written over it, and returns it with a full view.
279///
280/// **For a page that is mostly empty**, which is what an atlas is when it is
281/// created: [`crate::ui_pass`]'s image atlas and glyph pages. Staging such a
282/// page through [`upload_texture`] builds every zero texel on the host, pads a
283/// second copy of it, and writes it into a staging buffer — and on
284/// `crcbl-webgpu` that write is bytes on the command stream, which lives in the
285/// wasm heap, grows to hold the whole start-up frame and never gives the
286/// address space back. Here the zeroes never exist on the host: one
287/// device-local buffer a layer in size is zeroed by
288/// [`clear_buffer`](crcbl_hal::CommandEncoder::clear_buffer) and copied into
289/// every layer, and only the patches are staged and written. The page is
290/// transparent black where nothing was patched, on every backend, rather than
291/// whatever an uninitialised image held.
292///
293/// One mip level. The same startup rules as [`upload_texture`]: it records its
294/// own barriers, blocks on [`Device::wait_idle`], and releases every buffer it
295/// created on every path out.
296///
297/// # Errors
298///
299/// [`upload_texture`]'s format and extent errors;
300/// [`HalError::InvalidDescriptor`] for zero layers, and for a patch that is
301/// empty, is not on a layer or inside the extent, or whose `pixels` is not its
302/// own size — naming the patch. [`HalError`] from any seam call otherwise.
303pub fn upload_cleared_texture(
304    device: &dyn Device,
305    queue: QueueHandle,
306    desc: &ClearedTextureDesc<'_>,
307) -> Result<UploadedTexture, HalError> {
308    let mut batch = UploadBatch::new(device, queue, desc.label);
309    let texture = batch.cleared_texture(desc)?;
310    batch.submit_one(texture)
311}
312
313/// [`upload_cleared_texture`]'s validation and staging, recorded into
314/// `batch`.
315fn stage_cleared_texture(
316    batch: &mut UploadBatch<'_>,
317    desc: &ClearedTextureDesc<'_>,
318) -> Result<UploadedTexture, HalError> {
319    let device = batch.device;
320    let label = desc.label;
321    let texel = image_texel(label, desc.format, (desc.width, desc.height))?;
322    if desc.layers == 0 {
323        return Err(HalError::InvalidDescriptor(format!(
324            "{label}: a texture needs at least one layer"
325        )));
326    }
327    let alignment = device
328        .caps()
329        .limits
330        .optimal_buffer_copy_offset_alignment
331        .max(1);
332    let full = u64::from(desc.width) * u64::from(texel);
333    let full_pitch = padded_row_pitch(full, texel, alignment);
334    // Whole words: `vkCmdFillBuffer` and `crcbl-dx12`'s clear refuse a size that
335    // is not a multiple of four.
336    let cleared = (full_pitch * u64::from(desc.height)).next_multiple_of(CLEAR_WORD_BYTES);
337    let mut patched = Vec::new();
338    let mut patch_regions = Vec::with_capacity(desc.patches.len());
339    for (index, patch) in desc.patches.iter().enumerate() {
340        let inside = patch
341            .x
342            .checked_add(patch.width)
343            .is_some_and(|right| right <= desc.width)
344            && patch
345                .y
346                .checked_add(patch.height)
347                .is_some_and(|bottom| bottom <= desc.height);
348        if patch.width == 0 || patch.height == 0 || patch.layer >= desc.layers || !inside {
349            return Err(HalError::InvalidDescriptor(format!(
350                "{label}: patch {index} is {}x{} at {},{} on layer {}, which is not a non-empty \
351                 rectangle inside a {}x{} image of {} layer(s)",
352                patch.width,
353                patch.height,
354                patch.x,
355                patch.y,
356                patch.layer,
357                desc.width,
358                desc.height,
359                desc.layers
360            )));
361        }
362        if let Some(other) = desc.patches[..index]
363            .iter()
364            .position(|earlier| earlier.layer == patch.layer && overlaps(earlier, patch))
365        {
366            return Err(HalError::InvalidDescriptor(format!(
367                "{label}: patch {index} overlaps patch {other} on layer {}, and a texel written \
368                 twice in one upload is a synchronisation hazard",
369                patch.layer
370            )));
371        }
372        let row_bytes = u64::from(patch.width) * u64::from(texel);
373        let expected = row_bytes * u64::from(patch.height);
374        if patch.pixels.len() as u64 != expected {
375            return Err(HalError::InvalidDescriptor(format!(
376                "{label}: patch {index} is {}x{} {:?}, {expected} bytes, got {}",
377                patch.width,
378                patch.height,
379                desc.format,
380                patch.pixels.len()
381            )));
382        }
383        let row_pitch = padded_row_pitch(row_bytes, texel, alignment);
384        let staged =
385            stage_rows(row_bytes, patch.height, row_pitch, patch.pixels).ok_or_else(|| {
386                HalError::InvalidDescriptor(format!(
387                    "{label}: patch {index} does not fit in this host's address space"
388                ))
389            })?;
390        patch_regions.push(StagedRegion {
391            buffer_offset: patched.len() as u64,
392            row_texels: u32::try_from(row_pitch / u64::from(texel)).unwrap_or(u32::MAX),
393            extent: Extent3d::d2(patch.width, patch.height),
394            layer: patch.layer,
395            mip: 0,
396            image_offset: Offset3d {
397                x: i32::try_from(patch.x).unwrap_or(i32::MAX),
398                y: i32::try_from(patch.y).unwrap_or(i32::MAX),
399                z: 0,
400            },
401        });
402        patched.extend_from_slice(&staged);
403    }
404
405    // The zeroes go only where no patch does, so no texel is written twice: two
406    // unbarriered writes to one subresource in one command buffer are a
407    // synchronisation hazard Vulkan's sync validation reports.
408    let row_texels = u32::try_from(full_pitch / u64::from(texel)).unwrap_or(u32::MAX);
409    let layer_regions: Vec<StagedRegion> = (0..desc.layers)
410        .flat_map(|layer| {
411            let covered: Vec<&TexturePatch<'_>> = desc
412                .patches
413                .iter()
414                .filter(|patch| patch.layer == layer)
415                .collect();
416            uncovered(desc.width, desc.height, &covered)
417                .into_iter()
418                .map(move |(x, y, width, height)| StagedRegion {
419                    buffer_offset: 0,
420                    row_texels,
421                    extent: Extent3d::d2(width, height),
422                    layer,
423                    mip: 0,
424                    image_offset: Offset3d {
425                        x: i32::try_from(x).unwrap_or(i32::MAX),
426                        y: i32::try_from(y).unwrap_or(i32::MAX),
427                        z: 0,
428                    },
429                })
430        })
431        .collect();
432
433    // Device-local, because a clear writes into the buffer on the GPU: a
434    // `crcbl-dx12` upload-heap buffer can never be a copy destination.
435    let zero_label = format!("{label} zero");
436    let zero = device.create_buffer(&BufferDesc {
437        label: Some(&zero_label),
438        size: cleared,
439        usage: BufferUsage::TRANSFER_SRC | BufferUsage::TRANSFER_DST,
440        memory: MemoryLocation::DeviceLocal,
441    })?;
442    batch.buffers.push(zero);
443    let staging = if patched.is_empty() {
444        None
445    } else {
446        let staging = create_staging(device, label, &patched)?;
447        batch.buffers.push(staging);
448        Some(staging)
449    };
450    let zero_source = CopySource {
451        buffer: zero,
452        regions: &layer_regions,
453    };
454    let sources: Vec<CopySource<'_>> = core::iter::once(zero_source)
455        .chain(staging.map(|buffer| CopySource {
456            buffer,
457            regions: &patch_regions,
458        }))
459        .collect();
460    batch.record(&UploadArgs {
461        label,
462        format: desc.format,
463        width: desc.width,
464        height: desc.height,
465        layer_count: desc.layers,
466        mip_levels: 1,
467        view_type: desc.view_type,
468        cleared: Some((zero, cleared)),
469        sources: &sources,
470    })
471}
472
473/// Whether two patches share a texel.
474fn overlaps(a: &TexturePatch<'_>, b: &TexturePatch<'_>) -> bool {
475    a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height
476}
477
478/// The rectangles of a `width` by `height` layer that no patch in `covered`
479/// touches, as `(x, y, width, height)`: the layer cut into horizontal bands at
480/// every patch's top and bottom edge, and each band's gaps between patches.
481/// The patches must not overlap and must lie inside the layer.
482fn uncovered(width: u32, height: u32, covered: &[&TexturePatch<'_>]) -> Vec<(u32, u32, u32, u32)> {
483    let mut edges: Vec<u32> = covered
484        .iter()
485        .flat_map(|patch| [patch.y, patch.y + patch.height])
486        .chain([0, height])
487        .collect();
488    edges.sort_unstable();
489    edges.dedup();
490    let mut gaps = Vec::new();
491    for band in edges.windows(2) {
492        let (top, bottom) = (band[0], band[1]);
493        let mut spans: Vec<(u32, u32)> = covered
494            .iter()
495            .filter(|patch| patch.y < bottom && top < patch.y + patch.height)
496            .map(|patch| (patch.x, patch.x + patch.width))
497            .collect();
498        spans.sort_unstable();
499        let mut x = 0;
500        for (left, right) in spans.into_iter().chain([(width, width)]) {
501            if left > x {
502                gaps.push((x, top, left - x, bottom - top));
503            }
504            x = x.max(right);
505        }
506    }
507    gaps
508}
509
510/// The word [`clear_buffer`](crcbl_hal::CommandEncoder::clear_buffer) zeroes in
511/// on the backends that fill `u32`s, and so the unit its size is rounded to.
512const CLEAR_WORD_BYTES: u64 = 4;
513
514/// The body the public uploads share, as a batch of one.
515///
516/// `extent` is `(width, height)` as one argument rather than two, which is what
517/// keeps this inside the argument count the public wrappers already sit at.
518fn upload(
519    device: &dyn Device,
520    queue: QueueHandle,
521    label: &str,
522    format: Format,
523    extent: (u32, u32),
524    layers: &[&[&[u8]]],
525    view_type: ImageViewType,
526) -> Result<UploadedTexture, HalError> {
527    let mut batch = UploadBatch::new(device, queue, label);
528    let texture = batch.texture(label, format, extent, layers, view_type)?;
529    batch.submit_one(texture)
530}
531
532/// Validates `layers`, stages every level of every layer into one buffer, and
533/// records the copies into `batch`.
534fn stage_texture(
535    batch: &mut UploadBatch<'_>,
536    label: &str,
537    format: Format,
538    extent: (u32, u32),
539    layers: &[&[&[u8]]],
540    view_type: ImageViewType,
541) -> Result<UploadedTexture, HalError> {
542    let device = batch.device;
543    let (width, height) = extent;
544    let texel = image_texel(label, format, extent)?;
545    let layer_count = u32::try_from(layers.len()).unwrap_or(u32::MAX);
546    if layer_count == 0 {
547        return Err(HalError::InvalidDescriptor(format!(
548            "{label}: a texture needs at least one layer of pixels"
549        )));
550    }
551    let mip_levels = u32::try_from(layers[0].len()).unwrap_or(u32::MAX);
552    let full_chain = Extent3d::d2(width, height).full_mip_levels(ImageType::D2);
553    if mip_levels == 0 {
554        return Err(HalError::InvalidDescriptor(format!(
555            "{label}: layer 0 has no mip levels; a layer needs at least its own texels"
556        )));
557    }
558    if mip_levels > full_chain {
559        return Err(HalError::InvalidDescriptor(format!(
560            "{label}: {mip_levels} mip levels for a {width}x{height} image, whose full chain \
561             is {full_chain}"
562        )));
563    }
564
565    let alignment = device
566        .caps()
567        .limits
568        .optimal_buffer_copy_offset_alignment
569        .max(1);
570
571    // Every level of every layer is validated and staged in the order the
572    // copies below read them: layer-major, level-minor. Each level's rows are a
573    // multiple of the alignment, so stacking them puts every subresource's own
574    // offset on it too — which is what lets each copy name one buffer offset.
575    let mut padded = Vec::new();
576    let mut regions = Vec::with_capacity(layers.len() * mip_levels as usize);
577    for (layer, chain) in layers.iter().enumerate() {
578        if chain.len() as u32 != mip_levels {
579            return Err(HalError::InvalidDescriptor(format!(
580                "{label}: layer {layer} carries {} mip levels and layer 0 carries {mip_levels}; \
581                 every layer of one image has the same chain",
582                chain.len()
583            )));
584        }
585        for (level, pixels) in chain.iter().enumerate() {
586            let level_width = level_extent(width, level as u32);
587            let level_height = level_extent(height, level as u32);
588            let row_bytes = u64::from(level_width) * u64::from(texel);
589            let expected = row_bytes * u64::from(level_height);
590            if pixels.len() as u64 != expected {
591                return Err(HalError::InvalidDescriptor(format!(
592                    "{label}: layer {layer} level {level} of a {width}x{height} {format:?} image \
593                     is {level_width}x{level_height}, {expected} bytes ({texel} per texel), got {}",
594                    pixels.len()
595                )));
596            }
597            let row_pitch = padded_row_pitch(row_bytes, texel, alignment);
598            let staged =
599                stage_rows(row_bytes, level_height, row_pitch, pixels).ok_or_else(|| {
600                    HalError::InvalidDescriptor(format!(
601                        "{label}: a staging image of {} bytes and more does not fit in this \
602                         host's address space",
603                        padded.len()
604                    ))
605                })?;
606            regions.push(StagedRegion {
607                buffer_offset: padded.len() as u64,
608                // The copy is in texels; the pitch above is in bytes.
609                // `padded_row_pitch` guarantees the division is exact.
610                row_texels: u32::try_from(row_pitch / u64::from(texel)).unwrap_or(u32::MAX),
611                extent: Extent3d::d2(level_width, level_height),
612                layer: layer as u32,
613                mip: level as u32,
614                image_offset: Offset3d { x: 0, y: 0, z: 0 },
615            });
616            padded.extend_from_slice(&staged);
617        }
618    }
619
620    let staging = create_staging(device, label, &padded)?;
621    batch.buffers.push(staging);
622    batch.record(&UploadArgs {
623        label,
624        format,
625        width,
626        height,
627        layer_count,
628        mip_levels,
629        view_type,
630        cleared: None,
631        sources: &[CopySource {
632            buffer: staging,
633            regions: &regions,
634        }],
635    })
636}
637
638/// The bytes one texel of `format` occupies, once `format` and `extent` are
639/// known to describe an image this module can stage.
640///
641/// # Errors
642///
643/// [`HalError::InvalidDescriptor`] for a format with no single colour plane, a
644/// block-compressed format, or a zero extent, each naming `label`.
645fn image_texel(label: &str, format: Format, (width, height): (u32, u32)) -> Result<u32, HalError> {
646    // `texel_size`, not `block_size`: it is the number a `BufferImageCopy` is
647    // sized against, and it is `None` for exactly the formats this path cannot
648    // describe — a combined depth/stencil format, whose two planes need two
649    // copies and neither of which is a `COLOR` aspect.
650    let texel = format.texel_size(ImageAspect::COLOR).ok_or_else(|| {
651        HalError::InvalidDescriptor(format!(
652            "{label}: {format:?} has no single colour plane, so it cannot be uploaded as one \
653             colour-aspect copy"
654        ))
655    })?;
656    // A compressed format's `block_size` covers a 4×4 block, not one texel, so
657    // the per-texel sizing below would be wrong by a factor of four: a BC1 row
658    // is `ceil(width / 4) × 8` bytes, not `width × 8`. No caller uploads one
659    // today; refuse rather than corrupt.
660    if format.is_compressed() {
661        return Err(HalError::InvalidDescriptor(format!(
662            "{label}: {format:?} is block-compressed and this path sizes per texel; \
663             it cannot be uploaded as a colour-aspect copy"
664        )));
665    }
666    if width == 0 || height == 0 {
667        return Err(HalError::InvalidDescriptor(format!(
668            "{label}: texture extent {width}x{height} must be non-zero in both dimensions"
669        )));
670    }
671    Ok(texel)
672}
673
674/// A host-visible `TRANSFER_SRC` buffer labelled `"{label} staging"` holding
675/// `bytes`, destroyed again if the write fails.
676fn create_staging(
677    device: &dyn Device,
678    label: &str,
679    bytes: &[u8],
680) -> Result<crcbl_hal::BufferHandle, HalError> {
681    let staging_label = format!("{label} staging");
682    let staging = device.create_buffer(&BufferDesc {
683        label: Some(&staging_label),
684        size: bytes.len() as u64,
685        usage: BufferUsage::TRANSFER_SRC,
686        memory: MemoryLocation::HostUpload,
687    })?;
688    if let Err(error) = device.write_buffer(staging, 0, bytes) {
689        device.destroy_buffer(staging);
690        return Err(error);
691    }
692    Ok(staging)
693}
694
695/// A tightly packed region of `format` texels staged for an in-frame copy: a
696/// host-visible `TRANSFER_SRC` buffer holding `pixels` with its rows padded to
697/// the device's copy alignment, and the row pitch in texels a
698/// [`BufferImageCopy`] reading it names.
699///
700/// The frame-time half of what [`upload_texture`] does at start-up, without the
701/// image, the barriers or the wait: the caller records the copy inside a
702/// [`RenderGraph`](crate::graph::RenderGraph) copy pass, which is where a
703/// barrier recorded during a frame belongs. [`ui_pass`](crate::ui_pass)'s image
704/// atlas and `crcbl_render`'s sprite atlas are the callers, and each owns the
705/// buffer's lifetime.
706///
707/// # Errors
708///
709/// [`HalError::InvalidDescriptor`] if `format` has no single colour plane, if
710/// the region is empty or if `pixels` is not exactly `width * height` texels;
711/// [`HalError`] from creating or writing the buffer, which is destroyed again
712/// if the write fails.
713pub fn stage_region(
714    device: &dyn Device,
715    label: &str,
716    format: Format,
717    (width, height): (u32, u32),
718    pixels: &[u8],
719) -> Result<(crcbl_hal::BufferHandle, u32), HalError> {
720    let texel = format.texel_size(ImageAspect::COLOR).ok_or_else(|| {
721        HalError::InvalidDescriptor(format!("{label}: {format:?} has no single colour plane"))
722    })?;
723    let row_bytes = u64::from(width) * u64::from(texel);
724    if width == 0 || height == 0 || pixels.len() as u64 != row_bytes * u64::from(height) {
725        return Err(HalError::InvalidDescriptor(format!(
726            "{label}: a {width}x{height} {format:?} region is {} bytes, got {}",
727            row_bytes * u64::from(height),
728            pixels.len()
729        )));
730    }
731    let alignment = device
732        .caps()
733        .limits
734        .optimal_buffer_copy_offset_alignment
735        .max(1);
736    let row_pitch = padded_row_pitch(row_bytes, texel, alignment);
737    let staged = stage_rows(row_bytes, height, row_pitch, pixels).ok_or_else(|| {
738        HalError::InvalidDescriptor(format!(
739            "{label}: the staged region does not fit in this host's address space"
740        ))
741    })?;
742    let buffer = device.create_buffer(&BufferDesc {
743        label: Some(label),
744        size: staged.len() as u64,
745        usage: BufferUsage::TRANSFER_SRC,
746        memory: MemoryLocation::HostUpload,
747    })?;
748    if let Err(error) = device.write_buffer(buffer, 0, &staged) {
749        device.destroy_buffer(buffer);
750        return Err(error);
751    }
752    // `padded_row_pitch` returns a whole number of texels, so this is exact.
753    let row_texels = u32::try_from(row_pitch / u64::from(texel)).unwrap_or(u32::MAX);
754    Ok((buffer, row_texels))
755}
756
757/// The row pitch in **bytes**: at least `row_bytes`, a multiple of `alignment`,
758/// and a whole number of texels.
759///
760/// The last of those is why this is not one `next_multiple_of` call. The copy
761/// expresses its pitch in texels, so a byte pitch that is not divisible by the
762/// texel size cannot be expressed at all. Every real device's alignment is a
763/// power of two at least as large as any uncompressed texel, so in practice the
764/// lcm *is* the alignment — this costs nothing and removes the assumption.
765fn padded_row_pitch(row_bytes: u64, texel: u32, alignment: u64) -> u64 {
766    let texel = u64::from(texel);
767    let step = texel / gcd(texel, alignment) * alignment;
768    row_bytes.next_multiple_of(step)
769}
770
771/// Greatest common divisor, for [`padded_row_pitch`]'s lcm.
772fn gcd(mut a: u64, mut b: u64) -> u64 {
773    while b != 0 {
774        (a, b) = (b, a % b);
775    }
776    a
777}
778
779/// Copies `height` tightly-packed rows of `row_bytes` into a buffer whose rows
780/// are `row_pitch` bytes apart, zero-filling the padding.
781///
782/// `None` only when the padded image does not fit in a `usize`, which on a
783/// 64-bit host means the caller asked for more than the address space.
784fn stage_rows(row_bytes: u64, height: u32, row_pitch: u64, pixels: &[u8]) -> Option<Vec<u8>> {
785    let size = usize::try_from(row_pitch * u64::from(height)).ok()?;
786    let row_bytes = usize::try_from(row_bytes).ok()?;
787    let row_pitch = usize::try_from(row_pitch).ok()?;
788    let mut padded = vec![0u8; size];
789    for row in 0..height as usize {
790        let src = row * row_bytes;
791        let dst = row * row_pitch;
792        padded[dst..dst + row_bytes].copy_from_slice(&pixels[src..src + row_bytes]);
793    }
794    Some(padded)
795}
796
797/// One subresource's place in the staging buffer: what its
798/// [`BufferImageCopy`] names besides the buffer and the image.
799struct StagedRegion {
800    /// Where this subresource's first row starts, on the copy alignment.
801    buffer_offset: u64,
802    /// The padded row pitch, in texels — the unit
803    /// [`BufferImageCopy::buffer_row_length`] documents.
804    row_texels: u32,
805    /// This level's own extent, halved from the image's per level.
806    extent: Extent3d,
807    layer: u32,
808    mip: u32,
809    /// Where in that subresource the rows land: the origin for a whole level,
810    /// the rectangle's corner for a [`TexturePatch`].
811    image_offset: Offset3d,
812}
813
814/// One buffer the copies read, and the regions they read from it.
815struct CopySource<'a> {
816    buffer: crcbl_hal::BufferHandle,
817    regions: &'a [StagedRegion],
818}
819
820/// Everything [`UploadBatch::record`] needs that is not the device, the queue
821/// or the bytes — one struct rather than seven positional arguments, which is what
822/// `clippy::too_many_arguments` is objecting to and also what makes the two
823/// `u32`s impossible to swap at the call site.
824struct UploadArgs<'a> {
825    label: &'a str,
826    format: Format,
827    width: u32,
828    height: u32,
829    /// Array layers in the image.
830    layer_count: u32,
831    /// Mip levels in the image, and in every layer's chain.
832    mip_levels: u32,
833    /// `D2` for one layer, `D2Array` for a page. Not derived from
834    /// `layer_count`: a one-layer array view is a legitimate thing to want, and
835    /// the shader's declaration is what decides which it is.
836    view_type: ImageViewType,
837    /// A buffer the copies zero first, and how many bytes of it, for
838    /// [`upload_cleared_texture`].
839    cleared: Option<(crcbl_hal::BufferHandle, u64)>,
840    /// Every copy, in the order they are recorded.
841    sources: &'a [CopySource<'a>],
842}
843
844/// Startup uploads recorded into one command buffer and submitted with one
845/// wait.
846///
847/// Each texture added is created at once, its staging written at once, and its
848/// copies queued behind the ones before it; each buffer [`fill`](Self::fill)ed
849/// is the caller's already, and its copy joins them. Nothing reaches the device
850/// until [`submit`](Self::submit). One submission rather than one per upload
851/// is the point: on Mesa's ANV the first submit on a fresh device costs several
852/// milliseconds and every later round trip through [`Device::wait_idle`] costs
853/// more than the copies of an empty page, and a renderer's start-up — this
854/// crate's [`crate::ui_pass`], and `crcbl_render`'s forward renderer with its
855/// views — makes many small uploads before its first frame.
856///
857/// The textures are the caller's from the moment they are returned, and
858/// neither they nor a filled buffer may be read until `submit` has returned
859/// `Ok` — or, after [`submit_deferred`](Self::submit_deferred), by anything
860/// but later work on the batch's queue until its [`PendingUpload`] retires.
861/// Binding one into a bind group before then is fine: a descriptor names a
862/// resource, it does not read it. The staging and zero buffers are the
863/// batch's, released when it drops: after the wait if it was submitted, and
864/// before any submission if an add or the caller failed first. A deferred
865/// submit hands them to its [`PendingUpload`] instead.
866///
867/// # No encoder until the submit
868///
869/// The barriers and copies are kept as data and recorded into an encoder that
870/// [`submit`](Self::submit) creates, records, finishes and submits in one go —
871/// never one held open while the caller does other work. A batch outlives
872/// whole build steps that create, finish and submit encoders of their own, and
873/// [`Device::create_command_encoder`] says at most one encoder per device may
874/// be recording at a time: `crcbl-webgpu` streams every command into the one
875/// encoder its browser side last created, so an encoder opened here at
876/// [`new`](Self::new) lost its copies to the first encoder a caller made after
877/// it.
878///
879/// # A failed build abandons the batch
880///
881/// A caller building several objects into one batch destroys what it had
882/// created when a later step fails, and the batch still holds copies into
883/// those objects. Submitting them would be a copy into a destroyed image, so a
884/// caller that rolls back something it added calls [`abandon`](Self::abandon),
885/// and every later add and the submit itself refuse. Dropping the batch
886/// unsubmitted is the other way out, and the ordinary one: a build that fails
887/// returns its error past the batch, and nothing is submitted.
888#[derive(Debug)]
889pub struct UploadBatch<'a> {
890    device: &'a dyn Device,
891    queue: QueueHandle,
892    /// The encoder's name, so a refusal after [`UploadBatch::abandon`] says
893    /// which batch it was.
894    label: String,
895    /// Every upload added, in the order [`submit`](Self::submit) records them.
896    /// [`None`] once abandoned, which is what every add and the submit check.
897    uploads: Option<Vec<Upload>>,
898    buffers: Vec<crcbl_hal::BufferHandle>,
899}
900
901/// One add to an [`UploadBatch`], kept as what to record rather than recorded,
902/// so the batch holds no encoder open — see the type's docs.
903#[derive(Debug)]
904enum Upload {
905    /// A texture's barriers, its zero clear and its copies; see
906    /// [`record_texture`].
907    Texture {
908        image: ImageHandle,
909        range: ImageSubresourceRange,
910        /// A buffer the copies zero first, and how many bytes of it.
911        cleared: Option<(crcbl_hal::BufferHandle, u64)>,
912        copies: Vec<BufferImageCopy>,
913    },
914    /// A [`fill`](UploadBatch::fill): `copy` into a buffer that has never held
915    /// anything, left in `final_state`.
916    Fill {
917        copy: BufferCopy,
918        final_state: ResourceState,
919    },
920}
921
922impl<'a> UploadBatch<'a> {
923    /// An empty batch; `label` is the stem of its encoder's name.
924    pub fn new(device: &'a dyn Device, queue: QueueHandle, label: &str) -> Self {
925        Self {
926            device,
927            queue,
928            label: format!("{label} upload"),
929            uploads: Some(Vec::new()),
930            buffers: Vec::new(),
931        }
932    }
933
934    /// The queue the batch submits to, for a builder that holds the batch and
935    /// still submits some work of its own.
936    pub fn queue(&self) -> QueueHandle {
937        self.queue
938    }
939
940    /// [`upload_texture_mip_layers`], recorded into this batch:
941    /// `layers[layer][level]` at `extent`, viewed as `view_type`.
942    /// [`upload_texture`]'s one image is `&[&[pixels]]` and
943    /// [`ImageViewType::D2`].
944    ///
945    /// # Errors
946    ///
947    /// As [`upload_texture_mip_layers`], before anything is recorded, and
948    /// [`HalError::InvalidDescriptor`] once the batch is abandoned.
949    pub fn texture(
950        &mut self,
951        label: &str,
952        format: Format,
953        extent: (u32, u32),
954        layers: &[&[&[u8]]],
955        view_type: ImageViewType,
956    ) -> Result<UploadedTexture, HalError> {
957        self.recording(label)?;
958        stage_texture(self, label, format, extent, layers, view_type)
959    }
960
961    /// [`upload_cleared_texture`], recorded into this batch.
962    ///
963    /// # Errors
964    ///
965    /// As [`upload_cleared_texture`], before anything is recorded, and
966    /// [`HalError::InvalidDescriptor`] once the batch is abandoned.
967    pub fn cleared_texture(
968        &mut self,
969        desc: &ClearedTextureDesc<'_>,
970    ) -> Result<UploadedTexture, HalError> {
971        self.recording(desc.label)?;
972        stage_cleared_texture(self, desc)
973    }
974
975    /// Writes `contents` over the start of `buffer` once, before any frame
976    /// exists, leaving it in `final_state` once submitted.
977    ///
978    /// For a **device-local** buffer whose first frame reads something real —
979    /// a host write cannot reach one, and a clear cannot say anything but zero
980    /// and `crcbl-dx12` refuses one outright. `buffer` must carry
981    /// [`BufferUsage::TRANSFER_DST`] and must never have held anything: its
982    /// contents are discarded rather than transitioned, so a buffer a frame has
983    /// already written is the wrong thing to hand this.
984    ///
985    /// `final_state` is the state the buffer's first importer declares as its
986    /// initial one, so the graph's first barrier on it names a state the buffer
987    /// is really in. `label` names the staging buffer, `"{label} staging"`.
988    ///
989    /// # Errors
990    ///
991    /// [`HalError`] from creating or writing the staging buffer, which is
992    /// destroyed again if the write fails, and [`HalError::InvalidDescriptor`]
993    /// once the batch is abandoned. Nothing is recorded on either.
994    pub fn fill(
995        &mut self,
996        label: &str,
997        buffer: crcbl_hal::BufferHandle,
998        contents: &[u8],
999        final_state: ResourceState,
1000    ) -> Result<(), HalError> {
1001        self.recording(label)?;
1002        let staging = create_staging(self.device, label, contents)?;
1003        self.buffers.push(staging);
1004        self.uploads
1005            .as_mut()
1006            .expect("checked by `recording` above, and nothing between abandons")
1007            .push(Upload::Fill {
1008                copy: BufferCopy {
1009                    src: staging,
1010                    src_offset: 0,
1011                    dst: buffer,
1012                    dst_offset: 0,
1013                    size: contents.len() as u64,
1014                },
1015                final_state,
1016            });
1017        Ok(())
1018    }
1019
1020    /// Throws away everything recorded, because the caller is about to destroy
1021    /// something it added — see the type's docs. Every later add and
1022    /// [`submit`](Self::submit) refuse; the staging buffers are still released
1023    /// when the batch drops.
1024    pub fn abandon(&mut self) {
1025        self.uploads = None;
1026    }
1027
1028    /// Records every queued copy into one encoder created here, submits it and
1029    /// waits for the device, leaving every texture in
1030    /// [`ResourceState::ShaderRead`] and every filled buffer in the state its
1031    /// [`fill`](Self::fill) named.
1032    ///
1033    /// # Errors
1034    ///
1035    /// [`HalError`] from finishing, submitting or waiting, and
1036    /// [`HalError::InvalidDescriptor`] for an abandoned batch, which submits
1037    /// nothing. The textures and buffers stay the caller's to destroy.
1038    pub fn submit(mut self) -> Result<(), HalError> {
1039        let commands = self.finish()?;
1040        let submitted = self
1041            .device
1042            .submit(self.queue, &SubmitInfo::new(&[commands]))
1043            .and_then(|()| self.device.wait_idle());
1044        self.device.destroy_command_buffer(commands);
1045        submitted
1046    }
1047
1048    /// [`submit`](Self::submit) without the wait: the copies are submitted
1049    /// and the staging and zero buffers, the command buffer and a timeline
1050    /// semaphore the submission signals move into the returned
1051    /// [`PendingUpload`], which releases them once the GPU is past them.
1052    ///
1053    /// For a start-up whose first submission is expensive — pikr measured the
1054    /// first one on a fresh device at 7–10 ms on an Intel iGPU under Mesa's
1055    /// ANV, on 2026-10-29 — and which has other work to do before its first
1056    /// frame: the copies run under it instead of in front of it.
1057    ///
1058    /// The textures and filled buffers may be read by any work submitted
1059    /// **to the same queue** after this returns, with no wait in between; see
1060    /// [`PendingUpload`] for why that holds on every backend. Work on another
1061    /// queue, or a host read, must wait for [`PendingUpload::wait`] first.
1062    ///
1063    /// # Without timeline semaphores it waits
1064    ///
1065    /// A device without [`Features::TIMELINE_SEMAPHORE`] has nothing that
1066    /// says when the copies are done short of [`Device::wait_idle`], so this
1067    /// is [`submit`](Self::submit) there, and the [`PendingUpload`] it returns
1068    /// holds nothing. That is the WebGPU backend's case, and it costs nothing
1069    /// there: `crcbl-webgpu`'s `wait_idle` does not block, because the browser
1070    /// keeps a destroyed buffer alive for the work already queued against it.
1071    ///
1072    /// # Errors
1073    ///
1074    /// As [`submit`](Self::submit), and [`HalError`] from creating the
1075    /// semaphore. On every error nothing is pending and the buffers have been
1076    /// released: either nothing was submitted, or (on the waiting path) the
1077    /// wait has already run or failed as [`submit`](Self::submit)'s does.
1078    pub fn submit_deferred(mut self) -> Result<PendingUpload, HalError> {
1079        let device = self.device;
1080        if !device.caps().supports(Features::TIMELINE_SEMAPHORE) {
1081            self.submit()?;
1082            return Ok(PendingUpload { in_flight: None });
1083        }
1084        if self.uploads.is_none() {
1085            return Err(self.abandoned(&self.label));
1086        }
1087        let semaphore = device.create_semaphore(&SemaphoreDesc {
1088            label: Some(&self.label),
1089            kind: SemaphoreKind::Timeline { initial_value: 0 },
1090        })?;
1091        let commands = match self.finish() {
1092            Ok(commands) => commands,
1093            Err(error) => {
1094                device.destroy_semaphore(semaphore);
1095                return Err(error);
1096            }
1097        };
1098        let signals = [SemaphoreSignal {
1099            semaphore,
1100            value: PendingUpload::LANDED,
1101        }];
1102        let submit = SubmitInfo {
1103            command_buffers: &[commands],
1104            waits: &[],
1105            signals: &signals,
1106        };
1107        if let Err(error) = device.submit(self.queue, &submit) {
1108            device.destroy_command_buffer(commands);
1109            device.destroy_semaphore(semaphore);
1110            return Err(error);
1111        }
1112        Ok(PendingUpload {
1113            in_flight: Some(InFlightUpload {
1114                semaphore,
1115                commands,
1116                buffers: std::mem::take(&mut self.buffers),
1117            }),
1118        })
1119    }
1120
1121    /// Records every queued upload into one encoder created here and finishes
1122    /// it, for either submit.
1123    fn finish(&mut self) -> Result<crcbl_hal::CommandBufferHandle, HalError> {
1124        let Some(uploads) = self.uploads.take() else {
1125            return Err(self.abandoned(&self.label));
1126        };
1127        let mut encoder = self.device.create_command_encoder(&CommandEncoderDesc {
1128            label: Some(&self.label),
1129            queue: self.queue,
1130        });
1131        for upload in &uploads {
1132            upload.record(encoder.as_mut());
1133        }
1134        encoder.finish()
1135    }
1136
1137    /// `Ok` while the batch is still recording; the refusal naming `label`
1138    /// once it is abandoned.
1139    fn recording(&self, label: &str) -> Result<(), HalError> {
1140        match self.uploads {
1141            Some(_) => Ok(()),
1142            None => Err(self.abandoned(label)),
1143        }
1144    }
1145
1146    fn abandoned(&self, what: &str) -> HalError {
1147        HalError::InvalidDescriptor(format!(
1148            "{what}: the batch {:?} was abandoned, because something recorded into it was \
1149             destroyed, so nothing in it may reach the device",
1150            self.label
1151        ))
1152    }
1153
1154    /// [`submit`](Self::submit) for a batch of the one `texture`, which is
1155    /// destroyed if the submission fails.
1156    fn submit_one(self, texture: UploadedTexture) -> Result<UploadedTexture, HalError> {
1157        let device = self.device;
1158        match self.submit() {
1159            Ok(()) => Ok(texture),
1160            Err(error) => {
1161                texture.destroy(device);
1162                Err(error)
1163            }
1164        }
1165    }
1166
1167    /// Creates the image and the view `args` describe and queues its copies,
1168    /// leaving it in [`ResourceState::ShaderRead`] once submitted.
1169    fn record(&mut self, args: &UploadArgs<'_>) -> Result<UploadedTexture, HalError> {
1170        let device = self.device;
1171        let image = device.create_image(&ImageDesc {
1172            label: Some(args.label),
1173            image_type: ImageType::D2,
1174            format: args.format,
1175            extent: Extent3d {
1176                width: args.width,
1177                height: args.height,
1178                // A `D2` image's `depth_or_layers` is its array length, which
1179                // the seam says on the field itself.
1180                depth_or_layers: args.layer_count,
1181            },
1182            mip_levels: args.mip_levels,
1183            samples: 1,
1184            // `TRANSFER_SRC` as well as the copy's `TRANSFER_DST`, so a test or
1185            // a capture can copy a level back out — `tests/forward_e2e/page.rs`
1186            // reads the page's chain that way. Free on every backend: a sampled
1187            // image that is also a copy source costs no layout, no memory and
1188            // no decompression it would not already pay.
1189            usage: ImageUsage::TRANSFER_SRC | ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED,
1190        })?;
1191        let view = match device.create_image_view(&ImageViewDesc {
1192            label: Some(args.label),
1193            image,
1194            view_type: args.view_type,
1195            format: args.format,
1196            range: color_range(args.mip_levels, args.layer_count),
1197        }) {
1198            Ok(view) => view,
1199            Err(error) => {
1200                device.destroy_image(image);
1201                return Err(error);
1202            }
1203        };
1204        self.uploads
1205            .as_mut()
1206            .expect("every add checks `recording` before it creates anything")
1207            .push(Upload::Texture {
1208                image,
1209                range: color_range(args.mip_levels, args.layer_count),
1210                cleared: args.cleared,
1211                copies: texture_copies(args, image),
1212            });
1213        Ok(UploadedTexture { image, view })
1214    }
1215}
1216
1217/// Refuses any `queue` but `device`'s [`QueueKind::Graphics`] queue for an
1218/// upload [`UploadBatch::submit_deferred`] will not wait for: `what` names the
1219/// caller, as "a UI pass" or "a forward renderer's view".
1220///
1221/// The rule every deferred caller shares, held in one place. Only the queue the
1222/// frames are submitted to orders the copies before the frames that read them,
1223/// since nothing waits on the host.
1224///
1225/// # Errors
1226///
1227/// [`HalError::InvalidDescriptor`] naming both queues.
1228pub fn require_frame_queue(
1229    device: &dyn Device,
1230    queue: QueueHandle,
1231    what: &str,
1232) -> Result<(), HalError> {
1233    let graphics = device.queue(QueueKind::Graphics);
1234    if graphics == Some(queue) {
1235        return Ok(());
1236    }
1237    Err(HalError::InvalidDescriptor(format!(
1238        "{what} must be on the device's graphics queue ({graphics:?}), the one its frames are \
1239         submitted to, and was given {queue:?}: its start-up uploads are not waited for, and \
1240         only that queue orders them before the frames that read them"
1241    )))
1242}
1243
1244impl Drop for UploadBatch<'_> {
1245    fn drop(&mut self) {
1246        for buffer in self.buffers.drain(..) {
1247            self.device.destroy_buffer(buffer);
1248        }
1249    }
1250}
1251
1252/// An [`UploadBatch`] submitted by
1253/// [`submit_deferred`](UploadBatch::submit_deferred) and not yet known to
1254/// have run: what it still owns, and the timeline value that says when it may
1255/// go.
1256///
1257/// # Why the textures may be sampled before it retires
1258///
1259/// The batch's last barrier on each image leaves it in
1260/// [`ResourceState::ShaderRead`], and what reads it next is a frame submitted
1261/// to the same queue after it. That is ordered without a host wait on every
1262/// backend here:
1263///
1264/// - **Vulkan**: a pipeline barrier's second synchronisation scope is every
1265///   command later in *submission order* on the queue, which spans later
1266///   `vkQueueSubmit`s, and the image's layout is a property of the image, not
1267///   of the command buffer that transitioned it.
1268/// - **D3D12**: a resource barrier's state persists past its command list, and
1269///   command lists on one queue run in `ExecuteCommandLists` order. An image
1270///   explicitly transitioned does not decay; a buffer does, to `COMMON`, the
1271///   same as it does after [`UploadBatch::submit`]'s wait.
1272/// - **Metal**: every resource `crcbl-mtl` allocates is hazard-tracked, and the
1273///   driver orders tracked hazards between command buffers committed to one
1274///   queue.
1275/// - **WebGPU**: never reaches here — [`UploadBatch::submit_deferred`] waits
1276///   on a device without timeline semaphores, which is every browser's — and
1277///   `queue.submit` order is WebGPU's own guarantee anyway.
1278///
1279/// Another queue has none of these guarantees, which is why the batch's queue
1280/// must be the one its readers submit to.
1281///
1282/// # What it still owns
1283///
1284/// The staging and zero buffers the copies read, the command buffer
1285/// ([`Device::destroy_command_buffer`] may not run before its submission
1286/// completes) and the semaphore. [`poll`](Self::poll) releases them once the
1287/// semaphore has reached [`LANDED`](Self::LANDED), without blocking;
1288/// [`wait`](Self::wait) blocks for it. One of the two must have released them
1289/// before the device is destroyed: dropping a pending upload leaks them, and
1290/// says so in the log, because releasing a buffer the GPU may still be reading
1291/// is the worse failure.
1292#[derive(Debug)]
1293#[must_use = "the staging buffers live until the upload is polled or waited for"]
1294pub struct PendingUpload {
1295    /// [`None`] once released, and for an upload that waited at its submit.
1296    in_flight: Option<InFlightUpload>,
1297}
1298
1299/// What a [`PendingUpload`] releases.
1300#[derive(Debug)]
1301struct InFlightUpload {
1302    semaphore: crcbl_hal::SemaphoreHandle,
1303    commands: crcbl_hal::CommandBufferHandle,
1304    buffers: Vec<crcbl_hal::BufferHandle>,
1305}
1306
1307impl PendingUpload {
1308    /// The value the submission signals its semaphore to once its copies have
1309    /// run. The semaphore is the upload's own, so it is the first value.
1310    pub const LANDED: u64 = 1;
1311
1312    /// Whether everything has been released — at once for an upload that
1313    /// waited at its submit.
1314    #[must_use]
1315    pub const fn is_retired(&self) -> bool {
1316        self.in_flight.is_none()
1317    }
1318
1319    /// Releases everything if the copies have run, without blocking, and says
1320    /// whether it is now retired.
1321    ///
1322    /// # Errors
1323    ///
1324    /// [`HalError`] from reading the semaphore — a lost device. Nothing is
1325    /// released then.
1326    pub fn poll(&mut self, device: &dyn Device) -> Result<bool, HalError> {
1327        let Some(in_flight) = &self.in_flight else {
1328            return Ok(true);
1329        };
1330        if device.semaphore_value(in_flight.semaphore)? < Self::LANDED {
1331            return Ok(false);
1332        }
1333        self.release(device);
1334        Ok(true)
1335    }
1336
1337    /// Blocks until the copies have run, then releases everything. Returns at
1338    /// once for one already retired.
1339    ///
1340    /// No timeout, like the [`Device::wait_idle`] it replaces: a GPU that
1341    /// never finishes is a lost device, which the wait reports.
1342    ///
1343    /// # Errors
1344    ///
1345    /// [`HalError`] from the wait. Nothing is released then.
1346    pub fn wait(&mut self, device: &dyn Device) -> Result<(), HalError> {
1347        let Some(in_flight) = &self.in_flight else {
1348            return Ok(());
1349        };
1350        let wait = crcbl_hal::SemaphoreWait {
1351            semaphore: in_flight.semaphore,
1352            value: Self::LANDED,
1353        };
1354        if !device.wait_semaphores(&[wait], u64::MAX)? {
1355            return Err(HalError::Backend(
1356                "an upload's semaphore wait with no timeout reported a timeout".to_string(),
1357            ));
1358        }
1359        self.release(device);
1360        Ok(())
1361    }
1362
1363    fn release(&mut self, device: &dyn Device) {
1364        if let Some(in_flight) = self.in_flight.take() {
1365            for buffer in in_flight.buffers {
1366                device.destroy_buffer(buffer);
1367            }
1368            device.destroy_command_buffer(in_flight.commands);
1369            device.destroy_semaphore(in_flight.semaphore);
1370        }
1371    }
1372}
1373
1374impl Drop for PendingUpload {
1375    fn drop(&mut self) {
1376        if let Some(in_flight) = &self.in_flight {
1377            crcbl_core::log::warn!(
1378                "PendingUpload dropped before it was polled or waited for — {} staging buffers \
1379                 leaked",
1380                in_flight.buffers.len()
1381            );
1382        }
1383    }
1384}
1385
1386/// The whole of a colour image `mips` levels deep and `layers` layers deep.
1387const fn color_range(mips: u32, layers: u32) -> ImageSubresourceRange {
1388    ImageSubresourceRange {
1389        aspect: ImageAspect::COLOR,
1390        base_mip: 0,
1391        mip_count: mips,
1392        base_layer: 0,
1393        layer_count: layers,
1394    }
1395}
1396
1397/// One copy per subresource region `args` stages, into `image`.
1398///
1399/// A region's `image_extent` is a 2D extent whatever the image is —
1400/// `crcbl-dx12` refuses anything else by name, because `CopyTextureRegion`
1401/// addresses one subresource — so the layer and the level are named by
1402/// `base_layer` and `mip`, and the buffer offset says where that subresource's
1403/// rows start.
1404fn texture_copies(args: &UploadArgs<'_>, image: ImageHandle) -> Vec<BufferImageCopy> {
1405    args.sources
1406        .iter()
1407        .flat_map(|source| source.regions.iter().map(move |region| (source, region)))
1408        .map(|(source, region)| BufferImageCopy {
1409            buffer: source.buffer,
1410            buffer_offset: region.buffer_offset,
1411            buffer_row_length: region.row_texels,
1412            buffer_image_height: region.extent.height,
1413            image,
1414            image_subresource: ImageSubresourceLayers {
1415                aspect: ImageAspect::COLOR,
1416                mip: region.mip,
1417                base_layer: region.layer,
1418                layer_count: 1,
1419            },
1420            image_offset: region.image_offset,
1421            image_extent: region.extent,
1422        })
1423        .collect()
1424}
1425
1426impl Upload {
1427    /// Records this upload into `encoder`. A texture's barriers name only its
1428    /// image and its own zero buffer, and a fill's only its buffer, so a
1429    /// batch's uploads do not wait on one another.
1430    fn record(&self, encoder: &mut dyn CommandEncoder) {
1431        match self {
1432            Self::Texture {
1433                image,
1434                range,
1435                cleared,
1436                copies,
1437            } => record_texture(encoder, *image, *range, *cleared, copies),
1438            Self::Fill { copy, final_state } => {
1439                // `Undefined` as the source: the buffer has never held
1440                // anything, so there is no state to preserve and its contents
1441                // are discarded rather than transitioned.
1442                encoder.pipeline_barrier(&crcbl_hal::Barriers {
1443                    buffers: &[crcbl_hal::BufferBarrier::new(
1444                        copy.dst,
1445                        ResourceState::Undefined,
1446                        ResourceState::TransferDst,
1447                    )],
1448                    ..Default::default()
1449                });
1450                encoder.copy_buffer_to_buffer(copy);
1451                encoder.pipeline_barrier(&crcbl_hal::Barriers {
1452                    buffers: &[crcbl_hal::BufferBarrier::new(
1453                        copy.dst,
1454                        ResourceState::TransferDst,
1455                        *final_state,
1456                    )],
1457                    ..Default::default()
1458                });
1459            }
1460        }
1461    }
1462}
1463
1464/// Records `image`'s barriers, its zero clear and `copies`, leaving it in
1465/// [`ResourceState::ShaderRead`].
1466fn record_texture(
1467    encoder: &mut dyn CommandEncoder,
1468    image: ImageHandle,
1469    range: ImageSubresourceRange,
1470    cleared: Option<(crcbl_hal::BufferHandle, u64)>,
1471    copies: &[BufferImageCopy],
1472) {
1473    // Undefined → TransferDst: the image has never held anything, so its old
1474    // contents are explicitly discarded rather than transitioned. The range
1475    // covers every level of every layer, so one barrier serves all the copies
1476    // below.
1477    encoder.pipeline_barrier(&crcbl_hal::Barriers {
1478        images: &[crcbl_hal::ImageBarrier::new(
1479            image,
1480            range,
1481            ResourceState::Undefined,
1482            ResourceState::TransferDst,
1483        )],
1484        ..Default::default()
1485    });
1486
1487    // Outside any pass, and before the copies that read it: a clear is recorded
1488    // into the same command buffer, so it runs first on every backend. The
1489    // buffer is then moved to a copy source explicitly, because the clear left
1490    // it a copy destination: D3D12 promotes a buffer implicitly only out of
1491    // `COMMON`, which a fresh one is in and this one no longer is.
1492    if let Some((buffer, size)) = cleared {
1493        encoder.clear_buffer(buffer, 0, size);
1494        encoder.pipeline_barrier(&crcbl_hal::Barriers {
1495            buffers: &[crcbl_hal::BufferBarrier::new(
1496                buffer,
1497                ResourceState::TransferDst,
1498                ResourceState::TransferSrc,
1499            )],
1500            ..Default::default()
1501        });
1502    }
1503
1504    for copy in copies {
1505        encoder.copy_buffer_to_image(copy);
1506    }
1507
1508    encoder.pipeline_barrier(&crcbl_hal::Barriers {
1509        images: &[crcbl_hal::ImageBarrier::new(
1510            image,
1511            range,
1512            ResourceState::TransferDst,
1513            ResourceState::ShaderRead,
1514        )],
1515        ..Default::default()
1516    });
1517}
1518
1519// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
1520#[cfg(all(test, not(target_arch = "wasm32")))]
1521mod tests {
1522    use super::*;
1523    use crcbl_hal::null::{Command, Event, NullInstance, Recorder};
1524    use crcbl_hal::{DeviceDesc, Features, Instance, QueueKind};
1525
1526    /// Tier B, because its `optimal_buffer_copy_offset_alignment` is 256 —
1527    /// WebGPU's — and Tier A's is 4, which an `Rgba8Unorm` row satisfies for
1528    /// free. Padding is only exercised on the tier that asks for it.
1529    fn open_tier_b(recorder: &Recorder) -> (Box<dyn Device>, QueueHandle) {
1530        let instance = NullInstance::portable().with_recorder(recorder.clone());
1531        let adapter = instance.adapters().remove(0);
1532        let device = instance
1533            .create_device(&DeviceDesc {
1534                label: None,
1535                adapter: adapter.id,
1536                required_features: Features::COMPUTE,
1537                optional_features: Features::empty(),
1538                compatible_surface: None,
1539            })
1540            .expect("the tier B null adapter opens");
1541        let queue = device.queue(QueueKind::Graphics).expect("always present");
1542        (device, queue)
1543    }
1544
1545    fn open_tier_a(recorder: &Recorder) -> (Box<dyn Device>, QueueHandle) {
1546        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
1547        let adapter = instance.adapters().remove(0);
1548        let device = instance
1549            .create_device(&DeviceDesc {
1550                label: None,
1551                adapter: adapter.id,
1552                required_features: Features::GPU_DRIVEN,
1553                optional_features: Features::empty(),
1554                compatible_surface: None,
1555            })
1556            .expect("the null backend always opens");
1557        let queue = device.queue(QueueKind::Graphics).expect("always present");
1558        (device, queue)
1559    }
1560
1561    fn the_copies(recorder: &Recorder) -> Vec<BufferImageCopy> {
1562        recorder
1563            .commands()
1564            .into_iter()
1565            .filter_map(|command| match command {
1566                Command::CopyBufferToImage(copy) => Some(copy),
1567                _ => None,
1568            })
1569            .collect()
1570    }
1571
1572    fn the_copy(recorder: &Recorder) -> BufferImageCopy {
1573        let copies = the_copies(recorder);
1574        assert_eq!(
1575            copies.len(),
1576            1,
1577            "a single-layer upload records exactly one buffer-to-image copy"
1578        );
1579        copies[0]
1580    }
1581
1582    fn bytes_written(recorder: &Recorder) -> usize {
1583        recorder
1584            .events()
1585            .into_iter()
1586            .find_map(|event| match event {
1587                Event::BufferWritten { len, .. } => Some(len),
1588                _ => None,
1589            })
1590            .expect("an upload writes its staging buffer once")
1591    }
1592
1593    /// A 100-texel RGBA row: 400 bytes, which Tier B's 256-byte alignment pads
1594    /// to 512. Every number here is different from the one the old
1595    /// texels-as-bytes arithmetic would produce — that pitched 100 up to 256 —
1596    /// so this is what fails if a pitch is ever computed from `width` rather
1597    /// than `width * texel_size` again.
1598    const WIDTH: u32 = 100;
1599    const HEIGHT: u32 = 3;
1600    const ROW_BYTES: usize = 400;
1601    const PITCH: usize = 512;
1602
1603    fn ramp(len: usize) -> Vec<u8> {
1604        // Coprime with 256, so no two bytes 256 apart are equal and a row
1605        // written at the wrong offset cannot compare equal by accident.
1606        (0..len).map(|index| (index % 251) as u8).collect()
1607    }
1608
1609    /// The row pitch is in **bytes**, and each source row lands at its padded
1610    /// byte offset with zeroes after it.
1611    #[test]
1612    fn each_source_row_lands_at_its_padded_byte_offset() {
1613        let texel = Format::Rgba8Unorm
1614            .texel_size(ImageAspect::COLOR)
1615            .expect("rgba8 is a colour format");
1616        assert_eq!(texel, 4);
1617
1618        let row_bytes = u64::from(WIDTH) * u64::from(texel);
1619        assert_eq!(row_bytes as usize, ROW_BYTES);
1620        let pitch = padded_row_pitch(row_bytes, texel, 256);
1621        assert_eq!(
1622            pitch as usize, PITCH,
1623            "400 bytes padded up to the 256-byte alignment is 512, not 256"
1624        );
1625
1626        let pixels = ramp(ROW_BYTES * HEIGHT as usize);
1627        let padded = stage_rows(row_bytes, HEIGHT, pitch, &pixels).expect("fits");
1628        assert_eq!(padded.len(), PITCH * HEIGHT as usize);
1629        for row in 0..HEIGHT as usize {
1630            let start = row * PITCH;
1631            assert_eq!(
1632                &padded[start..start + ROW_BYTES],
1633                &pixels[row * ROW_BYTES..(row + 1) * ROW_BYTES],
1634                "row {row} must sit at byte {start}"
1635            );
1636            assert!(
1637                padded[start + ROW_BYTES..start + PITCH]
1638                    .iter()
1639                    .all(|&byte| byte == 0),
1640                "row {row}'s padding must be zero, not the next row"
1641            );
1642        }
1643    }
1644
1645    /// And the copy is told that pitch in *texels*, which is the unit
1646    /// [`BufferImageCopy::buffer_row_length`] documents.
1647    #[test]
1648    fn an_rgba_upload_records_its_pitch_in_texels() {
1649        let recorder = Recorder::new();
1650        let (device, queue) = open_tier_b(&recorder);
1651        assert_eq!(
1652            device.caps().limits.optimal_buffer_copy_offset_alignment,
1653            256,
1654            "the padding this test exercises only exists on the tier that asks for it"
1655        );
1656        let pixels = ramp(ROW_BYTES * HEIGHT as usize);
1657
1658        let texture = upload_texture(
1659            device.as_ref(),
1660            queue,
1661            "sprite atlas",
1662            Format::Rgba8Unorm,
1663            WIDTH,
1664            HEIGHT,
1665            &pixels,
1666        )
1667        .expect("the null backend accepts this");
1668
1669        assert_eq!(
1670            bytes_written(&recorder),
1671            PITCH * HEIGHT as usize,
1672            "the staging write is the padded image, not the packed one"
1673        );
1674        let copy = the_copy(&recorder);
1675        assert_eq!(
1676            copy.buffer_row_length, 128,
1677            "512 bytes of pitch is 128 rgba texels, not 512"
1678        );
1679        assert_eq!(copy.buffer_image_height, HEIGHT);
1680        assert_eq!(copy.image_extent, Extent3d::d2(WIDTH, HEIGHT));
1681        assert_eq!(copy.image_offset, Offset3d { x: 0, y: 0, z: 0 });
1682
1683        texture.destroy(device.as_ref());
1684        recorder.assert_valid();
1685    }
1686
1687    /// A device whose alignment an `Rgba8Unorm` row already satisfies pads
1688    /// nothing, and the copy's pitch is then simply the width.
1689    #[test]
1690    fn an_aligned_row_is_not_padded() {
1691        let recorder = Recorder::new();
1692        let (device, queue) = open_tier_a(&recorder);
1693        assert_eq!(device.caps().limits.optimal_buffer_copy_offset_alignment, 4);
1694        let pixels = vec![0u8; 5 * 3 * 4];
1695        let texture = upload_texture(
1696            device.as_ref(),
1697            queue,
1698            "tight",
1699            Format::Rgba8Unorm,
1700            5,
1701            3,
1702            &pixels,
1703        )
1704        .expect("accepted");
1705        assert_eq!(bytes_written(&recorder), 5 * 3 * 4);
1706        assert_eq!(the_copy(&recorder).buffer_row_length, 5);
1707        texture.destroy(device.as_ref());
1708        recorder.assert_valid();
1709    }
1710
1711    /// The pitch satisfies the alignment *and* stays a whole number of texels,
1712    /// including when the two do not divide each other — a byte pitch the copy
1713    /// cannot express in texels is not a pitch.
1714    #[test]
1715    fn a_row_pitch_is_aligned_and_a_whole_number_of_texels() {
1716        // The ordinary cases: alignment already a multiple of the texel.
1717        assert_eq!(padded_row_pitch(20, 4, 256), 256);
1718        assert_eq!(padded_row_pitch(20, 4, 4), 20);
1719        assert_eq!(padded_row_pitch(5, 1, 4), 8);
1720        assert_eq!(padded_row_pitch(1024, 4, 256), 1024);
1721        // The awkward one: 6-byte alignment, 4-byte texel. 4 is not enough (it
1722        // is not a multiple of 6) and 6 is not enough (it is not a whole texel);
1723        // 12 is the first that is both.
1724        let pitch = padded_row_pitch(4, 4, 6);
1725        assert_eq!(pitch, 12);
1726        assert_eq!(pitch % 6, 0, "must satisfy the alignment");
1727        assert_eq!(pitch % 4, 0, "must be a whole number of texels");
1728    }
1729
1730    /// **A page is one image whose layers each get their own copy**, and each
1731    /// copy reads the layer's own slice of the staging buffer.
1732    ///
1733    /// The offsets are what this is for. Every layer's rows are padded, so a
1734    /// second layer read at `width * height * texel` — the *unpadded* size —
1735    /// would take the tail of the first layer plus part of the second and put
1736    /// a plausible smear in the page. Tier B is used because its 256-byte
1737    /// alignment is what makes the padded and unpadded strides differ.
1738    #[test]
1739    fn a_page_copies_each_layer_from_its_own_padded_offset() {
1740        let recorder = Recorder::new();
1741        let (device, queue) = open_tier_b(&recorder);
1742        let layers: Vec<Vec<u8>> = (0..3).map(|_| ramp(ROW_BYTES * HEIGHT as usize)).collect();
1743        let refs: Vec<&[u8]> = layers.iter().map(Vec::as_slice).collect();
1744
1745        let page = upload_texture_layers(
1746            device.as_ref(),
1747            queue,
1748            "material page",
1749            Format::Rgba8Unorm,
1750            WIDTH,
1751            HEIGHT,
1752            &refs,
1753        )
1754        .expect("the null backend accepts this");
1755
1756        let layer_bytes = PITCH * HEIGHT as usize;
1757        assert_eq!(
1758            bytes_written(&recorder),
1759            layer_bytes * layers.len(),
1760            "the staging write is every layer, padded"
1761        );
1762        let copies = the_copies(&recorder);
1763        assert_eq!(
1764            copies.len(),
1765            layers.len(),
1766            "one copy per layer, because a region's extent is 2D on every backend"
1767        );
1768        for (layer, copy) in copies.iter().enumerate() {
1769            assert_eq!(
1770                copy.buffer_offset,
1771                (layer * layer_bytes) as u64,
1772                "layer {layer} must read from its own slice of the staging buffer"
1773            );
1774            assert_eq!(
1775                copy.image_subresource.base_layer, layer as u32,
1776                "layer {layer} must be written to layer {layer} of the image"
1777            );
1778            assert_eq!(copy.image_subresource.layer_count, 1);
1779            assert_eq!(copy.buffer_row_length, 128);
1780            assert_eq!(
1781                copy.image_extent,
1782                Extent3d::d2(WIDTH, HEIGHT),
1783                "a copy region's extent stays 2D"
1784            );
1785        }
1786
1787        page.destroy(device.as_ref());
1788        recorder.assert_valid();
1789    }
1790
1791    /// A page with no layers is refused here, by name.
1792    ///
1793    /// Without the guard it reaches the device as an image whose
1794    /// `depth_or_layers` is zero, whose complaint is about an *extent* — a
1795    /// different object and a message that does not say what the caller did.
1796    #[test]
1797    fn a_page_with_no_layers_is_rejected() {
1798        let recorder = Recorder::new();
1799        let (device, queue) = open_tier_a(&recorder);
1800        let error = upload_texture_layers(
1801            device.as_ref(),
1802            queue,
1803            "empty page",
1804            Format::Rgba8Unorm,
1805            4,
1806            4,
1807            &[],
1808        )
1809        .expect_err("a page needs a layer");
1810        assert!(
1811            error.to_string().contains("at least one layer"),
1812            "got: {error}"
1813        );
1814        assert_eq!(recorder.total_live_objects(), 0);
1815    }
1816
1817    /// A short or long slice is an error naming both numbers, not a
1818    /// `copy_from_slice` panic naming neither — and nothing is created before
1819    /// it is noticed.
1820    #[test]
1821    fn a_wrong_sized_pixel_slice_is_rejected() {
1822        let recorder = Recorder::new();
1823        let (device, queue) = open_tier_a(&recorder);
1824        let before = recorder.total_live_objects();
1825
1826        let short = vec![0u8; 5 * 3 * 4 - 1];
1827        let error = upload_texture(
1828            device.as_ref(),
1829            queue,
1830            "short",
1831            Format::Rgba8Unorm,
1832            5,
1833            3,
1834            &short,
1835        )
1836        .expect_err("a 59-byte slice is not a 5x3 rgba image");
1837        let message = error.to_string();
1838        assert!(
1839            message.contains("60") && message.contains("59"),
1840            "the error must name both sizes, got: {message}"
1841        );
1842
1843        let long = vec![0u8; 5 * 3 * 4 + 1];
1844        upload_texture(
1845            device.as_ref(),
1846            queue,
1847            "long",
1848            Format::Rgba8Unorm,
1849            5,
1850            3,
1851            &long,
1852        )
1853        .expect_err("a 61-byte slice is not one either");
1854
1855        assert_eq!(
1856            recorder.total_live_objects(),
1857            before,
1858            "a rejected upload creates nothing"
1859        );
1860    }
1861
1862    /// A zero extent is refused here rather than reaching the device as a
1863    /// zero-sized staging buffer, which is a different error about a different
1864    /// object.
1865    #[test]
1866    fn a_zero_extent_is_rejected() {
1867        let recorder = Recorder::new();
1868        let (device, queue) = open_tier_a(&recorder);
1869        for (width, height) in [(0u32, 4u32), (4, 0)] {
1870            let error = upload_texture(
1871                device.as_ref(),
1872                queue,
1873                "empty",
1874                Format::Rgba8Unorm,
1875                width,
1876                height,
1877                &[],
1878            )
1879            .expect_err("a zero extent is not a texture");
1880            // "texture extent", not merely "non-zero": without the guard above
1881            // this reaches the device as a zero-sized *buffer*, whose own error
1882            // also says "non-zero" and would have made this test pass while
1883            // naming the wrong object.
1884            assert!(
1885                error.to_string().contains("texture extent"),
1886                "got: {error}, which is not the extent complaint"
1887            );
1888        }
1889        assert_eq!(recorder.total_live_objects(), 0);
1890    }
1891
1892    /// A combined depth/stencil format has two planes and no colour aspect, so
1893    /// there is no single `texel_size` to pitch against. Refused by name rather
1894    /// than silently pitched against `block_size`, which would be 8.
1895    #[test]
1896    fn a_depth_stencil_format_is_rejected() {
1897        let recorder = Recorder::new();
1898        let (device, queue) = open_tier_a(&recorder);
1899        let error = upload_texture(
1900            device.as_ref(),
1901            queue,
1902            "depth",
1903            Format::D32FloatS8Uint,
1904            4,
1905            4,
1906            &[0u8; 128],
1907        )
1908        .expect_err("a depth/stencil upload needs one copy per plane");
1909        assert!(error.to_string().contains("colour plane"), "got: {error}");
1910        assert_eq!(recorder.total_live_objects(), 0);
1911    }
1912
1913    /// A compressed format's `block_size` covers a 4×4 block, not one texel, so
1914    /// the per-texel sizing here would be wrong by a factor of four — and there
1915    /// is no caller that needs one. Refused by name rather than silently
1916    /// pitched against the block size, before any device call.
1917    #[test]
1918    fn a_compressed_format_is_rejected() {
1919        let recorder = Recorder::new();
1920        let (device, queue) = open_tier_a(&recorder);
1921        // 8x8 BC1 is 2x2 blocks of 8 bytes: the *correct* compressed size, so a
1922        // regression that accepted compressed uploads would pass the size check
1923        // and fail only here.
1924        let error = upload_texture(
1925            device.as_ref(),
1926            queue,
1927            "compressed",
1928            Format::Bc1RgbaUnorm,
1929            8,
1930            8,
1931            &[0u8; 2 * 2 * 8],
1932        )
1933        .expect_err("a BC1 upload is sized per block, not per texel");
1934        assert!(
1935            error.to_string().contains("block-compressed"),
1936            "got: {error}"
1937        );
1938        assert_eq!(recorder.total_live_objects(), 0);
1939    }
1940
1941    /// A failure after the staging buffer exists releases it. `create_image`
1942    /// is what fails: Tier A's `max_image_2d` is 16384, and a 16385x1 R8 image
1943    /// is one byte per texel, so the staging allocation this must clean up is
1944    /// 16 KiB rather than something that would fail for its own reasons first.
1945    #[test]
1946    fn a_failed_upload_leaks_nothing() {
1947        let recorder = Recorder::new();
1948        let (device, queue) = open_tier_a(&recorder);
1949        let limit = device.caps().limits.max_image_2d;
1950        assert_eq!(limit, 16384);
1951        let before = recorder.total_live_objects();
1952
1953        let width = limit + 1;
1954        let pixels = vec![0u8; width as usize];
1955        let error = upload_texture(
1956            device.as_ref(),
1957            queue,
1958            "too wide",
1959            Format::R8Unorm,
1960            width,
1961            1,
1962            &pixels,
1963        )
1964        .expect_err("the device refuses an image past max_image_2d");
1965        assert!(
1966            error.to_string().contains("max_image_2d"),
1967            "the failure must be the image, not something earlier: {error}"
1968        );
1969
1970        assert_eq!(
1971            recorder.total_live_objects(),
1972            before,
1973            "the staging buffer created before the failure must be destroyed"
1974        );
1975        assert!(
1976            recorder
1977                .events()
1978                .iter()
1979                .any(|event| matches!(event, Event::BufferWritten { .. })),
1980            "the test is only meaningful if the staging buffer really was created \
1981             and written before the failure"
1982        );
1983    }
1984
1985    /// **A chain is one copy per level of every layer**, each into its own mip
1986    /// and each from its own padded offset — level-minor, so a layer's whole
1987    /// chain sits together in the staging buffer.
1988    ///
1989    /// Tier B again, for the padded-versus-unpadded reason above, and a width
1990    /// that halves onto rows of three different pitches: 100 texels pad to 512
1991    /// bytes, 50 to 256, 25 to 256. A level offset computed from level 0's
1992    /// pitch would land the second level's rows inside the first's tail.
1993    #[test]
1994    fn a_chain_copies_each_level_into_its_own_mip_from_its_own_offset() {
1995        let recorder = Recorder::new();
1996        let (device, queue) = open_tier_b(&recorder);
1997        // Three of the seven levels a 100-wide image has: a partial chain is
1998        // legal, and each level is its own extent's worth of texels.
1999        let level_extents = [(WIDTH, HEIGHT), (50, 1), (25, 1)];
2000        let chains: Vec<Vec<Vec<u8>>> = (0..2)
2001            .map(|_| {
2002                level_extents
2003                    .iter()
2004                    .map(|&(width, height)| ramp((width * height * 4) as usize))
2005                    .collect()
2006            })
2007            .collect();
2008        let levels: Vec<Vec<&[u8]>> = chains
2009            .iter()
2010            .map(|chain| chain.iter().map(Vec::as_slice).collect())
2011            .collect();
2012        let layers: Vec<&[&[u8]]> = levels.iter().map(Vec::as_slice).collect();
2013
2014        let page = upload_texture_mip_layers(
2015            device.as_ref(),
2016            queue,
2017            "mipped page",
2018            Format::Rgba8Unorm,
2019            WIDTH,
2020            HEIGHT,
2021            &layers,
2022        )
2023        .expect("the null backend accepts a partial chain");
2024
2025        let level_bytes = [PITCH * HEIGHT as usize, 256, 256];
2026        let layer_bytes: usize = level_bytes.iter().sum();
2027        assert_eq!(
2028            bytes_written(&recorder),
2029            layer_bytes * chains.len(),
2030            "the staging write is every level of every layer, each padded to its own pitch"
2031        );
2032        let copies = the_copies(&recorder);
2033        assert_eq!(copies.len(), chains.len() * level_extents.len());
2034        let mut expected_offset = 0u64;
2035        for (index, copy) in copies.iter().enumerate() {
2036            let layer = index / level_extents.len();
2037            let level = index % level_extents.len();
2038            let (width, height) = level_extents[level];
2039            assert_eq!(
2040                (
2041                    copy.image_subresource.base_layer,
2042                    copy.image_subresource.mip
2043                ),
2044                (layer as u32, level as u32),
2045                "copy {index} is layer {layer}'s level {level}"
2046            );
2047            assert_eq!(copy.image_subresource.layer_count, 1);
2048            assert_eq!(
2049                copy.buffer_offset, expected_offset,
2050                "layer {layer} level {level} reads from its own slice of the staging buffer"
2051            );
2052            assert_eq!(
2053                copy.image_extent,
2054                Extent3d::d2(width, height),
2055                "level {level} is copied at its own extent"
2056            );
2057            assert_eq!(copy.buffer_image_height, height);
2058            assert_eq!(
2059                copy.buffer_row_length as usize * 4,
2060                level_bytes[level] / height as usize,
2061                "level {level}'s pitch is its own row padded, in texels"
2062            );
2063            expected_offset += level_bytes[level] as u64;
2064        }
2065
2066        page.destroy(device.as_ref());
2067        recorder.assert_valid();
2068    }
2069
2070    /// The single-level form is the chain form with one level, so the image it
2071    /// creates has one mip and the copies name it — a `mip_levels` that
2072    /// followed the chain length would otherwise be off by one somewhere.
2073    #[test]
2074    fn a_single_level_page_is_a_chain_of_one() {
2075        let recorder = Recorder::new();
2076        let (device, queue) = open_tier_a(&recorder);
2077        let pixels = vec![0u8; 4 * 4 * 4];
2078        let page = upload_texture_layers(
2079            device.as_ref(),
2080            queue,
2081            "flat page",
2082            Format::Rgba8Unorm,
2083            4,
2084            4,
2085            &[&pixels],
2086        )
2087        .expect("accepted");
2088        let copy = the_copy(&recorder);
2089        assert_eq!(copy.image_subresource.mip, 0);
2090        page.destroy(device.as_ref());
2091        recorder.assert_valid();
2092    }
2093
2094    /// A chain that is ragged, too long, empty, or has a level of the wrong
2095    /// size is refused by name before anything is created.
2096    #[test]
2097    fn a_malformed_chain_is_rejected_naming_the_layer_and_the_level() {
2098        let recorder = Recorder::new();
2099        let (device, queue) = open_tier_a(&recorder);
2100        let before = recorder.total_live_objects();
2101        let level0 = vec![0u8; 4 * 4 * 4];
2102        let level1 = vec![0u8; 2 * 2 * 4];
2103        let level2 = vec![0u8; 4];
2104        let upload = |layers: &[&[&[u8]]]| {
2105            upload_texture_mip_layers(
2106                device.as_ref(),
2107                queue,
2108                "chain",
2109                Format::Rgba8Unorm,
2110                4,
2111                4,
2112                layers,
2113            )
2114            .expect_err("a malformed chain is not a page")
2115            .to_string()
2116        };
2117
2118        let ragged = upload(&[&[&level0, &level1], &[&level0]]);
2119        assert!(
2120            ragged.contains("layer 1 carries 1 mip levels and layer 0 carries 2"),
2121            "got: {ragged}"
2122        );
2123        let long = upload(&[&[&level0, &level1, &level2, &level2]]);
2124        assert!(
2125            long.contains("4 mip levels") && long.contains("full chain is 3"),
2126            "got: {long}"
2127        );
2128        let empty = upload(&[&[]]);
2129        assert!(empty.contains("no mip levels"), "got: {empty}");
2130        let wrong = upload(&[&[&level0, &level0]]);
2131        assert!(
2132            wrong.contains("layer 0 level 1") && wrong.contains("is 2x2, 16 bytes"),
2133            "got: {wrong}"
2134        );
2135
2136        assert_eq!(
2137            recorder.total_live_objects(),
2138            before,
2139            "a rejected chain creates nothing"
2140        );
2141    }
2142
2143    /// **A cleared page is zeroed on the GPU and copied into every layer, and
2144    /// only its patches cross from the host** — each into its own layer at its
2145    /// own corner, after the zeroes it overwrites.
2146    ///
2147    /// Tier B, so the page and the patch pitch to different strides: a 100-texel
2148    /// RGBA row pads to 512 bytes, the 5-texel patch row to 256.
2149    #[test]
2150    fn a_cleared_page_zeroes_every_layer_and_stages_only_its_patches() {
2151        let recorder = Recorder::new();
2152        let (device, queue) = open_tier_b(&recorder);
2153        let before = recorder.total_live_objects();
2154        let pixels = ramp(5 * 2 * 4);
2155
2156        let page = upload_cleared_texture(
2157            device.as_ref(),
2158            queue,
2159            &ClearedTextureDesc {
2160                label: "cleared page",
2161                format: Format::Rgba8Unorm,
2162                width: WIDTH,
2163                height: HEIGHT,
2164                layers: 3,
2165                view_type: ImageViewType::D2Array,
2166                patches: &[TexturePatch {
2167                    layer: 2,
2168                    x: 7,
2169                    y: 1,
2170                    width: 5,
2171                    height: 2,
2172                    pixels: &pixels,
2173                }],
2174            },
2175        )
2176        .expect("the null backend accepts this");
2177
2178        let commands = recorder.commands();
2179        let clears: Vec<(crcbl_hal::BufferHandle, u64, u64)> = commands
2180            .iter()
2181            .filter_map(|command| match command {
2182                Command::ClearBuffer {
2183                    buffer,
2184                    offset,
2185                    size,
2186                } => Some((*buffer, *offset, *size)),
2187                _ => None,
2188            })
2189            .collect();
2190        let [(zero, 0, size)] = clears[..] else {
2191            panic!("expected one clear from the start of one buffer, got {clears:?}");
2192        };
2193        assert_eq!(size as usize, PITCH * HEIGHT as usize, "one padded layer");
2194        let first_copy = commands
2195            .iter()
2196            .position(|command| matches!(command, Command::CopyBufferToImage(_)));
2197        let clear_at = commands
2198            .iter()
2199            .position(|command| matches!(command, Command::ClearBuffer { .. }));
2200        assert!(
2201            clear_at < first_copy,
2202            "the clear must be recorded before the copies that read it"
2203        );
2204
2205        let copies = the_copies(&recorder);
2206        // **Every texel of every layer is written exactly once**: by a zero
2207        // copy, or by the patch — never both, which sync validation reports.
2208        let mut writes = vec![0u8; 3 * (WIDTH * HEIGHT) as usize];
2209        for copy in &copies {
2210            let Offset3d { x, y, .. } = copy.image_offset;
2211            let layer = copy.image_subresource.base_layer;
2212            for row in 0..copy.image_extent.height {
2213                for column in 0..copy.image_extent.width {
2214                    let texel = (layer * WIDTH * HEIGHT
2215                        + (y as u32 + row) * WIDTH
2216                        + (x as u32 + column)) as usize;
2217                    writes[texel] += 1;
2218                }
2219            }
2220            if copy.buffer == zero {
2221                assert_eq!(copy.buffer_offset, 0);
2222                assert_eq!(copy.buffer_row_length, 128);
2223            }
2224        }
2225        assert!(
2226            writes.iter().all(|&count| count == 1),
2227            "a texel was written {} times, or not at all: {copies:?}",
2228            writes
2229                .iter()
2230                .copied()
2231                .find(|&count| count != 1)
2232                .unwrap_or(1)
2233        );
2234        let zeroes: Vec<_> = copies.iter().filter(|copy| copy.buffer == zero).collect();
2235        assert_eq!(
2236            zeroes.len(),
2237            2 + 3,
2238            "one copy for each unpatched layer, and the patched layer as the row \
2239             above its patch and the two spans beside it: {copies:?}"
2240        );
2241        let [patch] = copies
2242            .iter()
2243            .filter(|copy| copy.buffer != zero)
2244            .collect::<Vec<_>>()[..]
2245        else {
2246            panic!("expected one staged patch copy: {copies:?}");
2247        };
2248        let patch = *patch;
2249        assert_ne!(patch.buffer, zero, "a patch is staged, not cleared");
2250        assert_eq!(patch.buffer_offset, 0);
2251        assert_eq!(
2252            patch.buffer_row_length, 64,
2253            "256 bytes of pitch is 64 texels"
2254        );
2255        assert_eq!(patch.image_subresource.base_layer, 2);
2256        assert_eq!(patch.image_extent, Extent3d::d2(5, 2));
2257        assert_eq!(patch.image_offset, Offset3d { x: 7, y: 1, z: 0 });
2258
2259        let writes: Vec<(crcbl_hal::BufferHandle, usize)> = recorder
2260            .events()
2261            .into_iter()
2262            .filter_map(|event| match event {
2263                Event::BufferWritten { buffer, len, .. } => Some((buffer, len)),
2264                _ => None,
2265            })
2266            .collect();
2267        assert_eq!(
2268            writes,
2269            [(patch.buffer, 256 * 2)],
2270            "the host writes the padded patch and nothing of the page"
2271        );
2272
2273        page.destroy(device.as_ref());
2274        assert_eq!(
2275            recorder.total_live_objects(),
2276            before,
2277            "both buffers are released once the copies are submitted"
2278        );
2279        recorder.assert_valid();
2280    }
2281
2282    /// A page with nothing patched creates no staging buffer and writes nothing.
2283    #[test]
2284    fn a_cleared_page_with_no_patches_writes_nothing() {
2285        let recorder = Recorder::new();
2286        let (device, queue) = open_tier_a(&recorder);
2287        let page = upload_cleared_texture(
2288            device.as_ref(),
2289            queue,
2290            &ClearedTextureDesc {
2291                label: "empty page",
2292                format: Format::R8Unorm,
2293                width: 16,
2294                height: 16,
2295                layers: 2,
2296                view_type: ImageViewType::D2Array,
2297                patches: &[],
2298            },
2299        )
2300        .expect("accepted");
2301        assert!(
2302            !recorder
2303                .events()
2304                .iter()
2305                .any(|event| matches!(event, Event::BufferWritten { .. })),
2306            "an unpatched page is all zeroes, and zeroes are the GPU's to write"
2307        );
2308        assert_eq!(the_copies(&recorder).len(), 2, "one copy a layer");
2309        page.destroy(device.as_ref());
2310        recorder.assert_valid();
2311    }
2312
2313    /// A patch off its layer, outside the extent, empty, or not its own size is
2314    /// refused naming the patch — and so is a page with no layers — before
2315    /// anything is created.
2316    #[test]
2317    fn a_malformed_cleared_page_is_rejected_naming_the_patch() {
2318        let recorder = Recorder::new();
2319        let (device, queue) = open_tier_a(&recorder);
2320        let before = recorder.total_live_objects();
2321        let four = [0u8; 4];
2322        let upload = |layers: u32, patch: TexturePatch<'_>| {
2323            upload_cleared_texture(
2324                device.as_ref(),
2325                queue,
2326                &ClearedTextureDesc {
2327                    label: "atlas",
2328                    format: Format::Rgba8Unorm,
2329                    width: 8,
2330                    height: 8,
2331                    layers,
2332                    view_type: ImageViewType::D2,
2333                    patches: &[patch],
2334                },
2335            )
2336            .expect_err("a malformed page is not a texture")
2337            .to_string()
2338        };
2339        let texel = TexturePatch {
2340            layer: 0,
2341            x: 0,
2342            y: 0,
2343            width: 1,
2344            height: 1,
2345            pixels: &four,
2346        };
2347
2348        let no_layers = upload(0, texel);
2349        assert!(no_layers.contains("at least one layer"), "got: {no_layers}");
2350        for (patch, why) in [
2351            (TexturePatch { layer: 1, ..texel }, "off the only layer"),
2352            (TexturePatch { x: 8, ..texel }, "right of the extent"),
2353            (
2354                TexturePatch {
2355                    y: u32::MAX,
2356                    ..texel
2357                },
2358                "overflowing the extent",
2359            ),
2360            (TexturePatch { width: 0, ..texel }, "empty"),
2361        ] {
2362            let message = upload(1, patch);
2363            assert!(
2364                message.contains("patch 0") && message.contains("inside a 8x8 image"),
2365                "a patch {why} got: {message}"
2366            );
2367        }
2368        let overlapping = upload_cleared_texture(
2369            device.as_ref(),
2370            queue,
2371            &ClearedTextureDesc {
2372                label: "atlas",
2373                format: Format::Rgba8Unorm,
2374                width: 8,
2375                height: 8,
2376                layers: 1,
2377                view_type: ImageViewType::D2,
2378                patches: &[texel, texel],
2379            },
2380        )
2381        .expect_err("two patches on one texel are refused")
2382        .to_string();
2383        assert!(
2384            overlapping.contains("patch 1 overlaps patch 0"),
2385            "got: {overlapping}"
2386        );
2387        let short = upload(1, TexturePatch { width: 2, ..texel });
2388        assert!(
2389            short.contains("patch 0") && short.contains("8 bytes, got 4"),
2390            "got: {short}"
2391        );
2392
2393        assert_eq!(
2394            recorder.total_live_objects(),
2395            before,
2396            "a rejected page creates nothing"
2397        );
2398    }
2399
2400    /// A failure after both buffers exist releases both: the image is what
2401    /// fails, one texel past Tier A's `max_image_2d`.
2402    #[test]
2403    fn a_failed_cleared_page_leaks_nothing() {
2404        let recorder = Recorder::new();
2405        let (device, queue) = open_tier_a(&recorder);
2406        let limit = device.caps().limits.max_image_2d;
2407        let before = recorder.total_live_objects();
2408        let four = [0u8; 4];
2409
2410        let error = upload_cleared_texture(
2411            device.as_ref(),
2412            queue,
2413            &ClearedTextureDesc {
2414                label: "too wide",
2415                format: Format::R8Unorm,
2416                width: limit + 1,
2417                height: 1,
2418                layers: 1,
2419                view_type: ImageViewType::D2,
2420                patches: &[TexturePatch {
2421                    layer: 0,
2422                    x: 0,
2423                    y: 0,
2424                    width: 4,
2425                    height: 1,
2426                    pixels: &four,
2427                }],
2428            },
2429        )
2430        .expect_err("the device refuses an image past max_image_2d");
2431        assert!(
2432            error.to_string().contains("max_image_2d"),
2433            "the failure must be the image, not something earlier: {error}"
2434        );
2435        assert!(
2436            recorder
2437                .events()
2438                .iter()
2439                .any(|event| matches!(event, Event::BufferWritten { .. })),
2440            "only meaningful if the staging buffer really was created and written"
2441        );
2442        assert_eq!(
2443            recorder.total_live_objects(),
2444            before,
2445            "the zeroed and the staging buffer must both be destroyed"
2446        );
2447    }
2448
2449    /// A device-local buffer of `size` bytes a fill can copy into.
2450    fn fill_target(device: &dyn Device, size: u64) -> crcbl_hal::BufferHandle {
2451        device
2452            .create_buffer(&BufferDesc {
2453                label: Some("fill target"),
2454                size,
2455                usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_DST,
2456                memory: MemoryLocation::DeviceLocal,
2457            })
2458            .expect("the null backend allocates")
2459    }
2460
2461    /// **A fill is a copy between two barriers on the buffer, and nothing
2462    /// else**: in from `Undefined`, out to the state the caller named. Neither
2463    /// the null backend nor the Vulkan validation layer tracks a buffer's state
2464    /// across submissions, so a fill that left its buffer in `TransferDst`
2465    /// draws correctly behind the batch's `wait_idle` and only this sees it.
2466    #[test]
2467    fn a_fill_copies_its_bytes_between_its_two_barriers() {
2468        let recorder = Recorder::new();
2469        let (device, queue) = open_tier_a(&recorder);
2470        let contents = ramp(12);
2471        let buffer = fill_target(device.as_ref(), contents.len() as u64);
2472        let before = recorder.total_live_objects();
2473
2474        let mut batch = UploadBatch::new(device.as_ref(), queue, "fill");
2475        batch
2476            .fill("state", buffer, &contents, ResourceState::ShaderReadWrite)
2477            .expect("the null backend accepts this");
2478        // Read before the submit, which releases it: the bytes the copy will
2479        // read are the caller's, exactly.
2480        let [staging] = batch.buffers[..] else {
2481            panic!("one fill stages one buffer, got {:?}", batch.buffers);
2482        };
2483        assert_eq!(
2484            recorder.buffer_bytes(staging).as_deref(),
2485            Some(&contents[..])
2486        );
2487        batch.submit().expect("the null backend submits");
2488
2489        let commands = recorder.commands();
2490        let [
2491            Command::Barrier {
2492                buffers: into,
2493                images: into_images,
2494                ..
2495            },
2496            Command::CopyBufferToBuffer(copy),
2497            Command::Barrier {
2498                buffers: out,
2499                images: out_images,
2500                ..
2501            },
2502        ] = &commands[..]
2503        else {
2504            panic!("expected a barrier, a copy and a barrier, got {commands:?}");
2505        };
2506        assert!(into_images.is_empty() && out_images.is_empty());
2507        assert_eq!(
2508            into[..],
2509            [crcbl_hal::BufferBarrier::new(
2510                buffer,
2511                ResourceState::Undefined,
2512                ResourceState::TransferDst
2513            )]
2514        );
2515        assert_eq!(
2516            out[..],
2517            [crcbl_hal::BufferBarrier::new(
2518                buffer,
2519                ResourceState::TransferDst,
2520                ResourceState::ShaderReadWrite
2521            )]
2522        );
2523        assert_eq!((copy.src, copy.src_offset), (staging, 0));
2524        assert_eq!((copy.dst, copy.dst_offset), (buffer, 0));
2525        assert_eq!(copy.size, contents.len() as u64);
2526        assert_eq!(
2527            recorder.buffer_bytes(copy.src).as_deref(),
2528            None,
2529            "the staging buffer is released once the batch has waited"
2530        );
2531        assert_eq!(
2532            recorder.total_live_objects(),
2533            before,
2534            "the staging buffer, the encoder and the command buffer are all released"
2535        );
2536        recorder.assert_valid();
2537        device.destroy_buffer(buffer);
2538    }
2539
2540    /// **Several uploads, one submission and one wait** — the batch's point.
2541    #[test]
2542    fn a_batch_submits_every_upload_once() {
2543        let recorder = Recorder::new();
2544        let (device, queue) = open_tier_a(&recorder);
2545        let buffer = fill_target(device.as_ref(), 4);
2546
2547        let mut batch = UploadBatch::new(device.as_ref(), queue, "several");
2548        let first = batch
2549            .texture(
2550                "one",
2551                Format::R8Unorm,
2552                (1, 1),
2553                &[&[&[1]]],
2554                ImageViewType::D2,
2555            )
2556            .expect("recorded");
2557        let second = batch
2558            .texture(
2559                "two",
2560                Format::R8Unorm,
2561                (1, 1),
2562                &[&[&[2]]],
2563                ImageViewType::D2,
2564            )
2565            .expect("recorded");
2566        batch
2567            .fill("state", buffer, &[0; 4], ResourceState::ShaderRead)
2568            .expect("recorded");
2569        batch.submit().expect("submitted");
2570
2571        let events = recorder.events();
2572        let submits = events
2573            .iter()
2574            .filter(|event| matches!(event, Event::Submitted { .. }))
2575            .count();
2576        let waits = events
2577            .iter()
2578            .filter(|event| matches!(event, Event::WaitedIdle))
2579            .count();
2580        assert_eq!((submits, waits), (1, 1));
2581        recorder.assert_valid();
2582        first.destroy(device.as_ref());
2583        second.destroy(device.as_ref());
2584        device.destroy_buffer(buffer);
2585    }
2586
2587    /// A one-texture batch on `device`, submitted with
2588    /// [`UploadBatch::submit_deferred`], and its staging buffer.
2589    fn deferred_one(
2590        recorder: &Recorder,
2591        device: &dyn Device,
2592        queue: QueueHandle,
2593    ) -> (UploadedTexture, PendingUpload, crcbl_hal::BufferHandle) {
2594        let mut batch = UploadBatch::new(device, queue, "deferred");
2595        let texture = batch
2596            .texture(
2597                "one",
2598                Format::R8Unorm,
2599                (1, 1),
2600                &[&[&[1]]],
2601                ImageViewType::D2,
2602            )
2603            .expect("recorded");
2604        let pending = batch.submit_deferred().expect("submitted");
2605        let staging = the_copies(recorder)
2606            .first()
2607            .expect("the texture's copy")
2608            .buffer;
2609        (texture, pending, staging)
2610    }
2611
2612    /// **A deferred submit waits for nothing and frees nothing** until it is
2613    /// polled past its semaphore's value — and then frees the staging, the
2614    /// command buffer and the semaphore, once.
2615    #[test]
2616    fn a_deferred_submit_keeps_its_staging_until_polled() {
2617        let recorder = Recorder::new();
2618        let (device, queue) = open_tier_a(&recorder);
2619        let before = recorder.total_live_objects();
2620        let (texture, mut pending, staging) = deferred_one(&recorder, device.as_ref(), queue);
2621
2622        let events = recorder.events();
2623        assert!(
2624            !events
2625                .iter()
2626                .any(|event| matches!(event, Event::WaitedIdle))
2627        );
2628        let signals: Vec<_> = events
2629            .iter()
2630            .filter_map(|event| match event {
2631                Event::Submitted { signals, .. } => Some(signals.clone()),
2632                _ => None,
2633            })
2634            .collect();
2635        assert_eq!(signals.len(), 1, "one submission");
2636        assert_eq!(signals[0].len(), 1, "signalling one semaphore");
2637        assert_eq!(signals[0][0].value, PendingUpload::LANDED);
2638        assert!(
2639            recorder.buffer_size(staging).is_some(),
2640            "alive until polled"
2641        );
2642        assert!(!pending.is_retired());
2643
2644        assert!(pending.poll(device.as_ref()).expect("polled"));
2645        assert_eq!(recorder.buffer_size(staging), None, "freed by the poll");
2646        assert!(pending.poll(device.as_ref()).expect("polled again"));
2647        texture.destroy(device.as_ref());
2648        assert_eq!(recorder.total_live_objects(), before);
2649        recorder.assert_valid();
2650    }
2651
2652    /// [`PendingUpload::wait`] frees what [`PendingUpload::poll`] would.
2653    #[test]
2654    fn waiting_for_a_deferred_submit_frees_it() {
2655        let recorder = Recorder::new();
2656        let (device, queue) = open_tier_a(&recorder);
2657        let before = recorder.total_live_objects();
2658        let (texture, mut pending, staging) = deferred_one(&recorder, device.as_ref(), queue);
2659        pending.wait(device.as_ref()).expect("waited");
2660        assert!(pending.is_retired());
2661        assert_eq!(recorder.buffer_size(staging), None);
2662        pending
2663            .wait(device.as_ref())
2664            .expect("a second wait is a no-op");
2665        texture.destroy(device.as_ref());
2666        assert_eq!(recorder.total_live_objects(), before);
2667        recorder.assert_valid();
2668    }
2669
2670    /// **Without timeline semaphores a deferred submit is the waiting one**,
2671    /// chosen by the capability, not by an error.
2672    #[test]
2673    fn a_deferred_submit_without_a_timeline_waits() {
2674        let recorder = Recorder::new();
2675        let (device, queue) = open_tier_b(&recorder);
2676        assert!(!device.caps().supports(Features::TIMELINE_SEMAPHORE));
2677        let (texture, pending, staging) = deferred_one(&recorder, device.as_ref(), queue);
2678        let waits = recorder
2679            .events()
2680            .iter()
2681            .filter(|event| matches!(event, Event::WaitedIdle))
2682            .count();
2683        assert_eq!(waits, 1);
2684        assert!(pending.is_retired());
2685        assert_eq!(recorder.buffer_size(staging), None);
2686        texture.destroy(device.as_ref());
2687        recorder.assert_valid();
2688    }
2689
2690    /// An abandoned batch refuses a deferred submit as it does a waiting one,
2691    /// before creating a semaphore it would have to give back.
2692    #[test]
2693    fn an_abandoned_batch_refuses_a_deferred_submit() {
2694        let recorder = Recorder::new();
2695        let (device, queue) = open_tier_a(&recorder);
2696        let before = recorder.total_live_objects();
2697        let mut batch = UploadBatch::new(device.as_ref(), queue, "abandoned");
2698        let texture = batch
2699            .texture(
2700                "one",
2701                Format::R8Unorm,
2702                (1, 1),
2703                &[&[&[1]]],
2704                ImageViewType::D2,
2705            )
2706            .expect("recorded");
2707        texture.destroy(device.as_ref());
2708        batch.abandon();
2709        assert!(matches!(
2710            batch.submit_deferred(),
2711            Err(HalError::InvalidDescriptor(_))
2712        ));
2713        assert_eq!(recorder.total_live_objects(), before);
2714        assert!(
2715            !recorder
2716                .events()
2717                .iter()
2718                .any(|event| matches!(event, Event::Submitted { .. }))
2719        );
2720        recorder.assert_valid();
2721    }
2722
2723    /// **A batch holds no encoder open while its caller records others.** A
2724    /// build keeps one batch across steps that create, finish and submit
2725    /// encoders of their own, and `crcbl-webgpu` records every command into
2726    /// the encoder created last — so a batch that opened its encoder in `new`
2727    /// had its copies land after that encoder was finished, and the browser
2728    /// refused them. Every one of the batch's commands must be in one command
2729    /// buffer, from an encoder created after the other was finished.
2730    #[test]
2731    fn a_batch_records_nothing_until_its_submit() {
2732        let recorder = Recorder::new();
2733        let (device, queue) = open_tier_a(&recorder);
2734        let buffer = fill_target(device.as_ref(), 4);
2735
2736        let mut batch = UploadBatch::new(device.as_ref(), queue, "interleaved");
2737        let first = batch
2738            .texture(
2739                "before",
2740                Format::R8Unorm,
2741                (1, 1),
2742                &[&[&[1]]],
2743                ImageViewType::D2,
2744            )
2745            .expect("recorded");
2746        // Another build step's own encoder, start to finish, while the batch
2747        // is open.
2748        let mut other = device.create_command_encoder(&CommandEncoderDesc {
2749            label: Some("other step"),
2750            queue,
2751        });
2752        other.insert_debug_marker("other step");
2753        let other = other.finish().expect("finished");
2754        device
2755            .submit(queue, &SubmitInfo::new(&[other]))
2756            .expect("submitted");
2757        device.destroy_command_buffer(other);
2758        let second = batch
2759            .texture(
2760                "after",
2761                Format::R8Unorm,
2762                (1, 1),
2763                &[&[&[2]]],
2764                ImageViewType::D2,
2765            )
2766            .expect("recorded");
2767        batch
2768            .fill("state", buffer, &[0; 4], ResourceState::ShaderRead)
2769            .expect("recorded");
2770        batch.submit().expect("submitted");
2771
2772        recorder.assert_valid();
2773        let events = recorder.events();
2774        let finished: Vec<_> = events
2775            .iter()
2776            .filter_map(|event| match event {
2777                Event::Finished {
2778                    label,
2779                    command_buffer,
2780                } => Some((label.clone(), *command_buffer)),
2781                _ => None,
2782            })
2783            .collect();
2784        let [(other_label, other_buffer), (batch_label, batch_buffer)] = &finished[..] else {
2785            panic!("expected the other step's buffer and then the batch's, got {finished:?}");
2786        };
2787        assert_eq!(other_label.as_deref(), Some("other step"));
2788        assert_eq!(batch_label.as_deref(), Some("interleaved upload"));
2789        let in_batch = |buffer| {
2790            events
2791                .iter()
2792                .filter(|event| {
2793                    matches!(event, Event::Command { command_buffer, .. } if *command_buffer == buffer)
2794                })
2795                .count()
2796        };
2797        assert_eq!(in_batch(*other_buffer), 1, "the other step's marker alone");
2798        assert_eq!(
2799            in_batch(*batch_buffer),
2800            recorder.commands().len() - 1,
2801            "every batch command is in the batch's one command buffer"
2802        );
2803        assert_eq!(
2804            recorder
2805                .commands()
2806                .iter()
2807                .filter(|command| matches!(command, Command::CopyBufferToImage(_)))
2808                .count(),
2809            2
2810        );
2811        first.destroy(device.as_ref());
2812        second.destroy(device.as_ref());
2813        device.destroy_buffer(buffer);
2814    }
2815
2816    /// **An abandoned batch refuses everything and submits nothing**, so a
2817    /// caller that rolled back an image it had added cannot then submit a copy
2818    /// into it.
2819    #[test]
2820    fn an_abandoned_batch_refuses_to_record_or_submit() {
2821        let recorder = Recorder::new();
2822        let (device, queue) = open_tier_a(&recorder);
2823        let before = recorder.total_live_objects();
2824        let buffer = fill_target(device.as_ref(), 4);
2825
2826        let mut batch = UploadBatch::new(device.as_ref(), queue, "rolled back");
2827        let texture = batch
2828            .texture(
2829                "gone",
2830                Format::R8Unorm,
2831                (1, 1),
2832                &[&[&[1]]],
2833                ImageViewType::D2,
2834            )
2835            .expect("recorded");
2836        batch.abandon();
2837        texture.destroy(device.as_ref());
2838
2839        let refused = batch
2840            .texture(
2841                "late",
2842                Format::R8Unorm,
2843                (1, 1),
2844                &[&[&[1]]],
2845                ImageViewType::D2,
2846            )
2847            .expect_err("an abandoned batch records nothing");
2848        assert!(refused.to_string().contains("abandoned"), "{refused}");
2849        batch
2850            .fill("late", buffer, &[0; 4], ResourceState::ShaderRead)
2851            .expect_err("nor a fill");
2852        let refused = batch.submit().expect_err("and submits nothing");
2853        assert!(
2854            refused.to_string().contains("rolled back upload"),
2855            "names the batch: {refused}"
2856        );
2857        assert!(
2858            !recorder
2859                .events()
2860                .iter()
2861                .any(|event| matches!(event, Event::Submitted { .. })),
2862            "nothing reached the queue"
2863        );
2864        device.destroy_buffer(buffer);
2865        assert_eq!(
2866            recorder.total_live_objects(),
2867            before,
2868            "the staging buffer goes with the batch"
2869        );
2870    }
2871}