Skip to main content

mln_webgpu/
gpu.rs

1//! The [`Gpu`] interface on wgpu.
2
3use std::any::Any;
4use std::ops::Range;
5use std::rc::Rc;
6use std::sync::{Arc, OnceLock};
7
8use mln_gfx::gpu::validation::{
9    self, BindingsTags, BufferInfo, GeometryTags, LayoutTags, Lookup, PassTarget, PipelineTags, ShaderBinding,
10    TextureInfo,
11};
12use mln_gfx::gpu::{
13    BindGroupEntry, BindingsDesc, BindingsId, BufferDesc, BufferId, BufferUsage, Caps, ClipDepth, Draw, DynamicState,
14    GeometryDesc, GeometryId, Gpu, GpuError, LoadOp, PassDesc, PipelineDesc, PipelineId, ReadbackId, ResourceId,
15    SamplerId, Scissor, ShaderId, ShaderKey, SlotMap, TextureDesc, TextureFormat, TextureId, TextureRegion,
16    TextureUsage,
17};
18use mln_gfx::texture2d::SamplerState;
19use mln_gfx::types::{TextureFilterType, TextureWrapType};
20use mln_util::Color;
21use mln_util::size::Size;
22
23use crate::index_table::IndexTable;
24use crate::shaders::shader_program::{self, BindingType, ShaderProgram, validated};
25use crate::writes::Writes;
26use crate::{CustomLayerEncoder, CustomLayerPass, Device};
27
28/// The size of the buffers that small buffers share: uniform and storage
29/// buffers in one kind of page, vertex and index buffers in another.
30const PAGE: u64 = 16 << 10;
31
32/// The alignment of a small uniform or storage buffer in its page: WebGPU's
33/// largest allowed `minUniformBufferOffsetAlignment`, so an offset any
34/// device binds.
35const UNIFORM_ALIGNMENT: u64 = 256;
36
37/// A buffer, or the part of a shared page that a small buffer takes.
38struct Buffer {
39    buffer: wgpu::Buffer,
40    usage: BufferUsage,
41    /// Where the buffer starts in `buffer`.
42    offset: u64,
43    /// The bytes of `buffer` from `offset` that the buffer takes, which
44    /// its writes and bindings stay in.
45    size: u64,
46    /// Of a buffer in a page, the end of the bytes written so far: those
47    /// after it still hold the zeros it was made with. `None` for a buffer
48    /// of its own.
49    written: Option<u64>,
50}
51
52struct Texture {
53    texture: wgpu::Texture,
54    view: wgpu::TextureView,
55}
56
57/// A compiled program, and what it reads from its bindings.
58struct Shader {
59    program: Rc<ShaderProgram>,
60    reads: Vec<ShaderBinding>,
61}
62
63struct Pipeline {
64    pipeline: wgpu::RenderPipeline,
65    tags: PipelineTags,
66}
67
68/// A shader's bind groups, by the pipeline layout's slot, and the slot of
69/// its group of `globalIndex`.
70struct Bindings {
71    groups: Vec<(u32, wgpu::BindGroup)>,
72    index_slot: Option<u32>,
73    tags: BindingsTags,
74}
75
76/// The vertex buffers and the index buffer of a draw, each with the range
77/// of its wgpu buffer that it binds: from its offset to the end of its
78/// buffer, which in a page is short of the page's end.
79struct Geometry {
80    vertex_buffers: Vec<(wgpu::Buffer, Range<u64>)>,
81    index_buffer: (wgpu::Buffer, Range<u64>),
82    /// The ids and offsets of the vertex buffers and of the index buffer,
83    /// which a draw compares with what the pass has bound.
84    vertex_ids: Vec<(BufferId, u64)>,
85    index_id: (BufferId, u64),
86    tags: GeometryTags,
87}
88
89/// A texture's texels, copied into a buffer that the CPU maps.
90struct Readback {
91    buffer: wgpu::Buffer,
92    /// The bytes in each row of `buffer`, which WebGPU pads, and of the
93    /// texels.
94    padded_bytes_per_row: usize,
95    bytes_per_row: usize,
96    rows: usize,
97    #[cfg_attr(target_family = "wasm", expect(dead_code, reason = "a browser can't wait for a submission"))]
98    submission: wgpu::SubmissionIndex,
99    /// How the map ended, once it has.
100    mapped: Arc<OnceLock<Result<(), wgpu::BufferAsyncError>>>,
101}
102
103/// The pass draws record into, and what the draws so far set on it.
104struct OpenPass {
105    pass: wgpu::RenderPass<'static>,
106    target: PassTarget,
107    /// The wgpu formats of its attachments, which a custom layer's pass
108    /// tells.
109    color_format: Option<wgpu::TextureFormat>,
110    depth_stencil_format: Option<wgpu::TextureFormat>,
111    /// The pipeline, bindings, global index and geometry set, `None` where
112    /// a draw sets them again.
113    pipeline: Option<PipelineId>,
114    bindings: Option<BindingsId>,
115    global_index: Option<u32>,
116    geometry: Option<GeometryId>,
117    /// The vertex buffers bound, by slot, and the index buffer, as
118    /// [`Geometry::vertex_ids`]: geometries of other indices or attributes often
119    /// share vertex buffers.
120    vertex_buffers: Vec<(BufferId, u64)>,
121    index_buffer: Option<(BufferId, u64)>,
122    dynamic: Option<DynamicState>,
123}
124
125impl OpenPass {
126    /// Forgets what the draws set, as after a custom layer drew.
127    fn forget_state(&mut self) {
128        self.pipeline = None;
129        self.bindings = None;
130        self.global_index = None;
131        self.geometry = None;
132        self.vertex_buffers.clear();
133        self.index_buffer = None;
134        self.dynamic = None;
135    }
136}
137
138/// A [`Gpu`] on a WebGPU [`Device`].
139///
140/// A shader's groups are WebGPU bind groups, made with the bindings.
141/// `globalIndex` is a dynamic offset into a table of indices. Draws record
142/// into a pass of the frame's command encoder at once, setting only what
143/// changed since the draw before.
144///
145/// Small buffers share larger ones, so that buffers made together sit
146/// together, their writes join one copy, and a frame that remakes many
147/// small buffers makes few wgpu buffers. Writes are gathered and copied into
148/// place ahead of the next flush's commands.
149///
150/// On a browser's WebGPU, a `create_*` call returns before the browser
151/// validates it, so a rejected descriptor reaches the device's
152/// uncaptured-error callback instead of the call's result.
153pub struct WebGpu {
154    device: Device,
155    caps: Caps,
156    index_table: IndexTable,
157    buffers: SlotMap<BufferId, Buffer>,
158    /// The page that small uniform and storage buffers are taken from, and
159    /// how many of its bytes are taken.
160    uniform_page: Option<(wgpu::Buffer, u64)>,
161    /// The page that small vertex and index buffers are taken from, and how
162    /// many of its bytes are taken.
163    geometry_page: Option<(wgpu::Buffer, u64)>,
164    writes: Writes,
165    textures: SlotMap<TextureId, Texture>,
166    samplers: SlotMap<SamplerId, wgpu::Sampler>,
167    shaders: SlotMap<ShaderId, Shader>,
168    layout_tags: LayoutTags,
169    pipelines: SlotMap<PipelineId, Pipeline>,
170    bindings: SlotMap<BindingsId, Bindings>,
171    geometries: SlotMap<GeometryId, Geometry>,
172    readbacks: SlotMap<ReadbackId, Readback>,
173    /// The buffer of the last readback taken, which the next readback of
174    /// its size copies into, as a frame read back each time is.
175    spare_readback: Option<wgpu::Buffer>,
176    /// The commands recorded since the last flush.
177    encoder: Option<wgpu::CommandEncoder>,
178    pass: Option<OpenPass>,
179}
180
181impl WebGpu {
182    /// How many textures the `WebGpu` has, imports included.
183    #[cfg(test)]
184    pub(crate) fn texture_count(&self) -> usize {
185        self.textures.len()
186    }
187
188    #[must_use]
189    pub fn new(device: &Device) -> WebGpu {
190        let limits = device.device().limits();
191        let caps = Caps {
192            buffer_offset_alignment: limits
193                .min_uniform_buffer_offset_alignment
194                .max(limits.min_storage_buffer_offset_alignment),
195            max_texture_size: limits.max_texture_dimension_2d,
196            half_float_render_targets: true,
197            clip_depth: ClipDepth::ZeroToOne,
198            render_target_depth: Some(TextureFormat::Depth32Float),
199            clear_stencil_with_pass: false,
200            line_expressions: false,
201            cpu_rasterizer: device.adapter_info().device_type == wgpu::DeviceType::Cpu,
202            max_line_width: 1.0,
203        };
204        WebGpu {
205            index_table: IndexTable::new(device.device()),
206            device: device.clone(),
207            caps,
208            buffers: SlotMap::with_key(),
209            uniform_page: None,
210            geometry_page: None,
211            writes: Writes::default(),
212            textures: SlotMap::with_key(),
213            samplers: SlotMap::with_key(),
214            shaders: SlotMap::with_key(),
215            layout_tags: LayoutTags::default(),
216            pipelines: SlotMap::with_key(),
217            bindings: SlotMap::with_key(),
218            geometries: SlotMap::with_key(),
219            readbacks: SlotMap::with_key(),
220            spare_readback: None,
221            encoder: None,
222            pass: None,
223        }
224    }
225
226    /// Takes a texture made elsewhere, such as a surface's frame, as a
227    /// texture of this backend. Destroying it drops this backend's
228    /// reference.
229    pub fn import_texture(&mut self, texture: &wgpu::Texture) -> TextureId {
230        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
231        self.textures.insert(Texture { texture: texture.clone(), view })
232    }
233
234    /// The wgpu texture of `texture`.
235    #[cfg(test)]
236    pub(crate) fn native_texture(&self, texture: TextureId) -> Option<&wgpu::Texture> {
237        self.textures.get(texture).map(|texture| &texture.texture)
238    }
239
240    /// The wgpu buffer that `readback` copies into.
241    #[cfg(test)]
242    pub(crate) fn readback_buffer(&self, readback: ReadbackId) -> Option<&wgpu::Buffer> {
243        self.readbacks.get(readback).map(|readback| &readback.buffer)
244    }
245
246    /// Submits the commands since the last flush after the copies of the
247    /// writes made so far, with `then` recorded after them.
248    fn submit(&mut self, then: impl FnOnce(&mut wgpu::CommandEncoder)) -> Result<wgpu::SubmissionIndex, GpuError> {
249        let mut encoder = self.encoder.take().unwrap_or_else(|| {
250            self.device.device().create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") })
251        });
252        then(&mut encoder);
253        // wgpu reports what it rejects in the passes when they finish. The
254        // writes stay for the next flush.
255        let command_buffer = self.validated("flush", |_| encoder.finish())?;
256        let writes = self.writes.encode(self.device.device(), self.device.queue());
257        Ok(self.device.queue().submit(writes.into_iter().chain([command_buffer])))
258    }
259
260    fn info(&self) -> (impl Fn(BufferId) -> Option<BufferInfo> + '_, impl Fn(TextureId) -> Option<TextureInfo> + '_) {
261        let buffer =
262            |id| self.buffers.get(id).map(|buffer: &Buffer| BufferInfo { usage: buffer.usage, size: buffer.size });
263        let texture = |id| self.textures.get(id).map(|texture: &Texture| texture_info(&texture.texture));
264        (buffer, texture)
265    }
266
267    /// Begins a pass of `desc`, which the checks passed, on the frame's
268    /// encoder. Returns it, and the formats of its color and depth-stencil
269    /// attachments.
270    fn begin_render_pass(
271        &mut self,
272        desc: &PassDesc<'_>,
273    ) -> Result<(wgpu::RenderPass<'static>, Option<wgpu::TextureFormat>, Option<wgpu::TextureFormat>), GpuError> {
274        let texture = |id| self.textures.get(id).ok_or(GpuError::UnknownId("texture"));
275        let color = desc
276            .color
277            .map(|attachment| Ok::<_, GpuError>((texture(attachment.texture)?, attachment.load)))
278            .transpose()?;
279        let depth_stencil = desc
280            .depth_stencil
281            .map(|attachment| Ok::<_, GpuError>((texture(attachment.texture)?, attachment)))
282            .transpose()?;
283        let color_format = color.map(|(texture, _)| texture.texture.format());
284        let depth_stencil_format = depth_stencil.map(|(texture, _)| texture.texture.format());
285        let color_attachment = color.map(|(texture, load)| wgpu::RenderPassColorAttachment {
286            view: &texture.view,
287            depth_slice: None,
288            resolve_target: None,
289            ops: wgpu::Operations {
290                load: match load {
291                    LoadOp::Load => wgpu::LoadOp::Load,
292                    LoadOp::Clear(color) => wgpu::LoadOp::Clear(wgpu_color(color)),
293                },
294                store: wgpu::StoreOp::Store,
295            },
296        });
297        let depth_stencil_attachment =
298            depth_stencil.map(|(texture, attachment)| wgpu::RenderPassDepthStencilAttachment {
299                view: &texture.view,
300                depth_ops: Some(wgpu::Operations {
301                    load: match attachment.depth {
302                        LoadOp::Load => wgpu::LoadOp::Load,
303                        LoadOp::Clear(depth) => wgpu::LoadOp::Clear(depth),
304                    },
305                    store: wgpu::StoreOp::Store,
306                }),
307                stencil_ops: texture.texture.format().has_stencil_aspect().then_some(wgpu::Operations {
308                    load: match attachment.stencil {
309                        LoadOp::Load => wgpu::LoadOp::Load,
310                        LoadOp::Clear(stencil) => wgpu::LoadOp::Clear(stencil),
311                    },
312                    store: wgpu::StoreOp::Store,
313                }),
314            });
315        let device = self.device.device();
316        let encoder = self.encoder.get_or_insert_with(|| {
317            device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") })
318        });
319        let pass = encoder
320            .begin_render_pass(&wgpu::RenderPassDescriptor {
321                label: Some(desc.label),
322                color_attachments: &[color_attachment],
323                depth_stencil_attachment,
324                timestamp_writes: None,
325                occlusion_query_set: None,
326                multiview_mask: None,
327            })
328            .forget_lifetime();
329        Ok((pass, color_format, depth_stencil_format))
330    }
331
332    fn no_pass(what: &str) -> GpuError {
333        GpuError::Invalid(format!("{what} outside a pass"))
334    }
335
336    fn open_pass(what: &str) -> GpuError {
337        GpuError::Invalid(format!("{what} while a pass is open"))
338    }
339
340    /// Blocks until the GPU has finished `submission`, or everything
341    /// submitted with `None`.
342    #[cfg(not(target_family = "wasm"))]
343    fn wait_for(&self, submission: Option<&wgpu::SubmissionIndex>) -> Result<(), GpuError> {
344        /// How long the wait goes on asking after waits that reported a
345        /// timeout.
346        const WAIT_AGAIN_LIMIT: std::time::Duration = std::time::Duration::from_secs(1);
347        let device = self.device.device();
348        let wait = || device.poll(wgpu::PollType::Wait { submission_index: submission.cloned(), timeout: None });
349        // A wait without a timeout can still report one: PowerVR's Vulkan
350        // driver on Android ends the wait shortly before the fence value
351        // that wgpu reads afterwards shows the submission finished. Waiting
352        // again returns at once then, so this asks until the value caught up.
353        let start = mln_util::time::Instant::now();
354        let mut waited = wait();
355        while matches!(waited, Err(wgpu::PollError::Timeout)) && start.elapsed() < WAIT_AGAIN_LIMIT {
356            waited = wait();
357        }
358        waited.map(drop).map_err(|error| GpuError::Invalid(format!("waiting for the GPU: {error}")))
359    }
360
361    /// `size` bytes of a page that small uniform and storage buffers share,
362    /// zero filled: the page and their offset in it.
363    fn allocate_uniform(&mut self, size: u64) -> Result<(wgpu::Buffer, u64), GpuError> {
364        let mut page = self.uniform_page.take();
365        let allocated = allocate_in_page(&mut page, size.next_multiple_of(UNIFORM_ALIGNMENT), || {
366            self.create_uniform_buffer("uniform page", PAGE)
367        });
368        self.uniform_page = page;
369        allocated
370    }
371
372    /// `size` bytes of a page that small vertex and index buffers share,
373    /// zero filled: the page and their offset in it.
374    fn allocate_geometry(&mut self, size: u64) -> Result<(wgpu::Buffer, u64), GpuError> {
375        let mut page = self.geometry_page.take();
376        let allocated = allocate_in_page(&mut page, size, || {
377            self.validated("geometry page", |device| {
378                device.create_buffer(&wgpu::BufferDescriptor {
379                    label: Some("geometry page"),
380                    size: PAGE,
381                    usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
382                    mapped_at_creation: false,
383                })
384            })
385        });
386        self.geometry_page = page;
387        allocated
388    }
389
390    /// A buffer that binds as a uniform or a storage buffer.
391    fn create_uniform_buffer(&self, label: &str, size: u64) -> Result<wgpu::Buffer, GpuError> {
392        self.validated(label, |device| {
393            device.create_buffer(&wgpu::BufferDescriptor {
394                label: Some(label),
395                size,
396                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
397                mapped_at_creation: false,
398            })
399        })
400    }
401
402    /// Runs `create` in a validation error scope, as the error of the call
403    /// that `what` names.
404    fn validated<T>(&self, what: &str, create: impl FnOnce(&wgpu::Device) -> T) -> Result<T, GpuError> {
405        let device = self.device.device();
406        validated(device, || create(device)).map_err(|error| GpuError::Invalid(format!("{what}: {error}")))
407    }
408}
409
410/// `size` bytes of `page`, or of a new page that `create` makes when it has
411/// too few left: the page and the offset in it.
412fn allocate_in_page(
413    page: &mut Option<(wgpu::Buffer, u64)>,
414    size: u64,
415    create: impl FnOnce() -> Result<wgpu::Buffer, GpuError>,
416) -> Result<(wgpu::Buffer, u64), GpuError> {
417    let (buffer, taken) = match page {
418        Some((buffer, taken)) if *taken + size <= PAGE => (buffer, taken),
419        _ => {
420            let (buffer, taken) = page.insert((create()?, 0));
421            (buffer, taken)
422        }
423    };
424    let offset = *taken;
425    *taken += size;
426    Ok((buffer.clone(), offset))
427}
428
429/// What the checks read of `texture`.
430fn texture_info(texture: &wgpu::Texture) -> TextureInfo {
431    let usage = texture.usage();
432    TextureInfo {
433        format: from_wgpu_format(texture.format()),
434        size: Size { width: texture.width(), height: texture.height() },
435        usage: TextureUsage {
436            sampled: usage.contains(wgpu::TextureUsages::TEXTURE_BINDING),
437            render_target: usage.contains(wgpu::TextureUsages::RENDER_ATTACHMENT),
438            copy_src: usage.contains(wgpu::TextureUsages::COPY_SRC),
439        },
440    }
441}
442
443fn wgpu_color(color: Color) -> wgpu::Color {
444    wgpu::Color { r: f64::from(color.r), g: f64::from(color.g), b: f64::from(color.b), a: f64::from(color.a) }
445}
446
447fn texture_format(format: TextureFormat) -> wgpu::TextureFormat {
448    match format {
449        // WGSL reads an alpha texture's one channel as red.
450        TextureFormat::R8Unorm | TextureFormat::A8Unorm => wgpu::TextureFormat::R8Unorm,
451        TextureFormat::R16Float => wgpu::TextureFormat::R16Float,
452        TextureFormat::R32Float => wgpu::TextureFormat::R32Float,
453        TextureFormat::Rgba8Unorm => wgpu::TextureFormat::Rgba8Unorm,
454        TextureFormat::Rgba8UnormSrgb => wgpu::TextureFormat::Rgba8UnormSrgb,
455        TextureFormat::Bgra8Unorm => wgpu::TextureFormat::Bgra8Unorm,
456        TextureFormat::Bgra8UnormSrgb => wgpu::TextureFormat::Bgra8UnormSrgb,
457        TextureFormat::Rgb10a2Unorm => wgpu::TextureFormat::Rgb10a2Unorm,
458        TextureFormat::Rgba16Float => wgpu::TextureFormat::Rgba16Float,
459        TextureFormat::Rgba32Float => wgpu::TextureFormat::Rgba32Float,
460        TextureFormat::Depth32Float => wgpu::TextureFormat::Depth32Float,
461        TextureFormat::Depth24PlusStencil8 => wgpu::TextureFormat::Depth24PlusStencil8,
462        TextureFormat::Depth32FloatStencil8 => wgpu::TextureFormat::Depth32FloatStencil8,
463    }
464}
465
466/// What `shader` reads from its bindings, by the shaders' ids.
467fn shader_bindings(shader: &ShaderProgram) -> Result<Vec<ShaderBinding>, GpuError> {
468    let mut bindings = Vec::new();
469    for &group in shader.bind_group_order() {
470        if Some(group) == shader.index_group() {
471            continue;
472        }
473        for info in shader.binding_infos(group) {
474            let binding = match info.type_ {
475                BindingType::UniformBuffer | BindingType::ReadOnlyStorageBuffer | BindingType::StorageBuffer => {
476                    ShaderBinding::Buffer { id: info.binding, min_size: shader.buffer_size(group, info.binding) }
477                }
478                BindingType::Sampler | BindingType::Texture | BindingType::UnfilterableTexture => {
479                    let sampler = info.type_ == BindingType::Sampler;
480                    let id = shader.texture_at(info.binding, sampler).ok_or_else(|| {
481                        GpuError::Invalid(format!(
482                            "{} reads binding {} with no texture id",
483                            shader.name(),
484                            info.binding
485                        ))
486                    })?;
487                    ShaderBinding::Texture { id: id as u32 }
488                }
489            };
490            if !bindings.contains(&binding) {
491                bindings.push(binding);
492            }
493        }
494    }
495    Ok(bindings)
496}
497
498/// The format of `format`, `None` for a format the interface has no name
499/// for.
500pub(crate) fn from_wgpu_format(format: wgpu::TextureFormat) -> Option<TextureFormat> {
501    Some(match format {
502        wgpu::TextureFormat::R8Unorm => TextureFormat::R8Unorm,
503        wgpu::TextureFormat::R16Float => TextureFormat::R16Float,
504        wgpu::TextureFormat::R32Float => TextureFormat::R32Float,
505        wgpu::TextureFormat::Rgba8Unorm => TextureFormat::Rgba8Unorm,
506        wgpu::TextureFormat::Rgba8UnormSrgb => TextureFormat::Rgba8UnormSrgb,
507        wgpu::TextureFormat::Bgra8Unorm => TextureFormat::Bgra8Unorm,
508        wgpu::TextureFormat::Bgra8UnormSrgb => TextureFormat::Bgra8UnormSrgb,
509        wgpu::TextureFormat::Rgb10a2Unorm => TextureFormat::Rgb10a2Unorm,
510        wgpu::TextureFormat::Rgba16Float => TextureFormat::Rgba16Float,
511        wgpu::TextureFormat::Rgba32Float => TextureFormat::Rgba32Float,
512        wgpu::TextureFormat::Depth32Float => TextureFormat::Depth32Float,
513        wgpu::TextureFormat::Depth24PlusStencil8 => TextureFormat::Depth24PlusStencil8,
514        wgpu::TextureFormat::Depth32FloatStencil8 => TextureFormat::Depth32FloatStencil8,
515        _ => return None,
516    })
517}
518
519impl Gpu for WebGpu {
520    fn caps(&self) -> &Caps {
521        &self.caps
522    }
523
524    fn create_buffer(&mut self, desc: &BufferDesc<'_>) -> Result<BufferId, GpuError> {
525        let size = desc.size.next_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT);
526        let usage = match desc.usage {
527            BufferUsage::Vertex | BufferUsage::Index if size <= PAGE / 4 => {
528                let (buffer, offset) = self.allocate_geometry(size)?;
529                let written = Some(0);
530                return Ok(self.buffers.insert(Buffer { buffer, usage: desc.usage, offset, size, written }));
531            }
532            BufferUsage::Vertex => wgpu::BufferUsages::VERTEX,
533            BufferUsage::Index => wgpu::BufferUsages::INDEX,
534            BufferUsage::Uniform | BufferUsage::Storage => {
535                let (buffer, offset, written) = if size <= PAGE / 4 {
536                    let (page, offset) = self.allocate_uniform(size)?;
537                    (page, offset, Some(0))
538                } else {
539                    (self.create_uniform_buffer(desc.label, size)?, 0, None)
540                };
541                return Ok(self.buffers.insert(Buffer { buffer, usage: desc.usage, offset, size, written }));
542            }
543        };
544        let buffer = self.validated(desc.label, |device| {
545            device.create_buffer(&wgpu::BufferDescriptor {
546                label: Some(desc.label),
547                size,
548                usage: usage | wgpu::BufferUsages::COPY_DST,
549                mapped_at_creation: false,
550            })
551        })?;
552        Ok(self.buffers.insert(Buffer { buffer, usage: desc.usage, offset: 0, size, written: None }))
553    }
554
555    fn write_buffer(&mut self, buffer: BufferId, offset: u64, data: &[u8]) -> Result<(), GpuError> {
556        let entry = self.buffers.get_mut(buffer).ok_or(GpuError::UnknownId("buffer"))?;
557        let end = offset + data.len() as u64;
558        if end > entry.size {
559            return Err(GpuError::Invalid(format!("a write to bytes {offset}..{end} of a buffer of {}", entry.size)));
560        }
561        // Where the rest of a buffer in a page still holds its zeros, they
562        // can be written with the data, so that the copy joins the next
563        // buffer's.
564        let padded = match &mut entry.written {
565            Some(written) if end >= *written => {
566                *written = end;
567                entry.size - offset
568            }
569            _ => data.len() as u64,
570        };
571        let (device, queue) = (self.device.device(), self.device.queue());
572        self.writes.write_padded(device, queue, &entry.buffer, entry.offset + offset, data, padded);
573        Ok(())
574    }
575
576    /// Writes from the JS array with `GPUQueue.writeBuffer`
577    /// (`Writes::write_from_host`).
578    #[cfg(target_family = "wasm")]
579    fn write_buffer_from_host(
580        &mut self,
581        buffer: BufferId,
582        offset: u64,
583        data: &mln_util::host_bytes::HostBytes,
584    ) -> Result<(), GpuError> {
585        let entry = self.buffers.get_mut(buffer).ok_or(GpuError::UnknownId("buffer"))?;
586        let len = data.len() as u64;
587        let end = offset + len.next_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT);
588        if end > entry.size {
589            return Err(GpuError::Invalid(format!("a write to bytes {offset}..{end} of a buffer of {}", entry.size)));
590        }
591        // A later write past these bytes pads only past them.
592        if let Some(written) = &mut entry.written {
593            *written = (*written).max(offset + len);
594        }
595        let (device, queue) = (self.device.device(), self.device.queue());
596        let at = entry.offset + offset;
597        let aligned = len & !(wgpu::COPY_BUFFER_ALIGNMENT - 1);
598        self.writes.write_from_host(device, queue, &entry.buffer, at, data, aligned);
599        if aligned < len
600            && let Some(array) = data.array()
601        {
602            // writeBuffer takes whole 4-byte words.
603            let mut tail = [0u8; wgpu::COPY_BUFFER_ALIGNMENT as usize];
604            array.subarray(aligned as u32, len as u32).copy_to(&mut tail[..(len - aligned) as usize]);
605            self.writes.write_padded(device, queue, &entry.buffer, at + aligned, &tail, wgpu::COPY_BUFFER_ALIGNMENT);
606        }
607        Ok(())
608    }
609
610    fn create_texture(&mut self, desc: &TextureDesc<'_>) -> Result<TextureId, GpuError> {
611        let mut usage = wgpu::TextureUsages::empty();
612        if desc.usage.sampled {
613            usage |= wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST;
614        }
615        if desc.usage.render_target {
616            usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
617        }
618        if desc.usage.copy_src {
619            usage |= wgpu::TextureUsages::COPY_SRC;
620        }
621        let format = texture_format(desc.format);
622        let required = format.required_features();
623        if !self.device.device().features().contains(required) {
624            return Err(GpuError::Unsupported(format!("{:?} textures need {required:?}", desc.format)));
625        }
626        let texture = self.validated(desc.label, |device| {
627            device.create_texture(&wgpu::TextureDescriptor {
628                label: Some(desc.label),
629                size: wgpu::Extent3d { width: desc.size.width, height: desc.size.height, depth_or_array_layers: 1 },
630                mip_level_count: 1,
631                sample_count: 1,
632                dimension: wgpu::TextureDimension::D2,
633                format,
634                usage,
635                view_formats: &[],
636            })
637        })?;
638        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
639        Ok(self.textures.insert(Texture { texture, view }))
640    }
641
642    fn write_texture(&mut self, texture: TextureId, region: TextureRegion, data: &[u8]) -> Result<(), GpuError> {
643        let texture = &self.textures.get(texture).ok_or(GpuError::UnknownId("texture"))?.texture;
644        if !texture.usage().contains(wgpu::TextureUsages::COPY_DST) {
645            return Err(GpuError::Invalid("a write to a texture that isn't sampled".to_owned()));
646        }
647        let format = from_wgpu_format(texture.format())
648            .ok_or_else(|| GpuError::Invalid(format!("{:?} textures take no writes", texture.format())))?;
649        let size = Size::new(texture.width(), texture.height());
650        let bytes_per_row = region.write_bytes_per_row(size, format, data)?;
651        self.device.queue().write_texture(
652            wgpu::TexelCopyTextureInfo {
653                texture,
654                mip_level: 0,
655                origin: wgpu::Origin3d { x: region.x, y: region.y, z: 0 },
656                aspect: wgpu::TextureAspect::All,
657            },
658            data,
659            wgpu::TexelCopyBufferLayout {
660                offset: 0,
661                bytes_per_row: Some(bytes_per_row as u32),
662                rows_per_image: Some(region.size.height),
663            },
664            wgpu::Extent3d { width: region.size.width, height: region.size.height, depth_or_array_layers: 1 },
665        );
666        Ok(())
667    }
668
669    fn create_sampler(&mut self, state: &SamplerState) -> Result<SamplerId, GpuError> {
670        let filter = match state.filter {
671            TextureFilterType::Linear => wgpu::FilterMode::Linear,
672            TextureFilterType::Nearest => wgpu::FilterMode::Nearest,
673        };
674        let address_mode = |wrap| match wrap {
675            TextureWrapType::Repeat => wgpu::AddressMode::Repeat,
676            TextureWrapType::Clamp => wgpu::AddressMode::ClampToEdge,
677        };
678        let sampler = self.validated("sampler", |device| {
679            device.create_sampler(&wgpu::SamplerDescriptor {
680                label: None,
681                address_mode_u: address_mode(state.wrap_u),
682                address_mode_v: address_mode(state.wrap_v),
683                address_mode_w: wgpu::AddressMode::ClampToEdge,
684                mag_filter: filter,
685                min_filter: filter,
686                mipmap_filter: if state.mipmapped {
687                    wgpu::MipmapFilterMode::Linear
688                } else {
689                    wgpu::MipmapFilterMode::Nearest
690                },
691                anisotropy_clamp: u16::from(state.max_anisotropy.max(1)),
692                ..Default::default()
693            })
694        })?;
695        Ok(self.samplers.insert(sampler))
696    }
697
698    fn create_shader(&mut self, key: &ShaderKey) -> Result<ShaderId, GpuError> {
699        let program = shader_program::compile(self.device.device(), self.index_table.layout(), key)?;
700        let reads = shader_bindings(&program)?;
701        Ok(self.shaders.insert(Shader { program: Rc::new(program), reads }))
702    }
703
704    fn create_pipeline(&mut self, desc: &PipelineDesc<'_>) -> Result<PipelineId, GpuError> {
705        let shader = self.shaders.get(desc.shader).ok_or(GpuError::UnknownId("shader"))?;
706        let pipeline = shader.program.render_pipeline(
707            desc.vertex_buffers,
708            &desc.state,
709            desc.targets.color.map(texture_format),
710            desc.targets.depth_stencil.map(texture_format),
711        )?;
712        let layout = self.layout_tags.tag(desc.shader, desc.vertex_buffers);
713        let tags = PipelineTags { shader: desc.shader, layout, targets: desc.targets };
714        Ok(self.pipelines.insert(Pipeline { pipeline, tags }))
715    }
716
717    fn create_bindings(&mut self, desc: &BindingsDesc<'_>) -> Result<BindingsId, GpuError> {
718        let shader = self.shaders.get(desc.shader).ok_or(GpuError::UnknownId("shader"))?;
719        let elements = {
720            let (buffer, texture) = self.info();
721            let sampler = |id| self.samplers.contains_key(id);
722            let lookup = Lookup { buffer: &buffer, texture: &texture, sampler: &sampler };
723            validation::check_bindings(desc, &shader.reads, self.caps.buffer_offset_alignment, &lookup)?
724        };
725        let program = &shader.program;
726        let mut groups = Vec::new();
727        let mut index_slot = None;
728        for (slot, &group) in program.bind_group_order().iter().enumerate() {
729            if Some(group) == program.index_group() {
730                index_slot = Some(slot as u32);
731                continue;
732            }
733            let layout = program.bind_group_layout(group).ok_or(GpuError::UnknownId("bind group layout"))?;
734            let mut entries = Vec::new();
735            for info in program.binding_infos(group) {
736                let missing = || {
737                    GpuError::Invalid(format!(
738                        "{} reads binding {} of group {}, which no entry binds",
739                        program.name(),
740                        info.binding,
741                        info.group
742                    ))
743                };
744                let resource = match info.type_ {
745                    BindingType::UniformBuffer | BindingType::ReadOnlyStorageBuffer | BindingType::StorageBuffer => {
746                        let (buffer, offset, size) = desc
747                            .entries
748                            .iter()
749                            .find_map(|entry| match *entry {
750                                BindGroupEntry::Buffer { id, buffer, offset, size } if id == info.binding => {
751                                    Some((buffer, offset, size))
752                                }
753                                _ => None,
754                            })
755                            .ok_or_else(missing)?;
756                        let buffer = self.buffers.get(buffer).ok_or(GpuError::UnknownId("buffer"))?;
757                        wgpu::BindingResource::Buffer(wgpu::BufferBinding {
758                            buffer: &buffer.buffer,
759                            offset: buffer.offset + offset,
760                            size: wgpu::BufferSize::new(size),
761                        })
762                    }
763                    BindingType::Sampler | BindingType::Texture | BindingType::UnfilterableTexture => {
764                        let sampler = info.type_ == BindingType::Sampler;
765                        let texture_id = program.texture_at(info.binding, sampler).ok_or_else(missing)? as u32;
766                        let (texture, texture_sampler) = desc
767                            .entries
768                            .iter()
769                            .find_map(|entry| match *entry {
770                                BindGroupEntry::Texture { id, texture, sampler } if id == texture_id => {
771                                    Some((texture, sampler))
772                                }
773                                _ => None,
774                            })
775                            .ok_or_else(missing)?;
776                        if sampler {
777                            wgpu::BindingResource::Sampler(
778                                self.samplers.get(texture_sampler).ok_or(GpuError::UnknownId("sampler"))?,
779                            )
780                        } else {
781                            wgpu::BindingResource::TextureView(
782                                &self.textures.get(texture).ok_or(GpuError::UnknownId("texture"))?.view,
783                            )
784                        }
785                    }
786                };
787                entries.push(wgpu::BindGroupEntry { binding: info.binding, resource });
788            }
789            let group = self.validated(desc.label, |device| {
790                device.create_bind_group(&wgpu::BindGroupDescriptor {
791                    label: Some(desc.label),
792                    layout,
793                    entries: &entries,
794                })
795            })?;
796            groups.push((slot as u32, group));
797        }
798        let tags = BindingsTags { shader: desc.shader, elements };
799        Ok(self.bindings.insert(Bindings { groups, index_slot, tags }))
800    }
801
802    fn create_geometry(&mut self, desc: &GeometryDesc<'_>) -> Result<GeometryId, GpuError> {
803        if !self.shaders.contains_key(desc.shader) {
804            return Err(GpuError::UnknownId("shader"));
805        }
806        let ranges = {
807            let (buffer, texture) = self.info();
808            let lookup = Lookup { buffer: &buffer, texture: &texture, sampler: &|_| false };
809            validation::check_geometry(desc, &lookup)?
810        };
811        let native = |id: BufferId, offset: u64| {
812            let buffer = self.buffers.get(id).ok_or(GpuError::UnknownId("buffer"))?;
813            Ok::<_, GpuError>((buffer.buffer.clone(), buffer.offset + offset..buffer.offset + buffer.size))
814        };
815        let vertex_buffers =
816            desc.vertex_buffers.iter().map(|&(id, offset)| native(id, offset)).collect::<Result<Vec<_>, _>>()?;
817        let index_buffer = native(desc.index_buffer, 0)?;
818        let tags = GeometryTags { layout: self.layout_tags.tag(desc.shader, desc.layouts), ranges };
819        Ok(self.geometries.insert(Geometry {
820            vertex_buffers,
821            index_buffer,
822            vertex_ids: desc.vertex_buffers.to_vec(),
823            index_id: (desc.index_buffer, 0),
824            tags,
825        }))
826    }
827
828    /// Drops this backend's references: wgpu keeps a resource while
829    /// bindings, geometry or recorded commands hold it.
830    fn destroy(&mut self, resource: ResourceId) {
831        match resource {
832            ResourceId::Buffer(id) => drop(self.buffers.remove(id)),
833            ResourceId::Texture(id) => drop(self.textures.remove(id)),
834            ResourceId::Sampler(id) => drop(self.samplers.remove(id)),
835            ResourceId::Shader(id) => drop(self.shaders.remove(id)),
836            ResourceId::Pipeline(id) => drop(self.pipelines.remove(id)),
837            ResourceId::Bindings(id) => drop(self.bindings.remove(id)),
838            ResourceId::Geometry(id) => drop(self.geometries.remove(id)),
839            ResourceId::Readback(id) => drop(self.readbacks.remove(id)),
840        }
841    }
842
843    fn begin_pass(&mut self, desc: &PassDesc<'_>) -> Result<(), GpuError> {
844        if self.pass.is_some() {
845            return Err(Self::open_pass("a pass"));
846        }
847        let target = {
848            let (_, texture) = self.info();
849            validation::check_pass(desc, &texture)?
850        };
851        let (pass, color_format, depth_stencil_format) = self.begin_render_pass(desc)?;
852        self.pass = Some(OpenPass {
853            pass,
854            target,
855            color_format,
856            depth_stencil_format,
857            pipeline: None,
858            bindings: None,
859            global_index: None,
860            geometry: None,
861            vertex_buffers: Vec::new(),
862            index_buffer: None,
863            dynamic: Some(DynamicState {
864                depth_range: (0.0, 1.0),
865                scissor: Scissor { x: 0, y: 0, width: target.size.width, height: target.size.height },
866                stencil_reference: 0,
867                blend_constant: Color::new_unchecked(0.0, 0.0, 0.0, 0.0),
868                line_width: 1.0,
869            }),
870        });
871        Ok(())
872    }
873
874    fn draw(&mut self, draw: &Draw) -> Result<(), GpuError> {
875        let open = self.pass.as_mut().ok_or_else(|| Self::no_pass("a draw"))?;
876        let pipeline = self.pipelines.get(draw.pipeline).ok_or(GpuError::UnknownId("pipeline"))?;
877        let bindings = self.bindings.get(draw.bindings).ok_or(GpuError::UnknownId("bindings"))?;
878        let geometry = self.geometries.get(draw.geometry).ok_or(GpuError::UnknownId("geometry"))?;
879        validation::check_draw(draw, open.target.targets, &pipeline.tags, &bindings.tags, &geometry.tags)?;
880        let pass = &mut open.pass;
881        if open.pipeline != Some(draw.pipeline) {
882            pass.set_pipeline(&pipeline.pipeline);
883            open.pipeline = Some(draw.pipeline);
884        }
885        let bindings_changed = open.bindings != Some(draw.bindings);
886        if bindings_changed {
887            for (slot, group) in &bindings.groups {
888                pass.set_bind_group(*slot, group, &[]);
889            }
890            open.bindings = Some(draw.bindings);
891        }
892        if let Some(slot) = bindings.index_slot
893            && (bindings_changed || open.global_index != Some(draw.global_index))
894        {
895            self.index_table.reserve(self.device.device(), self.device.queue(), draw.global_index);
896            let (group, offset) = self
897                .index_table
898                .get(draw.global_index)
899                .ok_or_else(|| GpuError::Invalid(format!("global index {}", draw.global_index)))?;
900            pass.set_bind_group(slot, group, &[offset]);
901            open.global_index = Some(draw.global_index);
902        }
903        if open.geometry != Some(draw.geometry) {
904            for (slot, ((buffer, range), id)) in geometry.vertex_buffers.iter().zip(&geometry.vertex_ids).enumerate() {
905                if open.vertex_buffers.get(slot) != Some(id) {
906                    pass.set_vertex_buffer(slot as u32, buffer.slice(range.clone()));
907                    match open.vertex_buffers.get_mut(slot) {
908                        Some(bound) => *bound = *id,
909                        None => open.vertex_buffers.push(*id),
910                    }
911                }
912            }
913            if open.index_buffer != Some(geometry.index_id) {
914                let (buffer, range) = &geometry.index_buffer;
915                pass.set_index_buffer(buffer.slice(range.clone()), wgpu::IndexFormat::Uint16);
916                open.index_buffer = Some(geometry.index_id);
917            }
918            open.geometry = Some(draw.geometry);
919        }
920        let dynamic = draw.dynamic;
921        let last = open.dynamic.replace(dynamic);
922        let changed = |same: fn(&DynamicState, &DynamicState) -> bool| last.is_none_or(|last| !same(&last, &dynamic));
923        if changed(|a, b| a.depth_range == b.depth_range) {
924            let size = open.target.size;
925            let (min, max) = dynamic.depth_range;
926            pass.set_viewport(0.0, 0.0, size.width as f32, size.height as f32, min, max);
927        }
928        if changed(|a, b| a.scissor == b.scissor) {
929            let Scissor { x, y, width, height } = dynamic.scissor;
930            pass.set_scissor_rect(x, y, width, height);
931        }
932        if changed(|a, b| a.stencil_reference == b.stencil_reference) {
933            pass.set_stencil_reference(dynamic.stencil_reference);
934        }
935        if changed(|a, b| a.blend_constant == b.blend_constant) {
936            pass.set_blend_constant(wgpu_color(dynamic.blend_constant));
937        }
938        // WebGPU draws lines 1 pixel wide.
939        let indices = draw.first_index..draw.first_index + draw.index_count;
940        let instances = draw.first_instance..draw.first_instance + draw.instance_count;
941        pass.draw_indexed(indices, draw.base_vertex, instances);
942        Ok(())
943    }
944
945    /// Lends the open pass, or the frame's command encoder. A pass that a
946    /// custom layer draws into has a color attachment.
947    fn lend(&mut self, f: &mut dyn FnMut(&mut dyn Any)) -> Result<(), GpuError> {
948        let (device, queue) = (self.device.device().clone(), self.device.queue().clone());
949        if let Some(mut open) = self.pass.take() {
950            let Some(color_format) = open.color_format else {
951                self.pass = Some(open);
952                return Err(GpuError::Unsupported("a custom layer's pass without a color attachment".to_owned()));
953            };
954            let depth_stencil_format = open.depth_stencil_format;
955            let mut lent =
956                CustomLayerPass { device, queue, pass: open.pass, color_format, depth_stencil_format, sample_count: 1 };
957            f(&mut lent);
958            open.pass = lent.pass;
959            open.forget_state();
960            self.pass = Some(open);
961            return Ok(());
962        }
963        let encoder = self
964            .encoder
965            .take()
966            .unwrap_or_else(|| device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") }));
967        let mut lent = CustomLayerEncoder { device, queue, encoder };
968        f(&mut lent);
969        self.encoder = Some(lent.encoder);
970        Ok(())
971    }
972
973    fn end_pass(&mut self) -> Result<(), GpuError> {
974        self.pass.take().map(drop).ok_or_else(|| Self::no_pass("the end of a pass"))
975    }
976
977    fn flush(&mut self, wait: bool) -> Result<(), GpuError> {
978        if self.pass.is_some() {
979            return Err(Self::open_pass("a flush"));
980        }
981        let submission = self.submit(|_| {})?;
982        #[cfg(not(target_family = "wasm"))]
983        if wait {
984            return self.wait_for(Some(&submission));
985        }
986        let _ = (wait, submission);
987        Ok(())
988    }
989
990    /// Copies into a buffer that is mapped once the copy is done: the last
991    /// readback's where it's as big, else a new one.
992    fn read_texture(&mut self, texture: TextureId, region: TextureRegion) -> Result<ReadbackId, GpuError> {
993        if self.pass.is_some() {
994            return Err(Self::open_pass("a readback"));
995        }
996        let texture = self.textures.get(texture).map(|texture| texture.texture.clone());
997        let readback = validation::check_readback(texture.as_ref().map(texture_info), region)?;
998        let texture = texture.ok_or(GpuError::UnknownId("texture"))?;
999        let padded_bytes_per_row = readback.bytes_per_row.next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize);
1000        let (width, rows) = (region.size.width, region.size.height);
1001        let size = (padded_bytes_per_row * rows as usize) as u64;
1002        let buffer = match self.spare_readback.take() {
1003            Some(buffer) if buffer.size() == size => buffer,
1004            _ => self.validated("readback", |device| {
1005                device.create_buffer(&wgpu::BufferDescriptor {
1006                    label: Some("readback"),
1007                    size,
1008                    usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
1009                    mapped_at_creation: false,
1010                })
1011            })?,
1012        };
1013        let submission = self.submit(|encoder| {
1014            encoder.copy_texture_to_buffer(
1015                wgpu::TexelCopyTextureInfo {
1016                    texture: &texture,
1017                    mip_level: 0,
1018                    origin: wgpu::Origin3d { x: region.x, y: region.y, z: 0 },
1019                    aspect: wgpu::TextureAspect::All,
1020                },
1021                wgpu::TexelCopyBufferInfo {
1022                    buffer: &buffer,
1023                    layout: wgpu::TexelCopyBufferLayout {
1024                        offset: 0,
1025                        bytes_per_row: Some(padded_bytes_per_row as u32),
1026                        rows_per_image: Some(rows),
1027                    },
1028                },
1029                wgpu::Extent3d { width, height: rows, depth_or_array_layers: 1 },
1030            );
1031        })?;
1032        let mapped = Arc::new(OnceLock::new());
1033        let map_ended = Arc::clone(&mapped);
1034        buffer.map_async(wgpu::MapMode::Read, .., move |result| {
1035            let _ = map_ended.set(result);
1036        });
1037        Ok(self.readbacks.insert(Readback {
1038            buffer,
1039            padded_bytes_per_row,
1040            bytes_per_row: readback.bytes_per_row,
1041            rows: rows as usize,
1042            submission,
1043            mapped,
1044        }))
1045    }
1046
1047    /// Polls the device for the map, or on a browser leaves it to the
1048    /// browser's event loop, which can't wait.
1049    fn take_readback(&mut self, readback: ReadbackId, wait: bool) -> Result<Option<Vec<u8>>, GpuError> {
1050        let entry = self.readbacks.get(readback).ok_or(GpuError::UnknownId("readback"))?;
1051        let mapped = Arc::clone(&entry.mapped);
1052        if mapped.get().is_none() {
1053            #[cfg(not(target_family = "wasm"))]
1054            if wait {
1055                if let Err(error) = self.wait_for(Some(&entry.submission)) {
1056                    self.readbacks.remove(readback);
1057                    return Err(error);
1058                }
1059            } else {
1060                let _ = self.device.device().poll(wgpu::PollType::Poll);
1061            }
1062            #[cfg(target_family = "wasm")]
1063            let _ = wait;
1064        }
1065        let Some(mapped) = mapped.get() else {
1066            return Ok(None);
1067        };
1068        let Readback { buffer, padded_bytes_per_row, bytes_per_row, rows, .. } =
1069            self.readbacks.remove(readback).ok_or(GpuError::UnknownId("readback"))?;
1070        if let Err(error) = mapped {
1071            return Err(GpuError::Invalid(format!("mapping a readback: {error}")));
1072        }
1073        let texels = {
1074            let range = buffer
1075                .get_mapped_range(..)
1076                .map_err(|error| GpuError::Invalid(format!("a readback's range: {error}")))?;
1077            if padded_bytes_per_row == bytes_per_row {
1078                range[..bytes_per_row * rows].to_vec()
1079            } else {
1080                let mut texels = Vec::with_capacity(bytes_per_row * rows);
1081                for row in range.chunks(padded_bytes_per_row).take(rows) {
1082                    texels.extend_from_slice(&row[..bytes_per_row]);
1083                }
1084                texels
1085            }
1086        };
1087        buffer.unmap();
1088        self.spare_readback = Some(buffer);
1089        Ok(Some(texels))
1090    }
1091}