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