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 mln_gfx::frame::{FrameImage, FrameTarget, Handoff};
7use mln_gfx::gpu::{Gpu as _, ResourceId, TargetFormats, destroy_unused};
8use mln_gfx::{ConsumerSync, DepthStencilFormat, DepthStencilFormats, GpuSync, SyncKind, SyncKinds};
9use mln_util::error::Error;
10use mln_util::logging::{Event, Log};
11use mln_util::size::Size;
12
13use crate::gpu::{WebGpu, from_wgpu_format};
14use crate::renderer_backend::RendererBackend;
15
16/// A ring of the host's 2D textures, of `size` pixels and one format, with
17/// one layer, one mip level, one sample and `RENDER_ATTACHMENT` usage.
18#[derive(Clone, Debug, PartialEq)]
19pub struct BorrowedTextures {
20    pub textures: Vec<wgpu::Texture>,
21    pub size: Size,
22    /// The host's textures that frames draw their depth and stencil into
23    /// and store, one for each of `textures`, of their size and kind and one
24    /// depth and stencil format, or none for depth of the target's own.
25    pub depth_textures: Vec<wgpu::Texture>,
26}
27
28impl BorrowedTextures {
29    /// The kinds of sync with which the host can wait for a frame (the
30    /// producer's) and the target for the host's reads (the consumer's):
31    /// both share the device's queue.
32    #[must_use]
33    pub fn sync_kinds() -> (SyncKinds, SyncKinds) {
34        let kinds = SyncKinds::of(&[SyncKind::CpuComplete, SyncKind::QueueOrder]);
35        (kinds, kinds)
36    }
37
38    /// The formats of the depth textures that frames draw into on `device`.
39    #[must_use]
40    pub fn depth_stencil_formats(device: &wgpu::Device) -> DepthStencilFormats {
41        let formats = DepthStencilFormats::of(&[DepthStencilFormat::Depth24Stencil8]);
42        if device.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
43            formats.with(DepthStencilFormat::Depth32FloatStencil8)
44        } else {
45            formats
46        }
47    }
48
49    /// Checks the textures against their ring.
50    ///
51    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a
52    /// texture of another size than the ring's, of another format than the
53    /// first, or that a frame can't render into, for depth textures that
54    /// aren't one for each texture, and with
55    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) for depth textures of
56    /// no depth and stencil format.
57    pub fn check(&self) -> Result<(), Error> {
58        let Some(first) = self.textures.first() else {
59            return Err(Error::invalid_argument("a ring needs at least one texture"));
60        };
61        if let Some(depth) = self.depth_textures.first() {
62            if self.depth_textures.len() != self.textures.len() {
63                return Err(Error::invalid_argument("a ring's depth textures must be one for each of its textures"));
64            }
65            if depth_stencil_format(depth.format()).is_none() {
66                return Err(Error::unsupported("a ring's depth textures must have a depth and stencil format"));
67            }
68        }
69        for texture in self.textures.iter().chain(&self.depth_textures) {
70            let size = texture.size();
71            if (size.width, size.height) != (self.size.width, self.size.height) {
72                return Err(Error::invalid_argument("each texture's size must match the ring's physical size"));
73            }
74            let kin =
75                if texture.format().is_depth_stencil_format() { self.depth_textures.first() } else { Some(first) };
76            if Some(texture.format()) != kin.map(wgpu::Texture::format) {
77                return Err(Error::invalid_argument("the ring's textures must share a format"));
78            }
79            if !texture.usage().contains(wgpu::TextureUsages::RENDER_ATTACHMENT)
80                || texture.dimension() != wgpu::TextureDimension::D2
81                || texture.mip_level_count() != 1
82                || texture.sample_count() != 1
83                || size.depth_or_array_layers != 1
84            {
85                return Err(Error::invalid_argument(
86                    "each texture must be 2D with one layer, mip level and sample, and render-attachment usage",
87                ));
88            }
89        }
90        Ok(())
91    }
92
93    fn format(&self) -> Option<wgpu::TextureFormat> {
94        self.textures.first().map(wgpu::Texture::format)
95    }
96
97    fn depth_format(&self) -> Option<wgpu::TextureFormat> {
98        self.depth_textures.first().map(wgpu::Texture::format)
99    }
100}
101
102/// The depth and stencil format that `format` is, if it is one.
103#[must_use]
104pub fn depth_stencil_format(format: wgpu::TextureFormat) -> Option<DepthStencilFormat> {
105    match format {
106        wgpu::TextureFormat::Depth24PlusStencil8 => Some(DepthStencilFormat::Depth24Stencil8),
107        wgpu::TextureFormat::Depth32FloatStencil8 => Some(DepthStencilFormat::Depth32FloatStencil8),
108        _ => None,
109    }
110}
111
112/// Frames drawn into the host's textures, each given back to the host.
113pub struct BorrowedTarget {
114    device: wgpu::Device,
115    /// `None` once the target let go of them.
116    textures: Option<BorrowedTextures>,
117    /// The slot that the next frame draws into.
118    selected: usize,
119    producer: SyncKind,
120    depth_stencil_format: wgpu::TextureFormat,
121    /// The target's own depth and stencil texture, where the host gave
122    /// none.
123    depth_stencil: Option<wgpu::Texture>,
124    /// The slot of the frame begun and its textures, imported into the
125    /// backend's `WebGpu`, until the frame ends.
126    imports: Option<(usize, FrameImage)>,
127}
128
129impl BorrowedTarget {
130    /// A target on `backend` that draws into `textures`, which are of its
131    /// device, and hands each frame to the host with sync of the kind
132    /// `producer`, one of [`BorrowedTextures::sync_kinds`]'s.
133    ///
134    /// Fails as [`BorrowedTextures::check`] does, and with
135    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a producer kind
136    /// the target can't hand over.
137    pub fn new(backend: &RendererBackend, textures: BorrowedTextures, producer: SyncKind) -> Result<Self, Error> {
138        textures.check()?;
139        if !BorrowedTextures::sync_kinds().0.contains(producer) {
140            return Err(Error::unsupported(format!("a WebGPU target hands frames over with no {producer:?}")));
141        }
142        let device = backend.device().device().clone();
143        let depth_stencil_format = if device.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
144            wgpu::TextureFormat::Depth32FloatStencil8
145        } else {
146            wgpu::TextureFormat::Depth24PlusStencil8
147        };
148        Ok(BorrowedTarget {
149            device,
150            textures: Some(textures),
151            selected: 0,
152            producer,
153            depth_stencil_format,
154            depth_stencil: None,
155            imports: None,
156        })
157    }
158
159    /// Has the next frame draw into the texture at `slot`.
160    pub fn select(&mut self, slot: usize) {
161        self.selected = slot;
162    }
163
164    /// The host gave the texture at `slot` back. The host's reads went to
165    /// the queue before the next frame does, or have finished.
166    #[expect(
167        clippy::needless_pass_by_value,
168        reason = "the release takes the host's sync, as every backend's does, and drops it"
169    )]
170    pub fn release(&mut self, _slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
171        match consumer.sync.kind {
172            SyncKind::CpuComplete | SyncKind::QueueOrder => Ok(()),
173            kind => Err(Error::unsupported(format!("the WebGPU target waits for no {kind:?}"))),
174        }
175    }
176
177    /// The host gave up the texture at `slot`, which is never drawn into
178    /// again.
179    pub fn discard(&mut self, _slot: usize) {}
180
181    /// Draws into `textures` from now on, which must be as many, of the
182    /// ring's format. Returns the sync after which the host may use the old
183    /// textures, as [`release_textures`](Self::release_textures) does.
184    ///
185    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for
186    /// another number of textures, with
187    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) for another format,
188    /// with [`ErrorKind::InvalidState`](mln_util::ErrorKind) once the target
189    /// let go of its textures, as [`BorrowedTextures::check`] does, and as
190    /// [`release_textures`](Self::release_textures) does. The target then
191    /// keeps its textures.
192    pub fn replace(&mut self, gpu: &mut WebGpu, textures: BorrowedTextures) -> Result<GpuSync, Error> {
193        let Some(current) = &self.textures else {
194            return Err(Error::invalid_state("the ring let go of its textures"));
195        };
196        if textures.textures.len() != current.textures.len() {
197            return Err(Error::invalid_argument("a ring keeps its depth"));
198        }
199        if (textures.format(), textures.depth_format()) != (current.format(), current.depth_format()) {
200            return Err(Error::unsupported("a ring keeps its formats, and its depth textures or their lack"));
201        }
202        textures.check()?;
203        let sync = self.end_work(gpu)?;
204        self.textures = Some(textures);
205        Ok(sync)
206    }
207
208    /// Lets go of the textures, and returns the sync after which the host
209    /// may use them, of the producer's kind. The target draws no frame
210    /// after.
211    ///
212    /// Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind) once the
213    /// target let go of its textures, and with
214    /// [`ErrorKind::Native`](mln_util::ErrorKind) when it can't submit its
215    /// work, or wait for it for [`SyncKind::CpuComplete`]. It keeps its
216    /// textures then.
217    pub fn release_textures(&mut self, gpu: &mut WebGpu) -> Result<GpuSync, Error> {
218        if self.textures.is_none() {
219            return Err(Error::invalid_state("the ring let go of its textures"));
220        }
221        let sync = self.end_work(gpu)?;
222        self.textures = None;
223        self.depth_stencil = None;
224        Ok(sync)
225    }
226
227    /// Forgets a frame begun on the textures, submits the work recorded so
228    /// far, and returns the sync that ends it.
229    fn end_work(&mut self, gpu: &mut WebGpu) -> Result<GpuSync, Error> {
230        if let Some((_, image)) = self.imports.take() {
231            destroy_imports(gpu, image);
232        }
233        let wait = self.producer == SyncKind::CpuComplete;
234        gpu.flush(wait).map_err(|error| Error::native(format!("Submitting a ring's frames failed: {error}")))?;
235        Ok(GpuSync::of(self.producer))
236    }
237}
238
239/// A target's own depth and stencil texture of `size` and `format`, made
240/// on `device` in `own` when it has none of that size.
241fn own_depth_stencil(
242    device: &wgpu::Device,
243    format: wgpu::TextureFormat,
244    own: &mut Option<wgpu::Texture>,
245    size: Size,
246) -> wgpu::Texture {
247    match own {
248        Some(texture) if (texture.width(), texture.height()) == (size.width, size.height) => texture.clone(),
249        _ => own
250            .insert(device.create_texture(&wgpu::TextureDescriptor {
251                label: Some("borrowed ring depth and stencil"),
252                size: wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1 },
253                mip_level_count: 1,
254                sample_count: 1,
255                dimension: wgpu::TextureDimension::D2,
256                format,
257                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
258                view_formats: &[],
259            }))
260            .clone(),
261    }
262}
263
264fn destroy_imports(gpu: &mut WebGpu, image: FrameImage) {
265    let imports = [Some(image.color), image.depth_stencil].into_iter().flatten();
266    destroy_unused(gpu, imports.map(ResourceId::Texture));
267}
268
269impl FrameTarget for BorrowedTarget {
270    type Gpu = WebGpu;
271
272    fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
273        let slot = self.selected;
274        match self.imports {
275            Some((imported, image)) if imported == slot => return Some(image),
276            // A slot was selected since the frame began.
277            Some((_, image)) => {
278                self.imports = None;
279                destroy_imports(gpu, image);
280            }
281            None => {}
282        }
283        let textures = self.textures.as_ref()?;
284        let texture = textures.textures.get(slot)?.clone();
285        // The host's depth and stencil texture of the slot, or the
286        // target's own of the ring's size.
287        let depth_stencil = match textures.depth_textures.get(slot) {
288            Some(depth) => depth.clone(),
289            None => own_depth_stencil(&self.device, self.depth_stencil_format, &mut self.depth_stencil, textures.size),
290        };
291        let image = FrameImage {
292            size: textures.size,
293            color: gpu.import_texture(&texture),
294            depth_stencil: Some(gpu.import_texture(&depth_stencil)),
295            targets: TargetFormats {
296                color: from_wgpu_format(texture.format()),
297                depth_stencil: from_wgpu_format(depth_stencil.format()),
298            },
299        };
300        self.imports = Some((slot, image));
301        Some(image)
302    }
303
304    fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
305        let Some((_, image)) = self.imports.take() else {
306            return Handoff::Dropped;
307        };
308        destroy_imports(gpu, image);
309        let sync = if self.producer == SyncKind::QueueOrder {
310            GpuSync::of(SyncKind::QueueOrder)
311        } else {
312            if let Err(error) = gpu.flush(true) {
313                Log::error(Event::Render, format!("WebGPU: waiting for a borrowed texture's frame failed: {error}"));
314                return Handoff::Dropped;
315            }
316            GpuSync::of(SyncKind::CpuComplete)
317        };
318        Handoff::GivenBack { slot: self.selected, sync }
319    }
320
321    /// Forgets the textures of a frame begun and not ended.
322    fn tear_down(&mut self, gpu: &mut WebGpu) {
323        if let Some((_, image)) = self.imports.take() {
324            destroy_imports(gpu, image);
325        }
326    }
327}