Skip to main content

mln_webgpu/
borrowed_target.rs

1//! A ring of the host's textures, on the device that renders into them, that
2//! frames are drawn into and given back to the host. Both sides submit to the
3//! device's one queue, which orders the host's reads after the frame and the
4//! next frame after the host's reads.
5
6use std::convert::Infallible;
7
8use mln_gfx::gpu::{GpuError, TargetFormats, TextureFormat, TextureId};
9use mln_gfx::ring::{self, RingBackend, RingTextures};
10use mln_gfx::{ConsumerSync, DepthStencilFormat, DepthStencilFormats, Error, Size, SyncKind, SyncKinds};
11
12use crate::gpu::{WebGpu, from_wgpu_format};
13use crate::renderer_backend::RendererBackend;
14
15/// A ring of the host's 2D textures, of `size` pixels and one format, with
16/// one layer, one mip level, one sample and `RENDER_ATTACHMENT` usage.
17#[derive(Clone, Debug, PartialEq)]
18pub struct BorrowedTextures {
19    pub textures: Vec<wgpu::Texture>,
20    pub size: Size,
21    /// The host's textures that frames draw their depth and stencil into
22    /// and store, one for each of `textures`, of their size and kind and one
23    /// depth and stencil format, or none for depth of the target's own.
24    pub depth_textures: Vec<wgpu::Texture>,
25}
26
27impl BorrowedTextures {
28    /// The kinds of sync with which the host can wait for a frame (the
29    /// producer's) and the target for the host's reads (the consumer's):
30    /// both share the device's queue. In a browser, which can't block on
31    /// the GPU, a frame is handed over in queue order only.
32    #[must_use]
33    pub fn sync_kinds() -> (SyncKinds, SyncKinds) {
34        let consumer = SyncKinds::of(&[SyncKind::CpuComplete, SyncKind::QueueOrder]);
35        let producer = if cfg!(target_family = "wasm") { SyncKinds::of(&[SyncKind::QueueOrder]) } else { consumer };
36        (producer, consumer)
37    }
38
39    /// The formats of the depth textures that frames draw into on `device`.
40    #[must_use]
41    pub fn depth_stencil_formats(device: &wgpu::Device) -> DepthStencilFormats {
42        let formats = DepthStencilFormats::of(&[DepthStencilFormat::Depth24Stencil8]);
43        if device.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
44            formats.with(DepthStencilFormat::Depth32FloatStencil8)
45        } else {
46            formats
47        }
48    }
49
50    /// Checks the textures against their ring.
51    ///
52    /// Fails with [`ErrorKind::InvalidArgument`](mln_gfx::ErrorKind) for a
53    /// texture of another size than the ring's, of another format than the
54    /// first, or that a frame can't render into, for depth textures that
55    /// aren't one for each texture, and with
56    /// [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) for depth textures of
57    /// no depth and stencil format.
58    pub fn check(&self) -> Result<(), Error> {
59        let Some(first) = self.textures.first() else {
60            return Err(Error::invalid_argument("a ring needs at least one texture"));
61        };
62        if let Some(depth) = self.depth_textures.first() {
63            if self.depth_textures.len() != self.textures.len() {
64                return Err(Error::invalid_argument("a ring's depth textures must be one for each of its textures"));
65            }
66            if depth_stencil_format(depth.format()).is_none() {
67                return Err(Error::unsupported("a ring's depth textures must have a depth and stencil format"));
68            }
69        }
70        for texture in self.textures.iter().chain(&self.depth_textures) {
71            let size = texture.size();
72            if (size.width, size.height) != (self.size.width, self.size.height) {
73                return Err(Error::invalid_argument("each texture's size must match the ring's physical size"));
74            }
75            let kin =
76                if texture.format().is_depth_stencil_format() { self.depth_textures.first() } else { Some(first) };
77            if Some(texture.format()) != kin.map(wgpu::Texture::format) {
78                return Err(Error::invalid_argument("the ring's textures must share a format"));
79            }
80            if !texture.usage().contains(wgpu::TextureUsages::RENDER_ATTACHMENT)
81                || texture.dimension() != wgpu::TextureDimension::D2
82                || texture.mip_level_count() != 1
83                || texture.sample_count() != 1
84                || size.depth_or_array_layers != 1
85            {
86                return Err(Error::invalid_argument(
87                    "each texture must be 2D with one layer, mip level and sample, and render-attachment usage",
88                ));
89            }
90        }
91        Ok(())
92    }
93
94    fn format(&self) -> Option<wgpu::TextureFormat> {
95        self.textures.first().map(wgpu::Texture::format)
96    }
97
98    fn depth_format(&self) -> Option<wgpu::TextureFormat> {
99        self.depth_textures.first().map(wgpu::Texture::format)
100    }
101}
102
103impl RingTextures for BorrowedTextures {
104    type Image = wgpu::Texture;
105
106    fn images(&self) -> &[wgpu::Texture] {
107        &self.textures
108    }
109
110    fn same_image(a: &wgpu::Texture, b: &wgpu::Texture) -> bool {
111        a == b
112    }
113
114    fn size(&self) -> Size {
115        self.size
116    }
117
118    fn has_depth(&self) -> bool {
119        !self.depth_textures.is_empty()
120    }
121}
122
123/// The depth and stencil format that `format` is, if it is one.
124#[must_use]
125pub fn depth_stencil_format(format: wgpu::TextureFormat) -> Option<DepthStencilFormat> {
126    match format {
127        wgpu::TextureFormat::Depth24PlusStencil8 => Some(DepthStencilFormat::Depth24Stencil8),
128        wgpu::TextureFormat::Depth32FloatStencil8 => Some(DepthStencilFormat::Depth32FloatStencil8),
129        _ => None,
130    }
131}
132
133/// Frames drawn into the host's textures, each given back to the host.
134pub type BorrowedTarget = ring::BorrowedTarget<WebGpuRing>;
135
136/// A [`BorrowedTarget`]'s part on WebGPU: both sides share the device's
137/// queue, so frames need no separate sync objects.
138pub struct WebGpuRing;
139
140impl RingBackend for WebGpuRing {
141    type Gpu = WebGpu;
142    type Renderer = RendererBackend;
143    type Textures = BorrowedTextures;
144    type Wait = Infallible;
145    type Handed = Infallible;
146
147    /// Fails as [`BorrowedTextures::check`] does, and with
148    /// [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) for a producer kind
149    /// the target can't hand over.
150    fn new(_backend: &mut RendererBackend, textures: &BorrowedTextures, producer: SyncKind) -> Result<Self, Error> {
151        textures.check()?;
152        if !BorrowedTextures::sync_kinds().0.contains(producer) {
153            return Err(Error::unsupported(format!("a WebGPU target hands frames over with no {producer:?}")));
154        }
155        Ok(WebGpuRing)
156    }
157
158    /// Fails with [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) for another
159    /// format or depth format, or depth textures where the ring had none, and
160    /// as [`BorrowedTextures::check`] does.
161    fn check_replacement(&self, current: &BorrowedTextures, next: &BorrowedTextures) -> Result<(), Error> {
162        if (next.format(), next.depth_format()) != (current.format(), current.depth_format()) {
163            return Err(Error::unsupported("a ring keeps its formats, and its depth textures or their lack"));
164        }
165        next.check()
166    }
167
168    /// Fails with [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) for a color
169    /// format that `WebGpu` has no texture of.
170    fn targets(gpu: &WebGpu, textures: &BorrowedTextures) -> Result<TargetFormats, Error> {
171        let format = textures.format();
172        let color = format
173            .and_then(from_wgpu_format)
174            .ok_or_else(|| Error::unsupported(format!("the WebGPU target draws into no {format:?}")))?;
175        let depth_stencil = match textures.depth_format() {
176            Some(depth) => from_wgpu_format(depth),
177            None => Some(if gpu.device().device().features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
178                TextureFormat::Depth32FloatStencil8
179            } else {
180                TextureFormat::Depth24PlusStencil8
181            }),
182        };
183        Ok(TargetFormats { color: Some(color), depth_stencil })
184    }
185
186    fn import(gpu: &mut WebGpu, textures: &BorrowedTextures, slot: usize, depth: bool) -> Result<TextureId, GpuError> {
187        let list = if depth { &textures.depth_textures } else { &textures.textures };
188        let texture = list.get(slot).ok_or_else(|| GpuError::Invalid(format!("the ring has no slot {slot}")))?;
189        Ok(gpu.import_texture(texture))
190    }
191
192    fn wait_for(&mut self, _gpu: &mut WebGpu, consumer: ConsumerSync) -> Result<Option<Infallible>, Error> {
193        match consumer.sync.kind {
194            SyncKind::CpuComplete | SyncKind::QueueOrder => Ok(None),
195            kind => Err(Error::unsupported(format!("the WebGPU target waits for no {kind:?}"))),
196        }
197    }
198}