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//! This is a **startup** path, not a frame path: it records its own barriers
40//! and blocks on [`Device::wait_idle`], which is only legal because no graph
41//! is being recorded while it runs. See this crate's docs on the one rule — the
42//! two staging uploads (`crcbl_render::forward`'s cube and this) are its named
43//! exceptions. Its barriers name only the image it creates, so a caller between
44//! two frames — `ForwardRenderer::replace_page`
45//! reloading a page — touches nothing a frame in flight reads, and the wait
46//! means no frame can bind the image before its copy has landed.
47//!
48//! # Why it is not in `ui_pass`
49//!
50//! It was, and it was `R8_UNORM` only, with the glyph atlas's labels baked in.
51//! The interesting part is that the old code was *right by coincidence*: it
52//! computed a row pitch from `width`, called it `row_texels`, and handed it to
53//! [`BufferImageCopy::buffer_row_length`] — which really is in texels, and
54//! really did equal the byte count, because `R8Unorm` is one byte per texel.
55//! For `Rgba8Unorm` the two differ by four, so the pitch here is computed in
56//! **bytes** and converted back to texels exactly once, at the copy.
57
58use crcbl_hal::{
59    BufferDesc, BufferImageCopy, BufferUsage, CommandEncoderDesc, Device, Extent3d, Format,
60    HalError, ImageAspect, ImageDesc, ImageHandle, ImageSubresourceLayers, ImageSubresourceRange,
61    ImageType, ImageUsage, ImageViewDesc, ImageViewHandle, ImageViewType, MemoryLocation, Offset3d,
62    QueueHandle, ResourceState, SubmitInfo,
63};
64
65use crate::mip::level_extent;
66
67/// A texture that has been uploaded: the image, and the view callers bind.
68///
69/// The two travel together because they die together, and every caller that
70/// kept them as two loose handles has had to remember that on both its failure
71/// path and its teardown path. [`UploadedTexture::destroy`] is the one place
72/// the order lives.
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub struct UploadedTexture {
75    /// The device-local image the copy filled.
76    pub image: ImageHandle,
77    /// A full-subresource colour view of [`UploadedTexture::image`]: `D2` from
78    /// [`upload_texture`], `D2Array` from [`upload_texture_layers`] and
79    /// [`upload_texture_mip_layers`].
80    pub view: ImageViewHandle,
81}
82
83impl UploadedTexture {
84    /// Releases the view and then the image. The device must be idle.
85    pub fn destroy(&self, device: &dyn Device) {
86        device.destroy_image_view(self.view);
87        device.destroy_image(self.image);
88    }
89}
90
91/// Uploads a 2D colour texture via a staging-buffer copy, and returns the image
92/// and a view onto it.
93///
94/// `label` names the image and the view, and is the stem of the staging
95/// buffer's and the encoder's names, so a capture shows which texture an
96/// upload belonged to.
97///
98/// `pixels` must be exactly `width * height * texel_size` bytes, tightly
99/// packed; the row padding the device's copy alignment wants is added here.
100/// Padding rather than packing is what makes one upload path work on both
101/// backends: Vulkan takes either, WebGPU requires a 256-byte row pitch and says
102/// so through
103/// [`optimal_buffer_copy_offset_alignment`](crcbl_hal::Limits::optimal_buffer_copy_offset_alignment).
104///
105/// Every object this creates is released on every path out, including the
106/// failing ones: a `?` that dropped the staging buffer on the floor would leak
107/// one per failed startup, and the recorder's leak assertions would only notice
108/// once something actually failed.
109///
110/// # Errors
111///
112/// [`HalError::InvalidDescriptor`] if `format` has no single colour plane, if
113/// either extent is zero, or if `pixels` is not exactly the size the extent and
114/// the format imply — the last of which used to be a `copy_from_slice` panic
115/// naming neither number. [`HalError`] from any seam call otherwise; an extent
116/// past the device's `max_image_2d` is the device's to refuse, not this
117/// function's.
118pub fn upload_texture(
119    device: &dyn Device,
120    queue: QueueHandle,
121    label: &str,
122    format: Format,
123    width: u32,
124    height: u32,
125    pixels: &[u8],
126) -> Result<UploadedTexture, HalError> {
127    upload(
128        device,
129        queue,
130        label,
131        format,
132        (width, height),
133        &[&[pixels]],
134        ImageViewType::D2,
135    )
136}
137
138/// Uploads several equally-sized layers into one `D2Array` colour image, and
139/// returns it with an array view onto every layer.
140///
141/// §3.2's [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) page: the index a
142/// material row carries is a layer of the image this returns. One image rather
143/// than one descriptor per texture is what makes the lookup need no
144/// [`Features::DESCRIPTOR_INDEXING`](crcbl_hal::Features::DESCRIPTOR_INDEXING),
145/// and therefore run on every backend the engine has — see
146/// `crcbl_render::forward`, which builds the page this crate's only caller binds.
147///
148/// Every slice in `layers` must be exactly one tightly packed
149/// `width * height * texel_size` image, and they become layers 0, 1, … in the
150/// order given. [`upload_texture`]'s account of the label, the row padding and
151/// the release-on-every-path rule applies here unchanged. The image has one
152/// mip level; [`upload_texture_mip_layers`] is the form that carries a chain.
153///
154/// # Errors
155///
156/// [`upload_texture`]'s errors, plus [`HalError::InvalidDescriptor`] when
157/// `layers` is empty — a zero-layer image is not a page, and it reaches the
158/// device as a zero extent whose complaint names a different thing. A layer
159/// count past the device's `max_image_array_layers` is the device's to refuse.
160pub fn upload_texture_layers(
161    device: &dyn Device,
162    queue: QueueHandle,
163    label: &str,
164    format: Format,
165    width: u32,
166    height: u32,
167    layers: &[&[u8]],
168) -> Result<UploadedTexture, HalError> {
169    let chains: Vec<[&[u8]; 1]> = layers.iter().map(|pixels| [*pixels]).collect();
170    let layers: Vec<&[&[u8]]> = chains.iter().map(|chain| &chain[..]).collect();
171    upload(
172        device,
173        queue,
174        label,
175        format,
176        (width, height),
177        &layers,
178        ImageViewType::D2Array,
179    )
180}
181
182/// [`upload_texture_layers`] with a mip chain behind every layer: one
183/// `D2Array` image whose level count is the chain's length, and an array view
184/// onto every level of every layer.
185///
186/// `layers[layer][level]` is level `level` of layer `layer`, tightly packed at
187/// that level's extent — `width` and `height` each halved per level and never
188/// below one texel, which is [`crate::mip::level_extent`] and every backend's
189/// own definition. Every layer carries the same number of levels, at least one
190/// and at most the full chain
191/// [`Extent3d::full_mip_levels`](crcbl_hal::Extent3d::full_mip_levels) counts;
192/// a shorter chain is legal and leaves the sampler's `lod_max` to the caller.
193///
194/// # Errors
195///
196/// [`upload_texture_layers`]'s errors, plus [`HalError::InvalidDescriptor`]
197/// when a layer has no levels, when two layers disagree on how many, when the
198/// count exceeds the full chain, or when a level is not exactly its own
199/// extent's worth of texels — each naming the layer and the level.
200pub fn upload_texture_mip_layers(
201    device: &dyn Device,
202    queue: QueueHandle,
203    label: &str,
204    format: Format,
205    width: u32,
206    height: u32,
207    layers: &[&[&[u8]]],
208) -> Result<UploadedTexture, HalError> {
209    upload(
210        device,
211        queue,
212        label,
213        format,
214        (width, height),
215        layers,
216        ImageViewType::D2Array,
217    )
218}
219
220/// Texels written over an [`upload_cleared_texture`] image as it is created: a
221/// `width` by `height` rectangle of layer `layer`, its top-left texel at `x`,
222/// `y`.
223#[derive(Clone, Copy, Debug)]
224pub struct TexturePatch<'a> {
225    /// The array layer the rectangle is written to.
226    pub layer: u32,
227    /// The rectangle's left column.
228    pub x: u32,
229    /// The rectangle's top row.
230    pub y: u32,
231    /// Its width in texels.
232    pub width: u32,
233    /// Its height in texels.
234    pub height: u32,
235    /// Exactly `width * height * texel_size` bytes, tightly packed, rows top to
236    /// bottom.
237    pub pixels: &'a [u8],
238}
239
240/// The image [`upload_cleared_texture`] creates, and what goes on it.
241#[derive(Clone, Copy, Debug)]
242pub struct ClearedTextureDesc<'a> {
243    /// Names the image and the view, and is the stem of the buffers' and the
244    /// encoder's names, as in [`upload_texture`].
245    pub label: &'a str,
246    /// An uncompressed format with a single colour plane.
247    pub format: Format,
248    /// Width of every layer, in texels.
249    pub width: u32,
250    /// Height of every layer, in texels.
251    pub height: u32,
252    /// Array layers in the image; at least one.
253    pub layers: u32,
254    /// `D2` or `D2Array`: the shader's declaration decides, not `layers`.
255    pub view_type: ImageViewType,
256    /// Rectangles written over the zeroes, in order.
257    pub patches: &'a [TexturePatch<'a>],
258}
259
260/// Creates a sampled colour image whose every texel is zero, with `patches`
261/// written over it, and returns it with a full view.
262///
263/// **For a page that is mostly empty**, which is what an atlas is when it is
264/// created: [`crate::ui_pass`]'s image atlas and glyph pages. Staging such a
265/// page through [`upload_texture`] builds every zero texel on the host, pads a
266/// second copy of it, and writes it into a staging buffer — and on
267/// `crcbl-webgpu` that write is bytes on the command stream, which lives in the
268/// wasm heap, grows to hold the whole start-up frame and never gives the
269/// address space back. Here the zeroes never exist on the host: one
270/// device-local buffer a layer in size is zeroed by
271/// [`clear_buffer`](crcbl_hal::CommandEncoder::clear_buffer) and copied into
272/// every layer, and only the patches are staged and written. The page is
273/// transparent black where nothing was patched, on every backend, rather than
274/// whatever an uninitialised image held.
275///
276/// One mip level. The same startup rules as [`upload_texture`]: it records its
277/// own barriers, blocks on [`Device::wait_idle`], and releases every buffer it
278/// created on every path out.
279///
280/// # Errors
281///
282/// [`upload_texture`]'s format and extent errors;
283/// [`HalError::InvalidDescriptor`] for zero layers, and for a patch that is
284/// empty, is not on a layer or inside the extent, or whose `pixels` is not its
285/// own size — naming the patch. [`HalError`] from any seam call otherwise.
286pub fn upload_cleared_texture(
287    device: &dyn Device,
288    queue: QueueHandle,
289    desc: &ClearedTextureDesc<'_>,
290) -> Result<UploadedTexture, HalError> {
291    let label = desc.label;
292    let texel = image_texel(label, desc.format, (desc.width, desc.height))?;
293    if desc.layers == 0 {
294        return Err(HalError::InvalidDescriptor(format!(
295            "{label}: a texture needs at least one layer"
296        )));
297    }
298    let alignment = device
299        .caps()
300        .limits
301        .optimal_buffer_copy_offset_alignment
302        .max(1);
303    let full = u64::from(desc.width) * u64::from(texel);
304    let full_pitch = padded_row_pitch(full, texel, alignment);
305    // Whole words: `vkCmdFillBuffer` and `crcbl-dx12`'s clear refuse a size that
306    // is not a multiple of four.
307    let cleared = (full_pitch * u64::from(desc.height)).next_multiple_of(CLEAR_WORD_BYTES);
308    let mut patched = Vec::new();
309    let mut patch_regions = Vec::with_capacity(desc.patches.len());
310    for (index, patch) in desc.patches.iter().enumerate() {
311        let inside = patch
312            .x
313            .checked_add(patch.width)
314            .is_some_and(|right| right <= desc.width)
315            && patch
316                .y
317                .checked_add(patch.height)
318                .is_some_and(|bottom| bottom <= desc.height);
319        if patch.width == 0 || patch.height == 0 || patch.layer >= desc.layers || !inside {
320            return Err(HalError::InvalidDescriptor(format!(
321                "{label}: patch {index} is {}x{} at {},{} on layer {}, which is not a non-empty \
322                 rectangle inside a {}x{} image of {} layer(s)",
323                patch.width,
324                patch.height,
325                patch.x,
326                patch.y,
327                patch.layer,
328                desc.width,
329                desc.height,
330                desc.layers
331            )));
332        }
333        if let Some(other) = desc.patches[..index]
334            .iter()
335            .position(|earlier| earlier.layer == patch.layer && overlaps(earlier, patch))
336        {
337            return Err(HalError::InvalidDescriptor(format!(
338                "{label}: patch {index} overlaps patch {other} on layer {}, and a texel written \
339                 twice in one upload is a synchronisation hazard",
340                patch.layer
341            )));
342        }
343        let row_bytes = u64::from(patch.width) * u64::from(texel);
344        let expected = row_bytes * u64::from(patch.height);
345        if patch.pixels.len() as u64 != expected {
346            return Err(HalError::InvalidDescriptor(format!(
347                "{label}: patch {index} is {}x{} {:?}, {expected} bytes, got {}",
348                patch.width,
349                patch.height,
350                desc.format,
351                patch.pixels.len()
352            )));
353        }
354        let row_pitch = padded_row_pitch(row_bytes, texel, alignment);
355        let staged =
356            stage_rows(row_bytes, patch.height, row_pitch, patch.pixels).ok_or_else(|| {
357                HalError::InvalidDescriptor(format!(
358                    "{label}: patch {index} does not fit in this host's address space"
359                ))
360            })?;
361        patch_regions.push(StagedRegion {
362            buffer_offset: patched.len() as u64,
363            row_texels: u32::try_from(row_pitch / u64::from(texel)).unwrap_or(u32::MAX),
364            extent: Extent3d::d2(patch.width, patch.height),
365            layer: patch.layer,
366            mip: 0,
367            image_offset: Offset3d {
368                x: i32::try_from(patch.x).unwrap_or(i32::MAX),
369                y: i32::try_from(patch.y).unwrap_or(i32::MAX),
370                z: 0,
371            },
372        });
373        patched.extend_from_slice(&staged);
374    }
375
376    // The zeroes go only where no patch does, so no texel is written twice: two
377    // unbarriered writes to one subresource in one command buffer are a
378    // synchronisation hazard Vulkan's sync validation reports.
379    let row_texels = u32::try_from(full_pitch / u64::from(texel)).unwrap_or(u32::MAX);
380    let layer_regions: Vec<StagedRegion> = (0..desc.layers)
381        .flat_map(|layer| {
382            let covered: Vec<&TexturePatch<'_>> = desc
383                .patches
384                .iter()
385                .filter(|patch| patch.layer == layer)
386                .collect();
387            uncovered(desc.width, desc.height, &covered)
388                .into_iter()
389                .map(move |(x, y, width, height)| StagedRegion {
390                    buffer_offset: 0,
391                    row_texels,
392                    extent: Extent3d::d2(width, height),
393                    layer,
394                    mip: 0,
395                    image_offset: Offset3d {
396                        x: i32::try_from(x).unwrap_or(i32::MAX),
397                        y: i32::try_from(y).unwrap_or(i32::MAX),
398                        z: 0,
399                    },
400                })
401        })
402        .collect();
403
404    // Device-local, because a clear writes into the buffer on the GPU: a
405    // `crcbl-dx12` upload-heap buffer can never be a copy destination.
406    let zero_label = format!("{label} zero");
407    let zero = device.create_buffer(&BufferDesc {
408        label: Some(&zero_label),
409        size: cleared,
410        usage: BufferUsage::TRANSFER_SRC | BufferUsage::TRANSFER_DST,
411        memory: MemoryLocation::DeviceLocal,
412    })?;
413    let staging = if patched.is_empty() {
414        None
415    } else {
416        match create_staging(device, label, &patched) {
417            Ok(staging) => Some(staging),
418            Err(error) => {
419                device.destroy_buffer(zero);
420                return Err(error);
421            }
422        }
423    };
424    let zero_source = CopySource {
425        buffer: zero,
426        regions: &layer_regions,
427    };
428    let sources: Vec<CopySource<'_>> = core::iter::once(zero_source)
429        .chain(staging.map(|buffer| CopySource {
430            buffer,
431            regions: &patch_regions,
432        }))
433        .collect();
434    let outcome = upload_image(
435        device,
436        queue,
437        &UploadArgs {
438            label,
439            format: desc.format,
440            width: desc.width,
441            height: desc.height,
442            layer_count: desc.layers,
443            mip_levels: 1,
444            view_type: desc.view_type,
445            cleared: Some((zero, cleared)),
446            sources: &sources,
447        },
448    );
449    if let Some(staging) = staging {
450        device.destroy_buffer(staging);
451    }
452    device.destroy_buffer(zero);
453    outcome
454}
455
456/// Whether two patches share a texel.
457fn overlaps(a: &TexturePatch<'_>, b: &TexturePatch<'_>) -> bool {
458    a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height
459}
460
461/// The rectangles of a `width` by `height` layer that no patch in `covered`
462/// touches, as `(x, y, width, height)`: the layer cut into horizontal bands at
463/// every patch's top and bottom edge, and each band's gaps between patches.
464/// The patches must not overlap and must lie inside the layer.
465fn uncovered(width: u32, height: u32, covered: &[&TexturePatch<'_>]) -> Vec<(u32, u32, u32, u32)> {
466    let mut edges: Vec<u32> = covered
467        .iter()
468        .flat_map(|patch| [patch.y, patch.y + patch.height])
469        .chain([0, height])
470        .collect();
471    edges.sort_unstable();
472    edges.dedup();
473    let mut gaps = Vec::new();
474    for band in edges.windows(2) {
475        let (top, bottom) = (band[0], band[1]);
476        let mut spans: Vec<(u32, u32)> = covered
477            .iter()
478            .filter(|patch| patch.y < bottom && top < patch.y + patch.height)
479            .map(|patch| (patch.x, patch.x + patch.width))
480            .collect();
481        spans.sort_unstable();
482        let mut x = 0;
483        for (left, right) in spans.into_iter().chain([(width, width)]) {
484            if left > x {
485                gaps.push((x, top, left - x, bottom - top));
486            }
487            x = x.max(right);
488        }
489    }
490    gaps
491}
492
493/// The word [`clear_buffer`](crcbl_hal::CommandEncoder::clear_buffer) zeroes in
494/// on the backends that fill `u32`s, and so the unit its size is rounded to.
495const CLEAR_WORD_BYTES: u64 = 4;
496
497/// The body the public uploads share: validate, stage every level of every
498/// layer into one buffer, then hand over to [`upload_image`].
499///
500/// `extent` is `(width, height)` as one argument rather than two, which is what
501/// keeps this inside the argument count the public wrappers already sit at.
502fn upload(
503    device: &dyn Device,
504    queue: QueueHandle,
505    label: &str,
506    format: Format,
507    extent: (u32, u32),
508    layers: &[&[&[u8]]],
509    view_type: ImageViewType,
510) -> Result<UploadedTexture, HalError> {
511    let (width, height) = extent;
512    let texel = image_texel(label, format, extent)?;
513    let layer_count = u32::try_from(layers.len()).unwrap_or(u32::MAX);
514    if layer_count == 0 {
515        return Err(HalError::InvalidDescriptor(format!(
516            "{label}: a texture needs at least one layer of pixels"
517        )));
518    }
519    let mip_levels = u32::try_from(layers[0].len()).unwrap_or(u32::MAX);
520    let full_chain = Extent3d::d2(width, height).full_mip_levels(ImageType::D2);
521    if mip_levels == 0 {
522        return Err(HalError::InvalidDescriptor(format!(
523            "{label}: layer 0 has no mip levels; a layer needs at least its own texels"
524        )));
525    }
526    if mip_levels > full_chain {
527        return Err(HalError::InvalidDescriptor(format!(
528            "{label}: {mip_levels} mip levels for a {width}x{height} image, whose full chain \
529             is {full_chain}"
530        )));
531    }
532
533    let alignment = device
534        .caps()
535        .limits
536        .optimal_buffer_copy_offset_alignment
537        .max(1);
538
539    // Every level of every layer is validated and staged in the order the
540    // copies below read them: layer-major, level-minor. Each level's rows are a
541    // multiple of the alignment, so stacking them puts every subresource's own
542    // offset on it too — which is what lets each copy name one buffer offset.
543    let mut padded = Vec::new();
544    let mut regions = Vec::with_capacity(layers.len() * mip_levels as usize);
545    for (layer, chain) in layers.iter().enumerate() {
546        if chain.len() as u32 != mip_levels {
547            return Err(HalError::InvalidDescriptor(format!(
548                "{label}: layer {layer} carries {} mip levels and layer 0 carries {mip_levels}; \
549                 every layer of one image has the same chain",
550                chain.len()
551            )));
552        }
553        for (level, pixels) in chain.iter().enumerate() {
554            let level_width = level_extent(width, level as u32);
555            let level_height = level_extent(height, level as u32);
556            let row_bytes = u64::from(level_width) * u64::from(texel);
557            let expected = row_bytes * u64::from(level_height);
558            if pixels.len() as u64 != expected {
559                return Err(HalError::InvalidDescriptor(format!(
560                    "{label}: layer {layer} level {level} of a {width}x{height} {format:?} image \
561                     is {level_width}x{level_height}, {expected} bytes ({texel} per texel), got {}",
562                    pixels.len()
563                )));
564            }
565            let row_pitch = padded_row_pitch(row_bytes, texel, alignment);
566            let staged =
567                stage_rows(row_bytes, level_height, row_pitch, pixels).ok_or_else(|| {
568                    HalError::InvalidDescriptor(format!(
569                        "{label}: a staging image of {} bytes and more does not fit in this \
570                         host's address space",
571                        padded.len()
572                    ))
573                })?;
574            regions.push(StagedRegion {
575                buffer_offset: padded.len() as u64,
576                // The copy is in texels; the pitch above is in bytes.
577                // `padded_row_pitch` guarantees the division is exact.
578                row_texels: u32::try_from(row_pitch / u64::from(texel)).unwrap_or(u32::MAX),
579                extent: Extent3d::d2(level_width, level_height),
580                layer: layer as u32,
581                mip: level as u32,
582                image_offset: Offset3d { x: 0, y: 0, z: 0 },
583            });
584            padded.extend_from_slice(&staged);
585        }
586    }
587
588    let staging = create_staging(device, label, &padded)?;
589    let outcome = upload_image(
590        device,
591        queue,
592        &UploadArgs {
593            label,
594            format,
595            width,
596            height,
597            layer_count,
598            mip_levels,
599            view_type,
600            cleared: None,
601            sources: &[CopySource {
602                buffer: staging,
603                regions: &regions,
604            }],
605        },
606    );
607    device.destroy_buffer(staging);
608    outcome
609}
610
611/// The bytes one texel of `format` occupies, once `format` and `extent` are
612/// known to describe an image this module can stage.
613///
614/// # Errors
615///
616/// [`HalError::InvalidDescriptor`] for a format with no single colour plane, a
617/// block-compressed format, or a zero extent, each naming `label`.
618fn image_texel(label: &str, format: Format, (width, height): (u32, u32)) -> Result<u32, HalError> {
619    // `texel_size`, not `block_size`: it is the number a `BufferImageCopy` is
620    // sized against, and it is `None` for exactly the formats this path cannot
621    // describe — a combined depth/stencil format, whose two planes need two
622    // copies and neither of which is a `COLOR` aspect.
623    let texel = format.texel_size(ImageAspect::COLOR).ok_or_else(|| {
624        HalError::InvalidDescriptor(format!(
625            "{label}: {format:?} has no single colour plane, so it cannot be uploaded as one \
626             colour-aspect copy"
627        ))
628    })?;
629    // A compressed format's `block_size` covers a 4×4 block, not one texel, so
630    // the per-texel sizing below would be wrong by a factor of four: a BC1 row
631    // is `ceil(width / 4) × 8` bytes, not `width × 8`. No caller uploads one
632    // today; refuse rather than corrupt.
633    if format.is_compressed() {
634        return Err(HalError::InvalidDescriptor(format!(
635            "{label}: {format:?} is block-compressed and this path sizes per texel; \
636             it cannot be uploaded as a colour-aspect copy"
637        )));
638    }
639    if width == 0 || height == 0 {
640        return Err(HalError::InvalidDescriptor(format!(
641            "{label}: texture extent {width}x{height} must be non-zero in both dimensions"
642        )));
643    }
644    Ok(texel)
645}
646
647/// A host-visible `TRANSFER_SRC` buffer labelled `"{label} staging"` holding
648/// `bytes`, destroyed again if the write fails.
649fn create_staging(
650    device: &dyn Device,
651    label: &str,
652    bytes: &[u8],
653) -> Result<crcbl_hal::BufferHandle, HalError> {
654    let staging_label = format!("{label} staging");
655    let staging = device.create_buffer(&BufferDesc {
656        label: Some(&staging_label),
657        size: bytes.len() as u64,
658        usage: BufferUsage::TRANSFER_SRC,
659        memory: MemoryLocation::HostUpload,
660    })?;
661    if let Err(error) = device.write_buffer(staging, 0, bytes) {
662        device.destroy_buffer(staging);
663        return Err(error);
664    }
665    Ok(staging)
666}
667
668/// A tightly packed region of `format` texels staged for an in-frame copy: a
669/// host-visible `TRANSFER_SRC` buffer holding `pixels` with its rows padded to
670/// the device's copy alignment, and the row pitch in texels a
671/// [`BufferImageCopy`] reading it names.
672///
673/// The frame-time half of what [`upload_texture`] does at start-up, without the
674/// image, the barriers or the wait: the caller records the copy inside a
675/// [`RenderGraph`](crate::graph::RenderGraph) copy pass, which is where a
676/// barrier recorded during a frame belongs. [`ui_pass`](crate::ui_pass)'s image
677/// atlas and `crcbl_render`'s sprite atlas are the callers, and each owns the
678/// buffer's lifetime.
679///
680/// # Errors
681///
682/// [`HalError::InvalidDescriptor`] if `format` has no single colour plane, if
683/// the region is empty or if `pixels` is not exactly `width * height` texels;
684/// [`HalError`] from creating or writing the buffer, which is destroyed again
685/// if the write fails.
686pub fn stage_region(
687    device: &dyn Device,
688    label: &str,
689    format: Format,
690    (width, height): (u32, u32),
691    pixels: &[u8],
692) -> Result<(crcbl_hal::BufferHandle, u32), HalError> {
693    let texel = format.texel_size(ImageAspect::COLOR).ok_or_else(|| {
694        HalError::InvalidDescriptor(format!("{label}: {format:?} has no single colour plane"))
695    })?;
696    let row_bytes = u64::from(width) * u64::from(texel);
697    if width == 0 || height == 0 || pixels.len() as u64 != row_bytes * u64::from(height) {
698        return Err(HalError::InvalidDescriptor(format!(
699            "{label}: a {width}x{height} {format:?} region is {} bytes, got {}",
700            row_bytes * u64::from(height),
701            pixels.len()
702        )));
703    }
704    let alignment = device
705        .caps()
706        .limits
707        .optimal_buffer_copy_offset_alignment
708        .max(1);
709    let row_pitch = padded_row_pitch(row_bytes, texel, alignment);
710    let staged = stage_rows(row_bytes, height, row_pitch, pixels).ok_or_else(|| {
711        HalError::InvalidDescriptor(format!(
712            "{label}: the staged region does not fit in this host's address space"
713        ))
714    })?;
715    let buffer = device.create_buffer(&BufferDesc {
716        label: Some(label),
717        size: staged.len() as u64,
718        usage: BufferUsage::TRANSFER_SRC,
719        memory: MemoryLocation::HostUpload,
720    })?;
721    if let Err(error) = device.write_buffer(buffer, 0, &staged) {
722        device.destroy_buffer(buffer);
723        return Err(error);
724    }
725    // `padded_row_pitch` returns a whole number of texels, so this is exact.
726    let row_texels = u32::try_from(row_pitch / u64::from(texel)).unwrap_or(u32::MAX);
727    Ok((buffer, row_texels))
728}
729
730/// The row pitch in **bytes**: at least `row_bytes`, a multiple of `alignment`,
731/// and a whole number of texels.
732///
733/// The last of those is why this is not one `next_multiple_of` call. The copy
734/// expresses its pitch in texels, so a byte pitch that is not divisible by the
735/// texel size cannot be expressed at all. Every real device's alignment is a
736/// power of two at least as large as any uncompressed texel, so in practice the
737/// lcm *is* the alignment — this costs nothing and removes the assumption.
738fn padded_row_pitch(row_bytes: u64, texel: u32, alignment: u64) -> u64 {
739    let texel = u64::from(texel);
740    let step = texel / gcd(texel, alignment) * alignment;
741    row_bytes.next_multiple_of(step)
742}
743
744/// Greatest common divisor, for [`padded_row_pitch`]'s lcm.
745fn gcd(mut a: u64, mut b: u64) -> u64 {
746    while b != 0 {
747        (a, b) = (b, a % b);
748    }
749    a
750}
751
752/// Copies `height` tightly-packed rows of `row_bytes` into a buffer whose rows
753/// are `row_pitch` bytes apart, zero-filling the padding.
754///
755/// `None` only when the padded image does not fit in a `usize`, which on a
756/// 64-bit host means the caller asked for more than the address space.
757fn stage_rows(row_bytes: u64, height: u32, row_pitch: u64, pixels: &[u8]) -> Option<Vec<u8>> {
758    let size = usize::try_from(row_pitch * u64::from(height)).ok()?;
759    let row_bytes = usize::try_from(row_bytes).ok()?;
760    let row_pitch = usize::try_from(row_pitch).ok()?;
761    let mut padded = vec![0u8; size];
762    for row in 0..height as usize {
763        let src = row * row_bytes;
764        let dst = row * row_pitch;
765        padded[dst..dst + row_bytes].copy_from_slice(&pixels[src..src + row_bytes]);
766    }
767    Some(padded)
768}
769
770/// One subresource's place in the staging buffer: what its
771/// [`BufferImageCopy`] names besides the buffer and the image.
772struct StagedRegion {
773    /// Where this subresource's first row starts, on the copy alignment.
774    buffer_offset: u64,
775    /// The padded row pitch, in texels — the unit
776    /// [`BufferImageCopy::buffer_row_length`] documents.
777    row_texels: u32,
778    /// This level's own extent, halved from the image's per level.
779    extent: Extent3d,
780    layer: u32,
781    mip: u32,
782    /// Where in that subresource the rows land: the origin for a whole level,
783    /// the rectangle's corner for a [`TexturePatch`].
784    image_offset: Offset3d,
785}
786
787/// One buffer the copies read, and the regions they read from it.
788struct CopySource<'a> {
789    buffer: crcbl_hal::BufferHandle,
790    regions: &'a [StagedRegion],
791}
792
793/// Everything [`upload_image`] needs that is not the device, the queue or the
794/// bytes — one struct rather than seven positional arguments, which is what
795/// `clippy::too_many_arguments` is objecting to and also what makes the two
796/// `u32`s impossible to swap at the call site.
797struct UploadArgs<'a> {
798    label: &'a str,
799    format: Format,
800    width: u32,
801    height: u32,
802    /// Array layers in the image.
803    layer_count: u32,
804    /// Mip levels in the image, and in every layer's chain.
805    mip_levels: u32,
806    /// `D2` for one layer, `D2Array` for a page. Not derived from
807    /// `layer_count`: a one-layer array view is a legitimate thing to want, and
808    /// the shader's declaration is what decides which it is.
809    view_type: ImageViewType,
810    /// A buffer the copies zero first, and how many bytes of it, for
811    /// [`upload_cleared_texture`].
812    cleared: Option<(crcbl_hal::BufferHandle, u64)>,
813    /// Every copy, in the order they are recorded.
814    sources: &'a [CopySource<'a>],
815}
816
817/// The half of [`upload_texture`] that owns the image and the view, so the
818/// caller can destroy the staging buffer on every path out of it.
819fn upload_image(
820    device: &dyn Device,
821    queue: QueueHandle,
822    args: &UploadArgs<'_>,
823) -> Result<UploadedTexture, HalError> {
824    let image = device.create_image(&ImageDesc {
825        label: Some(args.label),
826        image_type: ImageType::D2,
827        format: args.format,
828        extent: Extent3d {
829            width: args.width,
830            height: args.height,
831            // A `D2` image's `depth_or_layers` is its array length, which the
832            // seam says on the field itself.
833            depth_or_layers: args.layer_count,
834        },
835        mip_levels: args.mip_levels,
836        samples: 1,
837        // `TRANSFER_SRC` as well as the copy's `TRANSFER_DST`, so a test or a
838        // capture can copy a level back out — `tests/forward_e2e/page.rs` reads
839        // the page's chain that way. Free on every backend: a sampled image
840        // that is also a copy source costs no layout, no memory and no
841        // decompression it would not already pay.
842        usage: ImageUsage::TRANSFER_SRC | ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED,
843    })?;
844
845    let view = match device.create_image_view(&ImageViewDesc {
846        label: Some(args.label),
847        image,
848        view_type: args.view_type,
849        format: args.format,
850        range: color_range(args.mip_levels, args.layer_count),
851    }) {
852        Ok(view) => view,
853        Err(error) => {
854            device.destroy_image(image);
855            return Err(error);
856        }
857    };
858
859    let uploaded = UploadedTexture { image, view };
860    match record_upload(device, queue, args, image) {
861        Ok(()) => Ok(uploaded),
862        Err(error) => {
863            uploaded.destroy(device);
864            Err(error)
865        }
866    }
867}
868
869/// The whole of a colour image `mips` levels deep and `layers` layers deep.
870const fn color_range(mips: u32, layers: u32) -> ImageSubresourceRange {
871    ImageSubresourceRange {
872        aspect: ImageAspect::COLOR,
873        base_mip: 0,
874        mip_count: mips,
875        base_layer: 0,
876        layer_count: layers,
877    }
878}
879
880/// Records, submits and drains the staging copy, leaving the image in
881/// [`ResourceState::ShaderRead`].
882fn record_upload(
883    device: &dyn Device,
884    queue: QueueHandle,
885    args: &UploadArgs<'_>,
886    image: ImageHandle,
887) -> Result<(), HalError> {
888    let encoder_label = format!("{} upload", args.label);
889    let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
890        label: Some(&encoder_label),
891        queue,
892    });
893
894    let range = color_range(args.mip_levels, args.layer_count);
895    // Undefined → TransferDst: the image has never held anything, so its old
896    // contents are explicitly discarded rather than transitioned. The range
897    // covers every level of every layer, so one barrier serves all the copies
898    // below.
899    encoder.pipeline_barrier(&crcbl_hal::Barriers {
900        images: &[crcbl_hal::ImageBarrier::new(
901            image,
902            range,
903            ResourceState::Undefined,
904            ResourceState::TransferDst,
905        )],
906        ..Default::default()
907    });
908
909    // Outside any pass, and before the copies that read it: a clear is recorded
910    // into the same command buffer, so it runs first on every backend. The
911    // buffer is then moved to a copy source explicitly, because the clear left
912    // it a copy destination: D3D12 promotes a buffer implicitly only out of
913    // `COMMON`, which a fresh one is in and this one no longer is.
914    if let Some((buffer, size)) = args.cleared {
915        encoder.clear_buffer(buffer, 0, size);
916        encoder.pipeline_barrier(&crcbl_hal::Barriers {
917            buffers: &[crcbl_hal::BufferBarrier::new(
918                buffer,
919                ResourceState::TransferDst,
920                ResourceState::TransferSrc,
921            )],
922            ..Default::default()
923        });
924    }
925
926    // One copy per subresource. A region's `image_extent` is a 2D extent
927    // whatever the image is — `crcbl-dx12` refuses anything else by name,
928    // because `CopyTextureRegion` addresses one subresource — so the layer and
929    // the level are named by `base_layer` and `mip`, and the buffer offset says
930    // where that subresource's rows start.
931    for (source, region) in args
932        .sources
933        .iter()
934        .flat_map(|source| source.regions.iter().map(move |region| (source, region)))
935    {
936        encoder.copy_buffer_to_image(&BufferImageCopy {
937            buffer: source.buffer,
938            buffer_offset: region.buffer_offset,
939            buffer_row_length: region.row_texels,
940            buffer_image_height: region.extent.height,
941            image,
942            image_subresource: ImageSubresourceLayers {
943                aspect: ImageAspect::COLOR,
944                mip: region.mip,
945                base_layer: region.layer,
946                layer_count: 1,
947            },
948            image_offset: region.image_offset,
949            image_extent: region.extent,
950        });
951    }
952
953    encoder.pipeline_barrier(&crcbl_hal::Barriers {
954        images: &[crcbl_hal::ImageBarrier::new(
955            image,
956            range,
957            ResourceState::TransferDst,
958            ResourceState::ShaderRead,
959        )],
960        ..Default::default()
961    });
962
963    let commands = encoder.finish()?;
964    let submitted = device
965        .submit(queue, &SubmitInfo::new(&[commands]))
966        .and_then(|()| device.wait_idle());
967    device.destroy_command_buffer(commands);
968    submitted
969}
970
971// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
972#[cfg(all(test, not(target_arch = "wasm32")))]
973mod tests {
974    use super::*;
975    use crcbl_hal::null::{Command, Event, NullInstance, Recorder};
976    use crcbl_hal::{DeviceDesc, Features, Instance, QueueKind};
977
978    /// Tier B, because its `optimal_buffer_copy_offset_alignment` is 256 —
979    /// WebGPU's — and Tier A's is 4, which an `Rgba8Unorm` row satisfies for
980    /// free. Padding is only exercised on the tier that asks for it.
981    fn open_tier_b(recorder: &Recorder) -> (Box<dyn Device>, QueueHandle) {
982        let instance = NullInstance::portable().with_recorder(recorder.clone());
983        let adapter = instance.adapters().remove(0);
984        let device = instance
985            .create_device(&DeviceDesc {
986                label: None,
987                adapter: adapter.id,
988                required_features: Features::COMPUTE,
989                optional_features: Features::empty(),
990                compatible_surface: None,
991            })
992            .expect("the tier B null adapter opens");
993        let queue = device.queue(QueueKind::Graphics).expect("always present");
994        (device, queue)
995    }
996
997    fn open_tier_a(recorder: &Recorder) -> (Box<dyn Device>, QueueHandle) {
998        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
999        let adapter = instance.adapters().remove(0);
1000        let device = instance
1001            .create_device(&DeviceDesc {
1002                label: None,
1003                adapter: adapter.id,
1004                required_features: Features::GPU_DRIVEN,
1005                optional_features: Features::empty(),
1006                compatible_surface: None,
1007            })
1008            .expect("the null backend always opens");
1009        let queue = device.queue(QueueKind::Graphics).expect("always present");
1010        (device, queue)
1011    }
1012
1013    fn the_copies(recorder: &Recorder) -> Vec<BufferImageCopy> {
1014        recorder
1015            .commands()
1016            .into_iter()
1017            .filter_map(|command| match command {
1018                Command::CopyBufferToImage(copy) => Some(copy),
1019                _ => None,
1020            })
1021            .collect()
1022    }
1023
1024    fn the_copy(recorder: &Recorder) -> BufferImageCopy {
1025        let copies = the_copies(recorder);
1026        assert_eq!(
1027            copies.len(),
1028            1,
1029            "a single-layer upload records exactly one buffer-to-image copy"
1030        );
1031        copies[0]
1032    }
1033
1034    fn bytes_written(recorder: &Recorder) -> usize {
1035        recorder
1036            .events()
1037            .into_iter()
1038            .find_map(|event| match event {
1039                Event::BufferWritten { len, .. } => Some(len),
1040                _ => None,
1041            })
1042            .expect("an upload writes its staging buffer once")
1043    }
1044
1045    /// A 100-texel RGBA row: 400 bytes, which Tier B's 256-byte alignment pads
1046    /// to 512. Every number here is different from the one the old
1047    /// texels-as-bytes arithmetic would produce — that pitched 100 up to 256 —
1048    /// so this is what fails if a pitch is ever computed from `width` rather
1049    /// than `width * texel_size` again.
1050    const WIDTH: u32 = 100;
1051    const HEIGHT: u32 = 3;
1052    const ROW_BYTES: usize = 400;
1053    const PITCH: usize = 512;
1054
1055    fn ramp(len: usize) -> Vec<u8> {
1056        // Coprime with 256, so no two bytes 256 apart are equal and a row
1057        // written at the wrong offset cannot compare equal by accident.
1058        (0..len).map(|index| (index % 251) as u8).collect()
1059    }
1060
1061    /// The row pitch is in **bytes**, and each source row lands at its padded
1062    /// byte offset with zeroes after it.
1063    #[test]
1064    fn each_source_row_lands_at_its_padded_byte_offset() {
1065        let texel = Format::Rgba8Unorm
1066            .texel_size(ImageAspect::COLOR)
1067            .expect("rgba8 is a colour format");
1068        assert_eq!(texel, 4);
1069
1070        let row_bytes = u64::from(WIDTH) * u64::from(texel);
1071        assert_eq!(row_bytes as usize, ROW_BYTES);
1072        let pitch = padded_row_pitch(row_bytes, texel, 256);
1073        assert_eq!(
1074            pitch as usize, PITCH,
1075            "400 bytes padded up to the 256-byte alignment is 512, not 256"
1076        );
1077
1078        let pixels = ramp(ROW_BYTES * HEIGHT as usize);
1079        let padded = stage_rows(row_bytes, HEIGHT, pitch, &pixels).expect("fits");
1080        assert_eq!(padded.len(), PITCH * HEIGHT as usize);
1081        for row in 0..HEIGHT as usize {
1082            let start = row * PITCH;
1083            assert_eq!(
1084                &padded[start..start + ROW_BYTES],
1085                &pixels[row * ROW_BYTES..(row + 1) * ROW_BYTES],
1086                "row {row} must sit at byte {start}"
1087            );
1088            assert!(
1089                padded[start + ROW_BYTES..start + PITCH]
1090                    .iter()
1091                    .all(|&byte| byte == 0),
1092                "row {row}'s padding must be zero, not the next row"
1093            );
1094        }
1095    }
1096
1097    /// And the copy is told that pitch in *texels*, which is the unit
1098    /// [`BufferImageCopy::buffer_row_length`] documents.
1099    #[test]
1100    fn an_rgba_upload_records_its_pitch_in_texels() {
1101        let recorder = Recorder::new();
1102        let (device, queue) = open_tier_b(&recorder);
1103        assert_eq!(
1104            device.caps().limits.optimal_buffer_copy_offset_alignment,
1105            256,
1106            "the padding this test exercises only exists on the tier that asks for it"
1107        );
1108        let pixels = ramp(ROW_BYTES * HEIGHT as usize);
1109
1110        let texture = upload_texture(
1111            device.as_ref(),
1112            queue,
1113            "sprite atlas",
1114            Format::Rgba8Unorm,
1115            WIDTH,
1116            HEIGHT,
1117            &pixels,
1118        )
1119        .expect("the null backend accepts this");
1120
1121        assert_eq!(
1122            bytes_written(&recorder),
1123            PITCH * HEIGHT as usize,
1124            "the staging write is the padded image, not the packed one"
1125        );
1126        let copy = the_copy(&recorder);
1127        assert_eq!(
1128            copy.buffer_row_length, 128,
1129            "512 bytes of pitch is 128 rgba texels, not 512"
1130        );
1131        assert_eq!(copy.buffer_image_height, HEIGHT);
1132        assert_eq!(copy.image_extent, Extent3d::d2(WIDTH, HEIGHT));
1133        assert_eq!(copy.image_offset, Offset3d { x: 0, y: 0, z: 0 });
1134
1135        texture.destroy(device.as_ref());
1136        recorder.assert_valid();
1137    }
1138
1139    /// A device whose alignment an `Rgba8Unorm` row already satisfies pads
1140    /// nothing, and the copy's pitch is then simply the width.
1141    #[test]
1142    fn an_aligned_row_is_not_padded() {
1143        let recorder = Recorder::new();
1144        let (device, queue) = open_tier_a(&recorder);
1145        assert_eq!(device.caps().limits.optimal_buffer_copy_offset_alignment, 4);
1146        let pixels = vec![0u8; 5 * 3 * 4];
1147        let texture = upload_texture(
1148            device.as_ref(),
1149            queue,
1150            "tight",
1151            Format::Rgba8Unorm,
1152            5,
1153            3,
1154            &pixels,
1155        )
1156        .expect("accepted");
1157        assert_eq!(bytes_written(&recorder), 5 * 3 * 4);
1158        assert_eq!(the_copy(&recorder).buffer_row_length, 5);
1159        texture.destroy(device.as_ref());
1160        recorder.assert_valid();
1161    }
1162
1163    /// The pitch satisfies the alignment *and* stays a whole number of texels,
1164    /// including when the two do not divide each other — a byte pitch the copy
1165    /// cannot express in texels is not a pitch.
1166    #[test]
1167    fn a_row_pitch_is_aligned_and_a_whole_number_of_texels() {
1168        // The ordinary cases: alignment already a multiple of the texel.
1169        assert_eq!(padded_row_pitch(20, 4, 256), 256);
1170        assert_eq!(padded_row_pitch(20, 4, 4), 20);
1171        assert_eq!(padded_row_pitch(5, 1, 4), 8);
1172        assert_eq!(padded_row_pitch(1024, 4, 256), 1024);
1173        // The awkward one: 6-byte alignment, 4-byte texel. 4 is not enough (it
1174        // is not a multiple of 6) and 6 is not enough (it is not a whole texel);
1175        // 12 is the first that is both.
1176        let pitch = padded_row_pitch(4, 4, 6);
1177        assert_eq!(pitch, 12);
1178        assert_eq!(pitch % 6, 0, "must satisfy the alignment");
1179        assert_eq!(pitch % 4, 0, "must be a whole number of texels");
1180    }
1181
1182    /// **A page is one image whose layers each get their own copy**, and each
1183    /// copy reads the layer's own slice of the staging buffer.
1184    ///
1185    /// The offsets are what this is for. Every layer's rows are padded, so a
1186    /// second layer read at `width * height * texel` — the *unpadded* size —
1187    /// would take the tail of the first layer plus part of the second and put
1188    /// a plausible smear in the page. Tier B is used because its 256-byte
1189    /// alignment is what makes the padded and unpadded strides differ.
1190    #[test]
1191    fn a_page_copies_each_layer_from_its_own_padded_offset() {
1192        let recorder = Recorder::new();
1193        let (device, queue) = open_tier_b(&recorder);
1194        let layers: Vec<Vec<u8>> = (0..3).map(|_| ramp(ROW_BYTES * HEIGHT as usize)).collect();
1195        let refs: Vec<&[u8]> = layers.iter().map(Vec::as_slice).collect();
1196
1197        let page = upload_texture_layers(
1198            device.as_ref(),
1199            queue,
1200            "material page",
1201            Format::Rgba8Unorm,
1202            WIDTH,
1203            HEIGHT,
1204            &refs,
1205        )
1206        .expect("the null backend accepts this");
1207
1208        let layer_bytes = PITCH * HEIGHT as usize;
1209        assert_eq!(
1210            bytes_written(&recorder),
1211            layer_bytes * layers.len(),
1212            "the staging write is every layer, padded"
1213        );
1214        let copies = the_copies(&recorder);
1215        assert_eq!(
1216            copies.len(),
1217            layers.len(),
1218            "one copy per layer, because a region's extent is 2D on every backend"
1219        );
1220        for (layer, copy) in copies.iter().enumerate() {
1221            assert_eq!(
1222                copy.buffer_offset,
1223                (layer * layer_bytes) as u64,
1224                "layer {layer} must read from its own slice of the staging buffer"
1225            );
1226            assert_eq!(
1227                copy.image_subresource.base_layer, layer as u32,
1228                "layer {layer} must be written to layer {layer} of the image"
1229            );
1230            assert_eq!(copy.image_subresource.layer_count, 1);
1231            assert_eq!(copy.buffer_row_length, 128);
1232            assert_eq!(
1233                copy.image_extent,
1234                Extent3d::d2(WIDTH, HEIGHT),
1235                "a copy region's extent stays 2D"
1236            );
1237        }
1238
1239        page.destroy(device.as_ref());
1240        recorder.assert_valid();
1241    }
1242
1243    /// A page with no layers is refused here, by name.
1244    ///
1245    /// Without the guard it reaches the device as an image whose
1246    /// `depth_or_layers` is zero, whose complaint is about an *extent* — a
1247    /// different object and a message that does not say what the caller did.
1248    #[test]
1249    fn a_page_with_no_layers_is_rejected() {
1250        let recorder = Recorder::new();
1251        let (device, queue) = open_tier_a(&recorder);
1252        let error = upload_texture_layers(
1253            device.as_ref(),
1254            queue,
1255            "empty page",
1256            Format::Rgba8Unorm,
1257            4,
1258            4,
1259            &[],
1260        )
1261        .expect_err("a page needs a layer");
1262        assert!(
1263            error.to_string().contains("at least one layer"),
1264            "got: {error}"
1265        );
1266        assert_eq!(recorder.total_live_objects(), 0);
1267    }
1268
1269    /// A short or long slice is an error naming both numbers, not a
1270    /// `copy_from_slice` panic naming neither — and nothing is created before
1271    /// it is noticed.
1272    #[test]
1273    fn a_wrong_sized_pixel_slice_is_rejected() {
1274        let recorder = Recorder::new();
1275        let (device, queue) = open_tier_a(&recorder);
1276        let before = recorder.total_live_objects();
1277
1278        let short = vec![0u8; 5 * 3 * 4 - 1];
1279        let error = upload_texture(
1280            device.as_ref(),
1281            queue,
1282            "short",
1283            Format::Rgba8Unorm,
1284            5,
1285            3,
1286            &short,
1287        )
1288        .expect_err("a 59-byte slice is not a 5x3 rgba image");
1289        let message = error.to_string();
1290        assert!(
1291            message.contains("60") && message.contains("59"),
1292            "the error must name both sizes, got: {message}"
1293        );
1294
1295        let long = vec![0u8; 5 * 3 * 4 + 1];
1296        upload_texture(
1297            device.as_ref(),
1298            queue,
1299            "long",
1300            Format::Rgba8Unorm,
1301            5,
1302            3,
1303            &long,
1304        )
1305        .expect_err("a 61-byte slice is not one either");
1306
1307        assert_eq!(
1308            recorder.total_live_objects(),
1309            before,
1310            "a rejected upload creates nothing"
1311        );
1312    }
1313
1314    /// A zero extent is refused here rather than reaching the device as a
1315    /// zero-sized staging buffer, which is a different error about a different
1316    /// object.
1317    #[test]
1318    fn a_zero_extent_is_rejected() {
1319        let recorder = Recorder::new();
1320        let (device, queue) = open_tier_a(&recorder);
1321        for (width, height) in [(0u32, 4u32), (4, 0)] {
1322            let error = upload_texture(
1323                device.as_ref(),
1324                queue,
1325                "empty",
1326                Format::Rgba8Unorm,
1327                width,
1328                height,
1329                &[],
1330            )
1331            .expect_err("a zero extent is not a texture");
1332            // "texture extent", not merely "non-zero": without the guard above
1333            // this reaches the device as a zero-sized *buffer*, whose own error
1334            // also says "non-zero" and would have made this test pass while
1335            // naming the wrong object.
1336            assert!(
1337                error.to_string().contains("texture extent"),
1338                "got: {error}, which is not the extent complaint"
1339            );
1340        }
1341        assert_eq!(recorder.total_live_objects(), 0);
1342    }
1343
1344    /// A combined depth/stencil format has two planes and no colour aspect, so
1345    /// there is no single `texel_size` to pitch against. Refused by name rather
1346    /// than silently pitched against `block_size`, which would be 8.
1347    #[test]
1348    fn a_depth_stencil_format_is_rejected() {
1349        let recorder = Recorder::new();
1350        let (device, queue) = open_tier_a(&recorder);
1351        let error = upload_texture(
1352            device.as_ref(),
1353            queue,
1354            "depth",
1355            Format::D32FloatS8Uint,
1356            4,
1357            4,
1358            &[0u8; 128],
1359        )
1360        .expect_err("a depth/stencil upload needs one copy per plane");
1361        assert!(error.to_string().contains("colour plane"), "got: {error}");
1362        assert_eq!(recorder.total_live_objects(), 0);
1363    }
1364
1365    /// A compressed format's `block_size` covers a 4×4 block, not one texel, so
1366    /// the per-texel sizing here would be wrong by a factor of four — and there
1367    /// is no caller that needs one. Refused by name rather than silently
1368    /// pitched against the block size, before any device call.
1369    #[test]
1370    fn a_compressed_format_is_rejected() {
1371        let recorder = Recorder::new();
1372        let (device, queue) = open_tier_a(&recorder);
1373        // 8x8 BC1 is 2x2 blocks of 8 bytes: the *correct* compressed size, so a
1374        // regression that accepted compressed uploads would pass the size check
1375        // and fail only here.
1376        let error = upload_texture(
1377            device.as_ref(),
1378            queue,
1379            "compressed",
1380            Format::Bc1RgbaUnorm,
1381            8,
1382            8,
1383            &[0u8; 2 * 2 * 8],
1384        )
1385        .expect_err("a BC1 upload is sized per block, not per texel");
1386        assert!(
1387            error.to_string().contains("block-compressed"),
1388            "got: {error}"
1389        );
1390        assert_eq!(recorder.total_live_objects(), 0);
1391    }
1392
1393    /// A failure after the staging buffer exists releases it. `create_image`
1394    /// is what fails: Tier A's `max_image_2d` is 16384, and a 16385x1 R8 image
1395    /// is one byte per texel, so the staging allocation this must clean up is
1396    /// 16 KiB rather than something that would fail for its own reasons first.
1397    #[test]
1398    fn a_failed_upload_leaks_nothing() {
1399        let recorder = Recorder::new();
1400        let (device, queue) = open_tier_a(&recorder);
1401        let limit = device.caps().limits.max_image_2d;
1402        assert_eq!(limit, 16384);
1403        let before = recorder.total_live_objects();
1404
1405        let width = limit + 1;
1406        let pixels = vec![0u8; width as usize];
1407        let error = upload_texture(
1408            device.as_ref(),
1409            queue,
1410            "too wide",
1411            Format::R8Unorm,
1412            width,
1413            1,
1414            &pixels,
1415        )
1416        .expect_err("the device refuses an image past max_image_2d");
1417        assert!(
1418            error.to_string().contains("max_image_2d"),
1419            "the failure must be the image, not something earlier: {error}"
1420        );
1421
1422        assert_eq!(
1423            recorder.total_live_objects(),
1424            before,
1425            "the staging buffer created before the failure must be destroyed"
1426        );
1427        assert!(
1428            recorder
1429                .events()
1430                .iter()
1431                .any(|event| matches!(event, Event::BufferWritten { .. })),
1432            "the test is only meaningful if the staging buffer really was created \
1433             and written before the failure"
1434        );
1435    }
1436
1437    /// **A chain is one copy per level of every layer**, each into its own mip
1438    /// and each from its own padded offset — level-minor, so a layer's whole
1439    /// chain sits together in the staging buffer.
1440    ///
1441    /// Tier B again, for the padded-versus-unpadded reason above, and a width
1442    /// that halves onto rows of three different pitches: 100 texels pad to 512
1443    /// bytes, 50 to 256, 25 to 256. A level offset computed from level 0's
1444    /// pitch would land the second level's rows inside the first's tail.
1445    #[test]
1446    fn a_chain_copies_each_level_into_its_own_mip_from_its_own_offset() {
1447        let recorder = Recorder::new();
1448        let (device, queue) = open_tier_b(&recorder);
1449        // Three of the seven levels a 100-wide image has: a partial chain is
1450        // legal, and each level is its own extent's worth of texels.
1451        let level_extents = [(WIDTH, HEIGHT), (50, 1), (25, 1)];
1452        let chains: Vec<Vec<Vec<u8>>> = (0..2)
1453            .map(|_| {
1454                level_extents
1455                    .iter()
1456                    .map(|&(width, height)| ramp((width * height * 4) as usize))
1457                    .collect()
1458            })
1459            .collect();
1460        let levels: Vec<Vec<&[u8]>> = chains
1461            .iter()
1462            .map(|chain| chain.iter().map(Vec::as_slice).collect())
1463            .collect();
1464        let layers: Vec<&[&[u8]]> = levels.iter().map(Vec::as_slice).collect();
1465
1466        let page = upload_texture_mip_layers(
1467            device.as_ref(),
1468            queue,
1469            "mipped page",
1470            Format::Rgba8Unorm,
1471            WIDTH,
1472            HEIGHT,
1473            &layers,
1474        )
1475        .expect("the null backend accepts a partial chain");
1476
1477        let level_bytes = [PITCH * HEIGHT as usize, 256, 256];
1478        let layer_bytes: usize = level_bytes.iter().sum();
1479        assert_eq!(
1480            bytes_written(&recorder),
1481            layer_bytes * chains.len(),
1482            "the staging write is every level of every layer, each padded to its own pitch"
1483        );
1484        let copies = the_copies(&recorder);
1485        assert_eq!(copies.len(), chains.len() * level_extents.len());
1486        let mut expected_offset = 0u64;
1487        for (index, copy) in copies.iter().enumerate() {
1488            let layer = index / level_extents.len();
1489            let level = index % level_extents.len();
1490            let (width, height) = level_extents[level];
1491            assert_eq!(
1492                (
1493                    copy.image_subresource.base_layer,
1494                    copy.image_subresource.mip
1495                ),
1496                (layer as u32, level as u32),
1497                "copy {index} is layer {layer}'s level {level}"
1498            );
1499            assert_eq!(copy.image_subresource.layer_count, 1);
1500            assert_eq!(
1501                copy.buffer_offset, expected_offset,
1502                "layer {layer} level {level} reads from its own slice of the staging buffer"
1503            );
1504            assert_eq!(
1505                copy.image_extent,
1506                Extent3d::d2(width, height),
1507                "level {level} is copied at its own extent"
1508            );
1509            assert_eq!(copy.buffer_image_height, height);
1510            assert_eq!(
1511                copy.buffer_row_length as usize * 4,
1512                level_bytes[level] / height as usize,
1513                "level {level}'s pitch is its own row padded, in texels"
1514            );
1515            expected_offset += level_bytes[level] as u64;
1516        }
1517
1518        page.destroy(device.as_ref());
1519        recorder.assert_valid();
1520    }
1521
1522    /// The single-level form is the chain form with one level, so the image it
1523    /// creates has one mip and the copies name it — a `mip_levels` that
1524    /// followed the chain length would otherwise be off by one somewhere.
1525    #[test]
1526    fn a_single_level_page_is_a_chain_of_one() {
1527        let recorder = Recorder::new();
1528        let (device, queue) = open_tier_a(&recorder);
1529        let pixels = vec![0u8; 4 * 4 * 4];
1530        let page = upload_texture_layers(
1531            device.as_ref(),
1532            queue,
1533            "flat page",
1534            Format::Rgba8Unorm,
1535            4,
1536            4,
1537            &[&pixels],
1538        )
1539        .expect("accepted");
1540        let copy = the_copy(&recorder);
1541        assert_eq!(copy.image_subresource.mip, 0);
1542        page.destroy(device.as_ref());
1543        recorder.assert_valid();
1544    }
1545
1546    /// A chain that is ragged, too long, empty, or has a level of the wrong
1547    /// size is refused by name before anything is created.
1548    #[test]
1549    fn a_malformed_chain_is_rejected_naming_the_layer_and_the_level() {
1550        let recorder = Recorder::new();
1551        let (device, queue) = open_tier_a(&recorder);
1552        let before = recorder.total_live_objects();
1553        let level0 = vec![0u8; 4 * 4 * 4];
1554        let level1 = vec![0u8; 2 * 2 * 4];
1555        let level2 = vec![0u8; 4];
1556        let upload = |layers: &[&[&[u8]]]| {
1557            upload_texture_mip_layers(
1558                device.as_ref(),
1559                queue,
1560                "chain",
1561                Format::Rgba8Unorm,
1562                4,
1563                4,
1564                layers,
1565            )
1566            .expect_err("a malformed chain is not a page")
1567            .to_string()
1568        };
1569
1570        let ragged = upload(&[&[&level0, &level1], &[&level0]]);
1571        assert!(
1572            ragged.contains("layer 1 carries 1 mip levels and layer 0 carries 2"),
1573            "got: {ragged}"
1574        );
1575        let long = upload(&[&[&level0, &level1, &level2, &level2]]);
1576        assert!(
1577            long.contains("4 mip levels") && long.contains("full chain is 3"),
1578            "got: {long}"
1579        );
1580        let empty = upload(&[&[]]);
1581        assert!(empty.contains("no mip levels"), "got: {empty}");
1582        let wrong = upload(&[&[&level0, &level0]]);
1583        assert!(
1584            wrong.contains("layer 0 level 1") && wrong.contains("is 2x2, 16 bytes"),
1585            "got: {wrong}"
1586        );
1587
1588        assert_eq!(
1589            recorder.total_live_objects(),
1590            before,
1591            "a rejected chain creates nothing"
1592        );
1593    }
1594
1595    /// **A cleared page is zeroed on the GPU and copied into every layer, and
1596    /// only its patches cross from the host** — each into its own layer at its
1597    /// own corner, after the zeroes it overwrites.
1598    ///
1599    /// Tier B, so the page and the patch pitch to different strides: a 100-texel
1600    /// RGBA row pads to 512 bytes, the 5-texel patch row to 256.
1601    #[test]
1602    fn a_cleared_page_zeroes_every_layer_and_stages_only_its_patches() {
1603        let recorder = Recorder::new();
1604        let (device, queue) = open_tier_b(&recorder);
1605        let before = recorder.total_live_objects();
1606        let pixels = ramp(5 * 2 * 4);
1607
1608        let page = upload_cleared_texture(
1609            device.as_ref(),
1610            queue,
1611            &ClearedTextureDesc {
1612                label: "cleared page",
1613                format: Format::Rgba8Unorm,
1614                width: WIDTH,
1615                height: HEIGHT,
1616                layers: 3,
1617                view_type: ImageViewType::D2Array,
1618                patches: &[TexturePatch {
1619                    layer: 2,
1620                    x: 7,
1621                    y: 1,
1622                    width: 5,
1623                    height: 2,
1624                    pixels: &pixels,
1625                }],
1626            },
1627        )
1628        .expect("the null backend accepts this");
1629
1630        let commands = recorder.commands();
1631        let clears: Vec<(crcbl_hal::BufferHandle, u64, u64)> = commands
1632            .iter()
1633            .filter_map(|command| match command {
1634                Command::ClearBuffer {
1635                    buffer,
1636                    offset,
1637                    size,
1638                } => Some((*buffer, *offset, *size)),
1639                _ => None,
1640            })
1641            .collect();
1642        let [(zero, 0, size)] = clears[..] else {
1643            panic!("expected one clear from the start of one buffer, got {clears:?}");
1644        };
1645        assert_eq!(size as usize, PITCH * HEIGHT as usize, "one padded layer");
1646        let first_copy = commands
1647            .iter()
1648            .position(|command| matches!(command, Command::CopyBufferToImage(_)));
1649        let clear_at = commands
1650            .iter()
1651            .position(|command| matches!(command, Command::ClearBuffer { .. }));
1652        assert!(
1653            clear_at < first_copy,
1654            "the clear must be recorded before the copies that read it"
1655        );
1656
1657        let copies = the_copies(&recorder);
1658        // **Every texel of every layer is written exactly once**: by a zero
1659        // copy, or by the patch — never both, which sync validation reports.
1660        let mut writes = vec![0u8; 3 * (WIDTH * HEIGHT) as usize];
1661        for copy in &copies {
1662            let Offset3d { x, y, .. } = copy.image_offset;
1663            let layer = copy.image_subresource.base_layer;
1664            for row in 0..copy.image_extent.height {
1665                for column in 0..copy.image_extent.width {
1666                    let texel = (layer * WIDTH * HEIGHT
1667                        + (y as u32 + row) * WIDTH
1668                        + (x as u32 + column)) as usize;
1669                    writes[texel] += 1;
1670                }
1671            }
1672            if copy.buffer == zero {
1673                assert_eq!(copy.buffer_offset, 0);
1674                assert_eq!(copy.buffer_row_length, 128);
1675            }
1676        }
1677        assert!(
1678            writes.iter().all(|&count| count == 1),
1679            "a texel was written {} times, or not at all: {copies:?}",
1680            writes
1681                .iter()
1682                .copied()
1683                .find(|&count| count != 1)
1684                .unwrap_or(1)
1685        );
1686        let zeroes: Vec<_> = copies.iter().filter(|copy| copy.buffer == zero).collect();
1687        assert_eq!(
1688            zeroes.len(),
1689            2 + 3,
1690            "one copy for each unpatched layer, and the patched layer as the row \
1691             above its patch and the two spans beside it: {copies:?}"
1692        );
1693        let [patch] = copies
1694            .iter()
1695            .filter(|copy| copy.buffer != zero)
1696            .collect::<Vec<_>>()[..]
1697        else {
1698            panic!("expected one staged patch copy: {copies:?}");
1699        };
1700        let patch = *patch;
1701        assert_ne!(patch.buffer, zero, "a patch is staged, not cleared");
1702        assert_eq!(patch.buffer_offset, 0);
1703        assert_eq!(
1704            patch.buffer_row_length, 64,
1705            "256 bytes of pitch is 64 texels"
1706        );
1707        assert_eq!(patch.image_subresource.base_layer, 2);
1708        assert_eq!(patch.image_extent, Extent3d::d2(5, 2));
1709        assert_eq!(patch.image_offset, Offset3d { x: 7, y: 1, z: 0 });
1710
1711        let writes: Vec<(crcbl_hal::BufferHandle, usize)> = recorder
1712            .events()
1713            .into_iter()
1714            .filter_map(|event| match event {
1715                Event::BufferWritten { buffer, len, .. } => Some((buffer, len)),
1716                _ => None,
1717            })
1718            .collect();
1719        assert_eq!(
1720            writes,
1721            [(patch.buffer, 256 * 2)],
1722            "the host writes the padded patch and nothing of the page"
1723        );
1724
1725        page.destroy(device.as_ref());
1726        assert_eq!(
1727            recorder.total_live_objects(),
1728            before,
1729            "both buffers are released once the copies are submitted"
1730        );
1731        recorder.assert_valid();
1732    }
1733
1734    /// A page with nothing patched creates no staging buffer and writes nothing.
1735    #[test]
1736    fn a_cleared_page_with_no_patches_writes_nothing() {
1737        let recorder = Recorder::new();
1738        let (device, queue) = open_tier_a(&recorder);
1739        let page = upload_cleared_texture(
1740            device.as_ref(),
1741            queue,
1742            &ClearedTextureDesc {
1743                label: "empty page",
1744                format: Format::R8Unorm,
1745                width: 16,
1746                height: 16,
1747                layers: 2,
1748                view_type: ImageViewType::D2Array,
1749                patches: &[],
1750            },
1751        )
1752        .expect("accepted");
1753        assert!(
1754            !recorder
1755                .events()
1756                .iter()
1757                .any(|event| matches!(event, Event::BufferWritten { .. })),
1758            "an unpatched page is all zeroes, and zeroes are the GPU's to write"
1759        );
1760        assert_eq!(the_copies(&recorder).len(), 2, "one copy a layer");
1761        page.destroy(device.as_ref());
1762        recorder.assert_valid();
1763    }
1764
1765    /// A patch off its layer, outside the extent, empty, or not its own size is
1766    /// refused naming the patch — and so is a page with no layers — before
1767    /// anything is created.
1768    #[test]
1769    fn a_malformed_cleared_page_is_rejected_naming_the_patch() {
1770        let recorder = Recorder::new();
1771        let (device, queue) = open_tier_a(&recorder);
1772        let before = recorder.total_live_objects();
1773        let four = [0u8; 4];
1774        let upload = |layers: u32, patch: TexturePatch<'_>| {
1775            upload_cleared_texture(
1776                device.as_ref(),
1777                queue,
1778                &ClearedTextureDesc {
1779                    label: "atlas",
1780                    format: Format::Rgba8Unorm,
1781                    width: 8,
1782                    height: 8,
1783                    layers,
1784                    view_type: ImageViewType::D2,
1785                    patches: &[patch],
1786                },
1787            )
1788            .expect_err("a malformed page is not a texture")
1789            .to_string()
1790        };
1791        let texel = TexturePatch {
1792            layer: 0,
1793            x: 0,
1794            y: 0,
1795            width: 1,
1796            height: 1,
1797            pixels: &four,
1798        };
1799
1800        let no_layers = upload(0, texel);
1801        assert!(no_layers.contains("at least one layer"), "got: {no_layers}");
1802        for (patch, why) in [
1803            (TexturePatch { layer: 1, ..texel }, "off the only layer"),
1804            (TexturePatch { x: 8, ..texel }, "right of the extent"),
1805            (
1806                TexturePatch {
1807                    y: u32::MAX,
1808                    ..texel
1809                },
1810                "overflowing the extent",
1811            ),
1812            (TexturePatch { width: 0, ..texel }, "empty"),
1813        ] {
1814            let message = upload(1, patch);
1815            assert!(
1816                message.contains("patch 0") && message.contains("inside a 8x8 image"),
1817                "a patch {why} got: {message}"
1818            );
1819        }
1820        let overlapping = upload_cleared_texture(
1821            device.as_ref(),
1822            queue,
1823            &ClearedTextureDesc {
1824                label: "atlas",
1825                format: Format::Rgba8Unorm,
1826                width: 8,
1827                height: 8,
1828                layers: 1,
1829                view_type: ImageViewType::D2,
1830                patches: &[texel, texel],
1831            },
1832        )
1833        .expect_err("two patches on one texel are refused")
1834        .to_string();
1835        assert!(
1836            overlapping.contains("patch 1 overlaps patch 0"),
1837            "got: {overlapping}"
1838        );
1839        let short = upload(1, TexturePatch { width: 2, ..texel });
1840        assert!(
1841            short.contains("patch 0") && short.contains("8 bytes, got 4"),
1842            "got: {short}"
1843        );
1844
1845        assert_eq!(
1846            recorder.total_live_objects(),
1847            before,
1848            "a rejected page creates nothing"
1849        );
1850    }
1851
1852    /// A failure after both buffers exist releases both: the image is what
1853    /// fails, one texel past Tier A's `max_image_2d`.
1854    #[test]
1855    fn a_failed_cleared_page_leaks_nothing() {
1856        let recorder = Recorder::new();
1857        let (device, queue) = open_tier_a(&recorder);
1858        let limit = device.caps().limits.max_image_2d;
1859        let before = recorder.total_live_objects();
1860        let four = [0u8; 4];
1861
1862        let error = upload_cleared_texture(
1863            device.as_ref(),
1864            queue,
1865            &ClearedTextureDesc {
1866                label: "too wide",
1867                format: Format::R8Unorm,
1868                width: limit + 1,
1869                height: 1,
1870                layers: 1,
1871                view_type: ImageViewType::D2,
1872                patches: &[TexturePatch {
1873                    layer: 0,
1874                    x: 0,
1875                    y: 0,
1876                    width: 4,
1877                    height: 1,
1878                    pixels: &four,
1879                }],
1880            },
1881        )
1882        .expect_err("the device refuses an image past max_image_2d");
1883        assert!(
1884            error.to_string().contains("max_image_2d"),
1885            "the failure must be the image, not something earlier: {error}"
1886        );
1887        assert!(
1888            recorder
1889                .events()
1890                .iter()
1891                .any(|event| matches!(event, Event::BufferWritten { .. })),
1892            "only meaningful if the staging buffer really was created and written"
1893        );
1894        assert_eq!(
1895            recorder.total_live_objects(),
1896            before,
1897            "the zeroed and the staging buffer must both be destroyed"
1898        );
1899    }
1900}