Skip to main content

mln_webgpu/
surface_target.rs

1//! Frames presented to a `wgpu::Surface`. The window stays with the host,
2//! which makes the surface and reports framebuffer resizes through
3//! [`SurfaceTarget::resize`].
4
5use mln_gfx::frame::{FrameImage, FrameTarget, Handoff};
6use mln_gfx::gpu::{Gpu as _, ReadbackId, ResourceId, TargetFormats, TextureId, TextureRegion, destroy_unused};
7use mln_util::error::Error;
8use mln_util::image::PremultipliedImage;
9use mln_util::logging::{Event, Log};
10use mln_util::size::Size;
11
12use crate::device::Device;
13use crate::gpu::{WebGpu, from_wgpu_format};
14use crate::renderer_backend::RendererBackend;
15
16/// How a surface's frames composite with what is behind them. A browser's
17/// canvas shows the page where the map draws nothing, as a WebGL2 canvas
18/// does: the renderer's colors are premultiplied. Elsewhere the surface
19/// picks.
20const ALPHA_MODE: wgpu::CompositeAlphaMode =
21    if cfg!(target_family = "wasm") { wgpu::CompositeAlphaMode::PreMultiplied } else { wgpu::CompositeAlphaMode::Auto };
22
23/// What an overlay draws into ([`SurfaceTarget::set_overlay`]): the frame's
24/// surface texture, after the map and before it is presented.
25pub struct OverlayTarget<'a> {
26    pub device: &'a wgpu::Device,
27    pub queue: &'a wgpu::Queue,
28    pub view: &'a wgpu::TextureView,
29    pub format: wgpu::TextureFormat,
30    /// In physical pixels.
31    pub size: Size,
32}
33
34/// Draws over a frame ([`SurfaceTarget::set_overlay`]), submitting its own
35/// commands to the queue.
36pub type Overlay = Box<dyn FnMut(&OverlayTarget<'_>)>;
37
38/// How a [`SurfaceTarget`] presents.
39#[derive(Clone, Copy, Debug)]
40pub struct SurfaceOptions {
41    /// Present in step with the display. Off, frames are presented at once,
42    /// tearing.
43    pub cap_frame_rate: bool,
44    /// The usages the surface supports, where the host knows them better
45    /// than the device's adapter does, as for a browser's canvas, or where
46    /// the device has no adapter. Frames can be read back when they have
47    /// `COPY_SRC`.
48    pub usages: Option<wgpu::TextureUsages>,
49    /// The format to configure the surface with, in place of the device's
50    /// surface format.
51    pub format: Option<wgpu::TextureFormat>,
52}
53
54impl Default for SurfaceOptions {
55    fn default() -> Self {
56        SurfaceOptions { cap_frame_rate: true, usages: None, format: None }
57    }
58}
59
60/// Frames presented to a `wgpu::Surface`.
61///
62/// The surface is configured when a frame begins at a size it isn't
63/// configured at, so a target that replaces another on the same window
64/// configures it only after the other one has let go of it. A minimized
65/// window's frames keep the size the surface was last configured at.
66pub struct SurfaceTarget {
67    state: Box<State>,
68}
69
70struct State {
71    /// The surface texture of the frame begun, until it is presented.
72    current: Option<wgpu::SurfaceTexture>,
73    /// The depth and stencil texture, of the last frame's size.
74    depth_stencil: Option<wgpu::Texture>,
75    overlay: Option<Overlay>,
76    surface: wgpu::Surface<'static>,
77
78    format: wgpu::TextureFormat,
79    usage: wgpu::TextureUsages,
80    present_mode: wgpu::PresentMode,
81    depth_stencil_format: wgpu::TextureFormat,
82    /// The size of the frames, as the host last reported it.
83    size: Size,
84    /// The size the surface is configured at; `None` before the first frame
85    /// and once the surface has to be configured again.
86    configured: Option<Size>,
87
88    /// The textures of the frame begun, imported into the backend's
89    /// `WebGpu`: the surface texture until the frame ends, and the depth
90    /// and stencil texture until it is replaced.
91    color_import: Option<TextureId>,
92    depth_import: Option<TextureId>,
93
94    readback_requested: bool,
95    /// The readback of the frame that `request_readback` asked for, and its
96    /// size, until it has the texels.
97    pending_readback: Option<(ReadbackId, Size)>,
98    readback: Option<PremultipliedImage>,
99    device: Device,
100}
101
102impl SurfaceTarget {
103    /// A target on `backend` that presents to `surface`, made with the
104    /// instance of the backend's device, at `framebuffer_size` physical
105    /// pixels. The surface is configured with the options' format, or the
106    /// device's surface format, or else an 8-bit RGBA or BGRA format that
107    /// the surface supports: in the browser the one the canvas prefers, and
108    /// elsewhere the first of BGRA8 and RGBA8.
109    ///
110    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
111    /// device's adapter can't present to the surface or the surface supports
112    /// none of those formats, and with
113    /// [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) when the device
114    /// has neither an adapter to ask nor a surface format.
115    pub fn new(
116        backend: &RendererBackend,
117        surface: wgpu::Surface<'static>,
118        framebuffer_size: Size,
119        options: SurfaceOptions,
120    ) -> Result<SurfaceTarget, Error> {
121        let device = backend.device();
122        let (format, mut usage, vsync_present_mode) = if let Some(adapter) = device.adapter() {
123            let capabilities = surface.get_capabilities(adapter);
124            if capabilities.formats.is_empty() {
125                return Err(Error::unsupported("The WebGPU adapter can't present to the surface"));
126            }
127            let format = match options.format.or(device.surface_format()) {
128                Some(format) if capabilities.formats.contains(&format) => format,
129                Some(format) => {
130                    return Err(Error::unsupported(format!("The surface does not take the {format:?} format")));
131                }
132                None => {
133                    const RENDERED: [wgpu::TextureFormat; 4] = [
134                        wgpu::TextureFormat::Bgra8Unorm,
135                        wgpu::TextureFormat::Bgra8UnormSrgb,
136                        wgpu::TextureFormat::Rgba8Unorm,
137                        wgpu::TextureFormat::Rgba8UnormSrgb,
138                    ];
139                    // A browser lists the canvas format it prefers first
140                    // (`getPreferredCanvasFormat()`), which it presents
141                    // without a copy.
142                    let format = if cfg!(target_family = "wasm") {
143                        capabilities.formats.iter().copied().find(|f| RENDERED.contains(f))
144                    } else {
145                        RENDERED.into_iter().find(|f| capabilities.formats.contains(f))
146                    };
147                    format
148                        .ok_or_else(|| Error::unsupported("The surface takes none of the formats the map renders in"))?
149                }
150            };
151            let usage = wgpu::TextureUsages::RENDER_ATTACHMENT | (capabilities.usages & wgpu::TextureUsages::COPY_SRC);
152            // FIFO blocks in acquire and present on Wayland while the window
153            // is hidden, which stalls the host's event loop. Mailbox is in
154            // step with the display without blocking.
155            let present_mode = if capabilities.present_modes.contains(&wgpu::PresentMode::Mailbox) {
156                wgpu::PresentMode::Mailbox
157            } else {
158                wgpu::PresentMode::Fifo
159            };
160            (format, usage, present_mode)
161        } else {
162            let format = options.format.or(device.surface_format()).ok_or_else(|| {
163                Error::invalid_argument("A surface on a device without an adapter needs the device's surface format")
164            })?;
165            (format, wgpu::TextureUsages::RENDER_ATTACHMENT, wgpu::PresentMode::Fifo)
166        };
167        if let Some(usages) = options.usages {
168            usage = wgpu::TextureUsages::RENDER_ATTACHMENT | (usages & wgpu::TextureUsages::COPY_SRC);
169        }
170        let depth_stencil_format = if device.device().features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
171            wgpu::TextureFormat::Depth32FloatStencil8
172        } else {
173            wgpu::TextureFormat::Depth24PlusStencil8
174        };
175
176        Ok(SurfaceTarget {
177            state: Box::new(State {
178                current: None,
179                depth_stencil: None,
180                overlay: None,
181                surface,
182                format,
183                usage,
184                present_mode: if options.cap_frame_rate { vsync_present_mode } else { wgpu::PresentMode::Immediate },
185                depth_stencil_format,
186                size: framebuffer_size,
187                configured: None,
188                color_import: None,
189                depth_import: None,
190                readback_requested: false,
191                pending_readback: None,
192                readback: None,
193                device: device.clone(),
194            }),
195        })
196    }
197
198    /// The format the surface is configured with.
199    #[must_use]
200    pub fn format(&self) -> wgpu::TextureFormat {
201        self.state.format
202    }
203
204    /// The size of the frames, in physical pixels.
205    #[must_use]
206    pub fn size(&self) -> Size {
207        self.state.size
208    }
209
210    /// Copies the next presented frame, for [`take_readback`](Self::take_readback).
211    pub fn request_readback(&mut self) {
212        self.state.readback_requested = true;
213    }
214
215    /// The frame copied after [`request_readback`](Self::request_readback),
216    /// once it is presented and mapped: natively at once, and in the browser
217    /// on a later turn of the event loop.
218    #[must_use]
219    pub fn take_readback(&mut self, gpu: &mut WebGpu) -> Option<PremultipliedImage> {
220        self.state.finish_readback(gpu, false);
221        self.state.readback.take()
222    }
223
224    /// Draws `overlay` over each frame from now on, after the map and before
225    /// the frame is presented and read back, or stops with `None`.
226    pub fn set_overlay(&mut self, overlay: Option<Overlay>) {
227        self.state.overlay = overlay;
228    }
229}
230
231impl State {
232    /// The size of the frame's surface texture, which is acquired, first
233    /// configuring the surface, if the frame has none yet. `None` when the
234    /// surface gives none, and the frame is skipped.
235    fn acquire(&mut self) -> Option<Size> {
236        let size_of = |texture: &wgpu::SurfaceTexture| Size::new(texture.texture.width(), texture.texture.height());
237        if let Some(current) = &self.current {
238            return Some(size_of(current));
239        }
240        let size = self.size;
241        // wgpu rejects a configuration without area, which a minimized
242        // window reports.
243        if self.configured != Some(size) && size.width != 0 && size.height != 0 {
244            self.surface.configure(
245                self.device.device(),
246                &wgpu::SurfaceConfiguration {
247                    usage: self.usage,
248                    format: self.format,
249                    width: size.width,
250                    height: size.height,
251                    present_mode: self.present_mode,
252                    desired_maximum_frame_latency: 2,
253                    alpha_mode: ALPHA_MODE,
254                    view_formats: vec![self.format],
255                    color_space: wgpu::SurfaceColorSpace::Auto,
256                },
257            );
258            self.configured = Some(size);
259        }
260        self.configured?;
261        let texture = match self.surface.get_current_texture() {
262            wgpu::CurrentSurfaceTexture::Success(texture) | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
263            wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
264                self.configured = None;
265                return None;
266            }
267            wgpu::CurrentSurfaceTexture::Timeout
268            | wgpu::CurrentSurfaceTexture::Occluded
269            | wgpu::CurrentSurfaceTexture::Validation => return None,
270        };
271        Some(size_of(self.current.insert(texture)))
272    }
273
274    /// The depth and stencil texture of `size`, imported into `gpu`.
275    fn depth_stencil_import(&mut self, gpu: &mut WebGpu, size: Size) -> TextureId {
276        let texture = match self.depth_stencil.take() {
277            Some(texture) if (texture.width(), texture.height()) == (size.width, size.height) => texture,
278            _ => {
279                if let Some(import) = self.depth_import.take() {
280                    destroy_unused(gpu, [ResourceId::Texture(import)]);
281                }
282                self.device.device().create_texture(&wgpu::TextureDescriptor {
283                    label: Some("surface depth and stencil"),
284                    size: wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1 },
285                    mip_level_count: 1,
286                    sample_count: 1,
287                    dimension: wgpu::TextureDimension::D2,
288                    format: self.depth_stencil_format,
289                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
290                    view_formats: &[],
291                })
292            }
293        };
294        let import = *self.depth_import.get_or_insert_with(|| gpu.import_texture(&texture));
295        self.depth_stencil = Some(texture);
296        import
297    }
298
299    /// Starts reading `texture`, the surface's, back.
300    fn read_back(&mut self, gpu: &mut WebGpu, texture: &wgpu::Texture) {
301        if !self.usage.contains(wgpu::TextureUsages::COPY_SRC) {
302            Log::warning(Event::Render, "WebGPU: the surface does not support readback (no COPY_SRC)");
303            return;
304        }
305        let size = Size::new(texture.width(), texture.height());
306        let imported = gpu.import_texture(texture);
307        let readback = gpu.read_texture(imported, TextureRegion::whole(size));
308        destroy_unused(gpu, [ResourceId::Texture(imported)]);
309        match readback {
310            Ok(readback) => {
311                if let Some((stale, _)) = self.pending_readback.replace((readback, size)) {
312                    destroy_unused(gpu, [ResourceId::Readback(stale)]);
313                }
314            }
315            Err(error) => Log::error(Event::Render, format!("WebGPU: reading the frame back failed: {error}")),
316        }
317    }
318
319    /// Turns the pending readback into an RGBA image once it has the
320    /// texels, waiting for them with `wait` where the platform can.
321    fn finish_readback(&mut self, gpu: &mut WebGpu, wait: bool) {
322        let Some((readback, size)) = self.pending_readback.take() else {
323            return;
324        };
325        let mut texels = match gpu.take_readback(readback, wait) {
326            Ok(Some(texels)) => texels,
327            Ok(None) => {
328                self.pending_readback = Some((readback, size));
329                return;
330            }
331            Err(error) => {
332                return Log::error(Event::Render, format!("WebGPU: reading the frame back failed: {error}"));
333            }
334        };
335        if matches!(self.format, wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb) {
336            for texel in texels.as_chunks_mut::<4>().0 {
337                texel.swap(0, 2);
338            }
339        }
340        self.readback = Some(PremultipliedImage::from_vec(size, texels));
341    }
342}
343
344impl FrameTarget for SurfaceTarget {
345    type Gpu = WebGpu;
346
347    /// Draws the next frame at `size` physical pixels.
348    fn resize(&mut self, _gpu: &mut WebGpu, size: Size) {
349        self.state.size = size;
350    }
351
352    /// Acquires the surface's next texture, unless the frame has one. A
353    /// frame without one is skipped.
354    fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
355        self.state.begin_frame(gpu)
356    }
357
358    /// Draws the overlay over the frame, reads it back if that was asked
359    /// for, and presents it.
360    fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
361        self.state.end_frame(gpu)
362    }
363
364    fn tear_down(&mut self, gpu: &mut WebGpu) {
365        let state = &mut *self.state;
366        if let Some((readback, _)) = state.pending_readback.take() {
367            destroy_unused(gpu, [ResourceId::Readback(readback)]);
368        }
369        let imports = [state.color_import.take(), state.depth_import.take()].into_iter().flatten();
370        destroy_unused(gpu, imports.map(ResourceId::Texture));
371    }
372}
373
374impl State {
375    fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
376        let size = self.acquire()?;
377        let depth_stencil = self.depth_stencil_import(gpu, size);
378        let current = self.current.as_ref()?;
379        let color = *self.color_import.get_or_insert_with(|| gpu.import_texture(&current.texture));
380        let targets = TargetFormats {
381            color: from_wgpu_format(self.format),
382            depth_stencil: from_wgpu_format(self.depth_stencil_format),
383        };
384        Some(FrameImage { size, color, depth_stencil: Some(depth_stencil), targets })
385    }
386
387    fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
388        if let Some(color) = self.color_import.take() {
389            destroy_unused(gpu, [ResourceId::Texture(color)]);
390        }
391        let Some(current) = self.current.take() else {
392            return Handoff::Dropped;
393        };
394        if let Some(overlay) = self.overlay.as_mut() {
395            let view = current.texture.create_view(&wgpu::TextureViewDescriptor::default());
396            overlay(&OverlayTarget {
397                device: self.device.device(),
398                queue: self.device.queue(),
399                view: &view,
400                format: self.format,
401                size: Size::new(current.texture.width(), current.texture.height()),
402            });
403        }
404        if std::mem::take(&mut self.readback_requested) {
405            self.read_back(gpu, &current.texture);
406            // Natively this waits for the copy; in the browser the event
407            // loop maps it later.
408            self.finish_readback(gpu, true);
409        }
410        self.device.queue().present(current);
411        Handoff::Presented
412    }
413}
414
415impl Drop for State {
416    fn drop(&mut self) {
417        // The surface texture goes before the surface.
418        drop(self.current.take());
419        drop(self.depth_stencil.take());
420        drop(self.overlay.take());
421        // Runs the callbacks still outstanding.
422        let _ = self.device.device().poll(wgpu::PollType::Poll);
423    }
424}