mln_gfx/gpu.rs
1//! The interface a GPU backend implements: resources the backend owns and
2//! the caller names by id, objects prepared from them, and draws.
3//!
4//! A [`Gpu`] keeps each kind of resource in a slot map keyed by its id, so a
5//! resource holds no pointer back to the backend, and the caller decides
6//! when one goes. What a draw reads is prepared ahead of it, and checked
7//! then: a [`ShaderId`]'s pipelines ([`Gpu::create_pipeline`]), the buffers
8//! and textures it binds ([`Gpu::create_bindings`]) and its vertex and
9//! index buffers ([`Gpu::create_geometry`]). A [`Draw`] names one of each,
10//! between [`Gpu::begin_pass`] and [`Gpu::end_pass`], and the backend
11//! records it at once.
12//!
13//! Bindings use the shaders' own numbering: a buffer binds at its uniform
14//! or storage buffer id (`shaders::shader_defines`, e.g.
15//! `ID_GLOBAL_PAINT_PARAMS_UBO`), a texture at its texture id (e.g.
16//! `ID_LINE_DASH_TEXTURE`) and a vertex attribute at its attribute id (e.g.
17//! `ID_LINE_POS_NORMAL_VERTEX_ATTRIBUTE`). Each backend maps them to its own
18//! slots, groups, descriptor sets or shader locations.
19
20#[cfg(feature = "gpu-conformance")]
21pub mod conformance;
22mod ids;
23pub mod validation;
24
25use std::any::Any;
26use std::sync::Arc;
27
28use mln_util::Color;
29pub use mln_util::clip_depth::ClipDepthRange;
30use mln_util::logging::{Event, Log};
31use mln_util::size::Size;
32
33pub use self::ids::{
34 BindingsId, BufferId, GeometryId, Id, IdData, PipelineId, ReadbackId, ResourceId, SamplerId, ShaderId, SlotMap,
35 TextureId,
36};
37use crate::color_mode::{BlendFunction, Mask};
38use crate::cull_face_mode::CullFaceMode;
39use crate::depth_mode::DepthMode;
40use crate::gfx_types::{AttributeDataType, DrawModeType};
41use crate::shaders::program::Program;
42use crate::stencil_mode::{StencilMode, Test};
43use crate::texture2d::SamplerState;
44use crate::types::{DepthFunctionType, DepthMaskType, StencilOpType};
45
46/// Why a [`Gpu`] call failed.
47#[derive(Debug, thiserror::Error)]
48pub enum GpuError {
49 /// The call named a resource this backend doesn't have: one another
50 /// backend made, or one already destroyed.
51 #[error("no such {0}")]
52 UnknownId(&'static str),
53 /// A destroy of a resource that live pipelines, bindings or geometry
54 /// were made of, which debug builds refuse.
55 #[error("the {0} is in use by pipelines, bindings or geometry")]
56 InUse(&'static str),
57 /// The backend can't make what the descriptor asks for, such as a
58 /// texture format the device lacks.
59 #[error("unsupported: {0}")]
60 Unsupported(String),
61 /// The backend rejected the call: a shader that doesn't compile, a
62 /// descriptor its API refuses, bindings missing a buffer their shader
63 /// reads, or a draw past its geometry.
64 #[error("{0}")]
65 Invalid(String),
66}
67
68/// What a backend's device allows, and how the renderer draws on it.
69#[derive(Clone, Copy, Debug, PartialEq)]
70pub struct Caps {
71 /// The alignment of the offset a uniform or storage buffer binds at.
72 pub buffer_offset_alignment: u32,
73 /// The widest and tallest texture.
74 pub max_texture_size: u32,
75 /// Whether passes draw into textures of `Rgba16Float`.
76 pub half_float_render_targets: bool,
77 pub clip_depth: ClipDepthRange,
78 /// The format of the depth attachment of the passes that draw into a
79 /// render target's texture, `None` for passes without one.
80 pub render_target_depth: Option<TextureFormat>,
81 /// Whether the renderer clears the stencil inside a pass by ending it
82 /// and beginning one that clears it, rather than drawing zero over it.
83 pub clear_stencil_with_pass: bool,
84 /// Whether the device rasterizes on the CPU, as Mesa's llvmpipe and
85 /// lavapipe do. Their vertex pipeline runs once per instance, so an
86 /// instanced draw costs about as much as a draw of each instance.
87 pub cpu_rasterizer: bool,
88 /// The widest line in pixels that a pipeline of line primitives draws
89 /// ([`DynamicState::line_width`]): 1 on a device without wide lines.
90 pub max_line_width: f32,
91 /// Whether bindings bind [`Vertex`](BufferUsage::Vertex) buffers too,
92 /// which shaders read as storage buffers. The renderer draws the walls
93 /// of fill extrusions there as quads whose vertex shader reads the
94 /// bucket's vertices by vertex index, rather than as instances.
95 pub binds_vertex_buffers: bool,
96}
97
98/// How a buffer is bound.
99#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
100pub enum BufferUsage {
101 Vertex,
102 /// 16-bit indices.
103 Index,
104 Uniform,
105 Storage,
106}
107
108#[derive(Clone, Copy, Debug)]
109pub struct BufferDesc<'a> {
110 pub label: &'a str,
111 pub usage: BufferUsage,
112 /// The size in bytes, which the backend may round up.
113 pub size: u64,
114}
115
116/// The texel formats of textures and render targets.
117#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
118pub enum TextureFormat {
119 R8Unorm,
120 /// One 8-bit channel that shaders read as alpha, with red, green and
121 /// blue 0. WebGPU, which has no such format, stores it as `R8Unorm`,
122 /// which its shaders read as red.
123 A8Unorm,
124 R16Float,
125 R32Float,
126 Rgba8Unorm,
127 Rgba8UnormSrgb,
128 Bgra8Unorm,
129 Bgra8UnormSrgb,
130 Rgb10a2Unorm,
131 Rgba16Float,
132 Rgba32Float,
133 Depth32Float,
134 Depth24PlusStencil8,
135 Depth32FloatStencil8,
136}
137
138impl TextureFormat {
139 /// Every format.
140 pub const ALL: [TextureFormat; 13] = [
141 TextureFormat::R8Unorm,
142 TextureFormat::R16Float,
143 TextureFormat::R32Float,
144 TextureFormat::Rgba8Unorm,
145 TextureFormat::Rgba8UnormSrgb,
146 TextureFormat::Bgra8Unorm,
147 TextureFormat::Bgra8UnormSrgb,
148 TextureFormat::Rgb10a2Unorm,
149 TextureFormat::Rgba16Float,
150 TextureFormat::Rgba32Float,
151 TextureFormat::Depth32Float,
152 TextureFormat::Depth24PlusStencil8,
153 TextureFormat::Depth32FloatStencil8,
154 ];
155
156 /// The bytes a texel of a color format takes in
157 /// [`write_texture`](Gpu::write_texture)'s data; `None` for a depth
158 /// format.
159 #[must_use]
160 pub fn bytes_per_texel(self) -> Option<u32> {
161 match self {
162 TextureFormat::R8Unorm | TextureFormat::A8Unorm => Some(1),
163 TextureFormat::R16Float => Some(2),
164 TextureFormat::R32Float
165 | TextureFormat::Rgba8Unorm
166 | TextureFormat::Rgba8UnormSrgb
167 | TextureFormat::Bgra8Unorm
168 | TextureFormat::Bgra8UnormSrgb
169 | TextureFormat::Rgb10a2Unorm => Some(4),
170 TextureFormat::Rgba16Float => Some(8),
171 TextureFormat::Rgba32Float => Some(16),
172 TextureFormat::Depth32Float | TextureFormat::Depth24PlusStencil8 | TextureFormat::Depth32FloatStencil8 => {
173 None
174 }
175 }
176 }
177
178 #[must_use]
179 pub fn has_stencil(self) -> bool {
180 matches!(self, TextureFormat::Depth24PlusStencil8 | TextureFormat::Depth32FloatStencil8)
181 }
182}
183
184/// What a texture is used for.
185#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
186pub struct TextureUsage {
187 /// Shaders sample it, and [`write_texture`](Gpu::write_texture) fills
188 /// it.
189 pub sampled: bool,
190 /// Passes draw into it.
191 pub render_target: bool,
192 /// Its texels are copied out after a pass, for a readback.
193 pub copy_src: bool,
194}
195
196#[derive(Clone, Copy, Debug)]
197pub struct TextureDesc<'a> {
198 pub label: &'a str,
199 pub size: Size,
200 pub format: TextureFormat,
201 pub usage: TextureUsage,
202}
203
204/// The texels at `x`, `y` of `size` that a write replaces.
205#[derive(Clone, Copy, Debug, PartialEq, Eq)]
206pub struct TextureRegion {
207 pub x: u32,
208 pub y: u32,
209 pub size: Size,
210}
211
212impl TextureRegion {
213 /// The whole of a texture of `size`.
214 #[must_use]
215 pub fn whole(size: Size) -> TextureRegion {
216 TextureRegion { x: 0, y: 0, size }
217 }
218
219 /// The bytes in each row of this region of a texture of `size` and
220 /// `format`, as [`write_texture`](Gpu::write_texture) takes them and
221 /// [`take_readback`](Gpu::take_readback) returns them. Fails for a depth
222 /// format, or a region past the texture's edges.
223 pub fn bytes_per_row(&self, size: Size, format: TextureFormat) -> Result<usize, GpuError> {
224 let bytes_per_texel = format
225 .bytes_per_texel()
226 .ok_or_else(|| GpuError::Invalid(format!("{format:?} textures have no texels to copy")))?;
227 let past = |start: u32, length: u32, limit: u32| u64::from(start) + u64::from(length) > u64::from(limit);
228 if past(self.x, self.size.width, size.width) || past(self.y, self.size.height, size.height) {
229 return Err(GpuError::Invalid(format!("{self:?} of a texture of {size:?}")));
230 }
231 Ok(self.size.width as usize * bytes_per_texel as usize)
232 }
233
234 /// The bytes in each row of `data` that
235 /// [`write_texture`](Gpu::write_texture) writes to this region of a
236 /// texture of `size` and `format`. Fails as
237 /// [`bytes_per_row`](Self::bytes_per_row) does, and for `data` of
238 /// another length.
239 pub fn write_bytes_per_row(&self, size: Size, format: TextureFormat, data: &[u8]) -> Result<usize, GpuError> {
240 let bytes_per_row = self.bytes_per_row(size, format)?;
241 let expected = bytes_per_row * self.size.height as usize;
242 if data.len() != expected {
243 return Err(GpuError::Invalid(format!("a write of {} bytes to a region of {expected}", data.len())));
244 }
245 Ok(bytes_per_row)
246 }
247}
248
249/// Whether a vertex buffer advances per vertex or per instance.
250#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
251pub enum VertexStep {
252 Vertex,
253 Instance,
254}
255
256/// An attribute of a vertex buffer: the shader input with attribute id
257/// `id` reads `format` from `offset` bytes into each element. The id is of
258/// the shader's per-vertex attributes in a [`VertexStep::Vertex`] buffer,
259/// and of its per-instance ones in a [`VertexStep::Instance`] buffer.
260#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
261pub struct VertexAttribute {
262 pub id: u32,
263 pub format: AttributeDataType,
264 pub offset: u32,
265}
266
267/// The layout of the vertex buffer in one slot.
268#[derive(Clone, Debug, PartialEq, Eq, Hash)]
269pub struct VertexBufferLayout {
270 /// The bytes between elements.
271 pub stride: u32,
272 pub step: VertexStep,
273 pub attributes: Vec<VertexAttribute>,
274}
275
276/// A program and the defines it is compiled with, from the source the
277/// backend has registered for the program. Clones share the defines.
278#[derive(Clone, Debug, PartialEq, Eq, Hash)]
279pub struct ShaderKey {
280 program: &'static Program,
281 defines: Arc<[String]>,
282}
283
284impl ShaderKey {
285 /// `program` with `defines`, in any order and with repeats: names such
286 /// as `PROJECTION_GLOBE` or `HAS_UNIFORM_u_color`, or `NAME=value` for
287 /// a define with a value, such as `DEVICE_PIXEL_RATIO=2.0`.
288 #[must_use]
289 pub fn new(program: &'static Program, defines: impl IntoIterator<Item = String>) -> ShaderKey {
290 let mut defines: Vec<String> = defines.into_iter().collect();
291 defines.sort_unstable();
292 defines.dedup();
293 ShaderKey { program, defines: defines.into() }
294 }
295
296 #[must_use]
297 pub fn program(&self) -> &'static Program {
298 self.program
299 }
300
301 /// The defines, sorted.
302 #[must_use]
303 pub fn defines(&self) -> &[String] {
304 &self.defines
305 }
306
307 /// Each define's name and value, `""` for one without a value.
308 pub fn define_values(&self) -> impl Iterator<Item = (&str, &str)> {
309 self.defines.iter().map(|define| define.split_once('=').unwrap_or((define, "")))
310 }
311}
312
313/// The depth test and write of a pipeline. Its depth range is each draw's
314/// ([`DynamicState::depth_range`]).
315#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
316pub struct DepthState {
317 pub compare: DepthFunctionType,
318 pub write: bool,
319}
320
321impl From<&DepthMode> for DepthState {
322 fn from(mode: &DepthMode) -> DepthState {
323 DepthState { compare: mode.func, write: mode.mask == DepthMaskType::ReadWrite }
324 }
325}
326
327/// The stencil test and operations of a pipeline, on both faces. The
328/// reference value is each draw's ([`DynamicState::stencil_reference`]).
329#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
330pub struct StencilState {
331 /// The comparison, and the mask it reads through.
332 pub test: Test,
333 pub write_mask: u32,
334 pub fail: StencilOpType,
335 pub depth_fail: StencilOpType,
336 pub pass: StencilOpType,
337}
338
339impl StencilState {
340 /// Whether the state leaves the stencil buffer alone: it always passes
341 /// and writes nothing.
342 #[must_use]
343 pub fn is_disabled(&self) -> bool {
344 self.test == Test::Always
345 && self.write_mask == 0
346 && self.fail == StencilOpType::Keep
347 && self.depth_fail == StencilOpType::Keep
348 && self.pass == StencilOpType::Keep
349 }
350}
351
352impl From<&StencilMode> for StencilState {
353 fn from(mode: &StencilMode) -> StencilState {
354 StencilState {
355 test: mode.test,
356 write_mask: mode.mask,
357 fail: mode.fail,
358 depth_fail: mode.depth_fail,
359 pass: mode.pass,
360 }
361 }
362}
363
364/// The fixed-function state of a pipeline.
365#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
366pub struct FixedState {
367 pub primitive: DrawModeType,
368 pub cull: CullFaceMode,
369 /// The blend of both color and alpha. Its constant is each draw's
370 /// ([`DynamicState::blend_constant`]).
371 pub blend: BlendFunction,
372 pub color_mask: Mask,
373 pub depth: DepthState,
374 pub stencil: StencilState,
375}
376
377/// The formats of the attachments a pipeline draws into.
378#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
379pub struct TargetFormats {
380 /// `None` for a pass without a color attachment, which only tests and
381 /// writes depth and stencil.
382 pub color: Option<TextureFormat>,
383 pub depth_stencil: Option<TextureFormat>,
384}
385
386/// What [`Gpu::create_pipeline`] makes a pipeline of.
387#[derive(Clone, Copy, Debug)]
388pub struct PipelineDesc<'a> {
389 pub shader: ShaderId,
390 /// The layout of each vertex buffer slot, from slot 0.
391 pub vertex_buffers: &'a [VertexBufferLayout],
392 pub state: FixedState,
393 pub targets: TargetFormats,
394}
395
396/// A [`PipelineDesc`] that owns its layouts. Equal keys make
397/// interchangeable pipelines, so a caller keeps one pipeline per key.
398#[derive(Clone, Debug, PartialEq, Eq, Hash)]
399pub struct PipelineKey {
400 pub shader: ShaderId,
401 pub vertex_buffers: Vec<VertexBufferLayout>,
402 pub state: FixedState,
403 pub targets: TargetFormats,
404}
405
406impl PipelineKey {
407 #[must_use]
408 pub fn desc(&self) -> PipelineDesc<'_> {
409 PipelineDesc {
410 shader: self.shader,
411 vertex_buffers: &self.vertex_buffers,
412 state: self.state,
413 targets: self.targets,
414 }
415 }
416}
417
418/// What bindings bind at one of the shaders' ids.
419#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
420pub enum BindGroupEntry {
421 /// `size` bytes of `buffer` from `offset`, at uniform or storage buffer
422 /// id `id`. A shader reads a [`Vertex`](BufferUsage::Vertex) buffer as
423 /// a storage buffer ([`Caps::binds_vertex_buffers`]).
424 Buffer { id: u32, buffer: BufferId, offset: u64, size: u64 },
425 /// `texture`, sampled with `sampler`, at texture id `id`.
426 Texture { id: u32, texture: TextureId, sampler: SamplerId },
427}
428
429/// What [`Gpu::create_bindings`] makes bindings of.
430#[derive(Clone, Copy, Debug)]
431pub struct BindingsDesc<'a> {
432 pub label: &'a str,
433 /// The shader whose draws bind them.
434 pub shader: ShaderId,
435 /// Everything the shader reads, each id once, and possibly more, which
436 /// the bindings leave out: the frame's, the layer's and the draw's
437 /// buffers and textures together.
438 pub entries: &'a [BindGroupEntry],
439}
440
441/// What [`Gpu::create_geometry`] makes geometry of.
442#[derive(Clone, Copy, Debug)]
443pub struct GeometryDesc<'a> {
444 /// The shader whose draws read it.
445 pub shader: ShaderId,
446 /// The layout of each vertex buffer, as the pipelines that draw it have
447 /// them.
448 pub layouts: &'a [VertexBufferLayout],
449 /// The buffer of each layout, and the offset its elements start at.
450 pub vertex_buffers: &'a [(BufferId, u64)],
451 /// The 16-bit indices, from the buffer's start.
452 pub index_buffer: BufferId,
453}
454
455/// What a pass does with an attachment's contents before it draws.
456#[derive(Clone, Copy, Debug, PartialEq)]
457pub enum LoadOp<T> {
458 /// Keeps them.
459 Load,
460 /// Clears them to the value.
461 Clear(T),
462}
463
464#[derive(Clone, Copy, Debug, PartialEq)]
465pub struct ColorAttachment {
466 pub texture: TextureId,
467 pub load: LoadOp<Color>,
468}
469
470#[derive(Clone, Copy, Debug, PartialEq)]
471pub struct DepthStencilAttachment {
472 pub texture: TextureId,
473 pub depth: LoadOp<f32>,
474 /// Ignored for a format without stencil.
475 pub stencil: LoadOp<u32>,
476}
477
478/// A render pass: the attachments its draws draw into, of one size, which
479/// are stored when it ends.
480#[derive(Clone, Copy, Debug, PartialEq)]
481pub struct PassDesc<'a> {
482 pub label: &'a str,
483 pub color: Option<ColorAttachment>,
484 pub depth_stencil: Option<DepthStencilAttachment>,
485}
486
487/// The area of the attachments that draws may write to, in pixels from the
488/// top left.
489#[derive(Clone, Copy, Debug, PartialEq, Eq)]
490pub struct Scissor {
491 pub x: u32,
492 pub y: u32,
493 pub width: u32,
494 pub height: u32,
495}
496
497/// The state of a draw that its pipeline leaves to it. Draws map clip space
498/// to the pass's whole attachments.
499#[derive(Clone, Copy, Debug, PartialEq)]
500pub struct DynamicState {
501 /// The depths that clip z maps to, from near to far.
502 pub depth_range: (f32, f32),
503 pub scissor: Scissor,
504 pub stencil_reference: u32,
505 /// The constant the pipeline's `Constant*` blend factors read.
506 pub blend_constant: Color,
507 /// The width in pixels of the lines that a pipeline of line primitives
508 /// draws, up to [`Caps::max_line_width`].
509 pub line_width: f32,
510}
511
512/// A draw of `index_count` of the geometry's indices from `first_index`,
513/// offset by `base_vertex`, for each of `instance_count` instances from
514/// `first_instance`. A vertex's index, as a shader reads it, includes
515/// `base_vertex`.
516#[derive(Clone, Copy, Debug, PartialEq)]
517pub struct Draw {
518 pub pipeline: PipelineId,
519 pub bindings: BindingsId,
520 pub geometry: GeometryId,
521 pub first_index: u32,
522 pub index_count: u32,
523 pub base_vertex: i32,
524 pub first_instance: u32,
525 pub instance_count: u32,
526 /// The value shaders read as `globalIndex`: the index of the draw's
527 /// elements in the storage buffers its bindings bind.
528 pub global_index: u32,
529 pub dynamic: DynamicState,
530}
531
532/// A GPU backend. It owns what its `create_*` calls make, until
533/// [`destroy`](Gpu::destroy).
534///
535/// An id names a resource of the backend that made it, which keeps it in a
536/// [`SlotMap`]. Another backend's id names nothing there: a call that names
537/// one fails with [`GpuError::UnknownId`], and destroying it does nothing.
538///
539/// The caller destroys what was made of a resource before the resource:
540/// pipelines before their shader, and bindings and geometry before the
541/// buffers, textures, samplers and shader they were made of. In debug
542/// builds, destroying a resource that live pipelines, bindings or geometry
543/// were made of fails with [`GpuError::InUse`] and keeps it, as every
544/// backend checks with [`validation::Dependents`]; release builds don't
545/// check, and a draw with what was made of a destroyed resource is then
546/// the caller's error.
547///
548/// A destroyed resource's id is invalid from the call on: a later call that
549/// names it fails with [`GpuError::UnknownId`], and destroying it again
550/// does nothing. The backend keeps the native object alive while the work
551/// recorded before the call, flushed or not, still reads it.
552///
553/// A draw reads what the buffers and textures it binds hold when the work
554/// is flushed, or what they held when it was recorded, for each write since
555/// it was recorded; work flushed later reads what the writes wrote.
556pub trait Gpu {
557 fn caps(&self) -> &Caps;
558
559 /// Makes a buffer of `desc`, whose contents are undefined until written.
560 fn create_buffer(&mut self, desc: &BufferDesc<'_>) -> Result<BufferId, GpuError>;
561 /// Writes `data` at `offset` bytes into `buffer`. `offset` and the
562 /// length of `data` are multiples of 4.
563 fn write_buffer(&mut self, buffer: BufferId, offset: u64, data: &[u8]) -> Result<(), GpuError>;
564 /// Writes the bytes of `data`, which are in a JS array, at `offset`
565 /// bytes into `buffer`. `offset` is a multiple of 4. A length that isn't
566 /// writes zeros to the rest of the last word. A backend that can write
567 /// from the array overrides this, which copies the bytes into wasm
568 /// memory first.
569 #[cfg(target_family = "wasm")]
570 fn write_buffer_from_host(
571 &mut self,
572 buffer: BufferId,
573 offset: u64,
574 data: &mln_util::host_bytes::HostBytes,
575 ) -> Result<(), GpuError> {
576 let mut bytes = data.to_pod_vec::<u8>();
577 bytes.resize(bytes.len().next_multiple_of(4), 0);
578 self.write_buffer(buffer, offset, &bytes)
579 }
580
581 fn create_texture(&mut self, desc: &TextureDesc<'_>) -> Result<TextureId, GpuError>;
582 /// Writes `data`, the region's texels in rows from the top with no
583 /// padding, to `region` of `texture`, which is
584 /// [`sampled`](TextureUsage::sampled).
585 fn write_texture(&mut self, texture: TextureId, region: TextureRegion, data: &[u8]) -> Result<(), GpuError>;
586
587 fn create_sampler(&mut self, state: &SamplerState) -> Result<SamplerId, GpuError>;
588
589 /// Compiles the program of `key`. Fails with [`GpuError::Unsupported`]
590 /// for a program the backend has no source for.
591 fn create_shader(&mut self, key: &ShaderKey) -> Result<ShaderId, GpuError>;
592 /// Makes a pipeline of `desc`'s shader and state. Fails with
593 /// [`GpuError::Unsupported`] for a primitive the backend doesn't draw.
594 fn create_pipeline(&mut self, desc: &PipelineDesc<'_>) -> Result<PipelineId, GpuError>;
595 /// Makes the bindings of `desc`'s entries that its shader reads. Fails
596 /// as [`validation::check_bindings`] does: for an entry of a buffer of
597 /// another usage than [`Uniform`](BufferUsage::Uniform) or
598 /// [`Storage`](BufferUsage::Storage), or
599 /// [`Vertex`](BufferUsage::Vertex) where
600 /// [`Caps::binds_vertex_buffers`] says, a range outside its buffer or at
601 /// an offset the backend doesn't align, a texture that isn't
602 /// [`sampled`](TextureUsage::sampled), two entries of one id, or a
603 /// buffer or texture the shader reads and no entry binds.
604 fn create_bindings(&mut self, desc: &BindingsDesc<'_>) -> Result<BindingsId, GpuError>;
605 /// Makes geometry of `desc`'s buffers. Fails as
606 /// [`validation::check_geometry`] does: for a buffer of another usage
607 /// than [`Vertex`](BufferUsage::Vertex) or the index buffer's
608 /// [`Index`](BufferUsage::Index), an offset past a buffer's end, or a
609 /// buffer for each layout but not one.
610 fn create_geometry(&mut self, desc: &GeometryDesc<'_>) -> Result<GeometryId, GpuError>;
611
612 /// Destroys `resource`, or drops a readback without reading it. Fails,
613 /// destroying nothing, as [`validation::Dependents::destroy`] does.
614 fn destroy(&mut self, resource: ResourceId) -> Result<(), GpuError>;
615
616 /// Begins a pass over `desc`'s attachments, which are render targets of
617 /// one size, a color one and a depth one, at least one of them. Fails
618 /// while a pass is open.
619 fn begin_pass(&mut self, desc: &PassDesc<'_>) -> Result<(), GpuError>;
620 /// Whether a pass can draw into `depth_stencil`, a depth attachment,
621 /// together with any color attachment of its size. Not where it is an
622 /// attachment of a framebuffer made elsewhere, such as a window
623 /// surface's, which a pass draws into only with that framebuffer's
624 /// color.
625 fn attaches_with_any_color(&self, _depth_stencil: TextureId) -> bool {
626 true
627 }
628 /// Draws `draw` into the open pass. Fails, drawing nothing, outside a
629 /// pass, for a pipeline of other target formats than the pass's
630 /// attachments, for bindings or geometry made for another shader or
631 /// vertex layouts than the pipeline's, for indices or instances past
632 /// the geometry's buffers, and for a global index past the elements of
633 /// the storage buffers the bindings bind. The contents of the indices
634 /// are the caller's to keep inside the vertex buffers.
635 fn draw(&mut self, draw: &Draw) -> Result<(), GpuError>;
636 /// Lends the backend's own commands to `f`: inside the open pass, its
637 /// `CustomLayerPass`, which records into the pass after its draws so
638 /// far; outside a pass, its `CustomLayerEncoder`, which records after
639 /// the work so far. The docs of each say what `f` may record.
640 fn lend(&mut self, f: &mut dyn FnMut(&mut dyn Any)) -> Result<(), GpuError>;
641 /// Ends the open pass, storing its attachments.
642 fn end_pass(&mut self) -> Result<(), GpuError>;
643 /// Sends the work recorded so far to the GPU; with `wait`, then blocks
644 /// until the GPU has finished it, on a backend that can block. Fails
645 /// while a pass is open.
646 fn flush(&mut self, wait: bool) -> Result<(), GpuError>;
647
648 /// Starts copying `region` of `texture`, whose `y` counts rows from the
649 /// top as passes do, out of the GPU, once the work recorded so far is
650 /// done, which it flushes: later work and writes don't change what the
651 /// copy holds. [`take_readback`](Self::take_readback) reads it. Fails
652 /// while a pass is open, as [`validation::check_readback`] does, or
653 /// with [`GpuError::Unsupported`] for a format the backend reads no
654 /// texels of.
655 fn read_texture(&mut self, texture: TextureId, region: TextureRegion) -> Result<ReadbackId, GpuError>;
656 /// The texels that `readback` copied, in the texture's format and with
657 /// no padding, as [`write_texture`](Self::write_texture) takes them, in
658 /// rows from the top as passes count them. (A backend that stores what
659 /// passes draw bottom row first reads a written texture's rows back in
660 /// the other order.) `None` while the GPU hasn't finished the copy;
661 /// with `wait`, the call blocks until it has, except on a backend that
662 /// can't block, which returns `None` as without it. Once the call
663 /// returns texels or fails, `readback` is gone.
664 fn take_readback(&mut self, readback: ReadbackId, wait: bool) -> Result<Option<Vec<u8>>, GpuError>;
665}
666
667/// The texels of `region` of `texture` once the work recorded so far is
668/// done: [`read_texture`](Gpu::read_texture), then a
669/// [`take_readback`](Gpu::take_readback) that waits. Fails with
670/// [`GpuError::Unsupported`] on a backend that can't block.
671pub fn read_texels(
672 gpu: &mut (impl Gpu + ?Sized),
673 texture: TextureId,
674 region: TextureRegion,
675) -> Result<Vec<u8>, GpuError> {
676 let readback = gpu.read_texture(texture, region)?;
677 if let Some(texels) = gpu.take_readback(readback, true)? {
678 return Ok(texels);
679 }
680 gpu.destroy(ResourceId::Readback(readback))?;
681 Err(GpuError::Unsupported("waiting for a readback".to_owned()))
682}
683
684/// Destroys `resources`, of which no bindings or geometry were made, such as
685/// a frame target's textures and readbacks. Logs a failure, which only a
686/// caller that made bindings or geometry of one of them causes.
687pub fn destroy_unused(gpu: &mut (impl Gpu + ?Sized), resources: impl IntoIterator<Item = ResourceId>) {
688 for resource in resources {
689 if let Err(error) = gpu.destroy(resource) {
690 Log::error(Event::Render, format!("Destroying {resource:?} failed: {error}"));
691 }
692 }
693}
694
695#[cfg(test)]
696mod tests {
697 use super::*;
698 use crate::shaders::programs;
699
700 #[test]
701 fn shader_keys_ignore_define_order_and_repeats() {
702 let key = |defines: &[&str]| ShaderKey::new(&programs::FILL, defines.iter().map(|&d| d.to_owned()));
703 assert_eq!(key(&["B", "A", "B"]), key(&["A", "B"]));
704 assert_eq!(key(&["B", "A"]).defines(), ["A", "B"]);
705 assert_ne!(key(&["A"]), ShaderKey::new(&programs::LINE, ["A".to_owned()]));
706 assert_eq!(key(&["B=2.0", "A"]).define_values().collect::<Vec<_>>(), [("A", ""), ("B", "2.0")]);
707 }
708
709 #[test]
710 fn texture_writes_fit_their_region_and_texture() {
711 let size = Size { width: 4, height: 2 };
712 let region = TextureRegion { x: 1, y: 0, size: Size { width: 3, height: 2 } };
713 assert_eq!(region.write_bytes_per_row(size, TextureFormat::Rgba8Unorm, &[0; 24]).ok(), Some(12));
714 assert!(region.write_bytes_per_row(size, TextureFormat::Rgba8Unorm, &[0; 20]).is_err());
715 assert!(region.write_bytes_per_row(size, TextureFormat::Depth32Float, &[0; 24]).is_err());
716 let past = TextureRegion { x: 2, ..region };
717 assert!(past.write_bytes_per_row(size, TextureFormat::Rgba8Unorm, &[0; 24]).is_err());
718 }
719
720 #[test]
721 fn a_disabled_stencil_mode_leaves_the_stencil_alone() {
722 assert!(StencilState::from(&StencilMode::disabled()).is_disabled());
723 assert!(!StencilState::from(&StencilMode { mask: 0xFF, ..StencilMode::disabled() }).is_disabled());
724 }
725}