mln-rs-webgpu 0.0.17

Part of mln-rs, a Rust port of the MapLibre Native map rendering core. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Frames presented to a `wgpu::Surface`. The window stays with the host,
//! which makes the surface and reports framebuffer resizes through
//! [`SurfaceTarget::resize`].

use mln_gfx::frame::{FrameImage, FrameTarget, Handoff};
use mln_gfx::gpu::{Gpu as _, ReadbackId, ResourceId, TargetFormats, TextureId, TextureRegion, destroy_unused};
use mln_gfx::{Error, FramePixels, Size};

use crate::device::Device;
use crate::gpu::{WebGpu, from_wgpu_format};
use crate::log_target;
use crate::renderer_backend::RendererBackend;

/// How a surface's frames composite with what is behind them. A browser's
/// canvas shows the page where the map draws nothing, as a WebGL2 canvas
/// does: the renderer's colors are premultiplied. Elsewhere the surface
/// picks.
const ALPHA_MODE: wgpu::CompositeAlphaMode =
    if cfg!(target_family = "wasm") { wgpu::CompositeAlphaMode::PreMultiplied } else { wgpu::CompositeAlphaMode::Auto };

/// What an overlay draws into ([`SurfaceTarget::set_overlay`]): the frame's
/// surface texture, after the map and before it is presented.
pub struct OverlayTarget<'a> {
    pub device: &'a wgpu::Device,
    pub queue: &'a wgpu::Queue,
    pub view: &'a wgpu::TextureView,
    pub format: wgpu::TextureFormat,
    /// In physical pixels.
    pub size: Size,
}

/// Draws over a frame ([`SurfaceTarget::set_overlay`]), submitting its own
/// commands to the queue.
pub type Overlay = Box<dyn FnMut(&OverlayTarget<'_>)>;

/// How a [`SurfaceTarget`] presents.
#[derive(Clone, Copy, Debug)]
pub struct SurfaceOptions {
    /// Present in step with the display. Off, frames are presented at once,
    /// tearing.
    pub cap_frame_rate: bool,
    /// The usages the surface supports, where the host knows them better
    /// than the device's adapter does, as for a browser's canvas, or where
    /// the device has no adapter. Frames can be read back when they have
    /// `COPY_SRC`.
    pub usages: Option<wgpu::TextureUsages>,
    /// The format to configure the surface with, in place of the device's
    /// surface format.
    pub format: Option<wgpu::TextureFormat>,
}

impl Default for SurfaceOptions {
    fn default() -> Self {
        SurfaceOptions { cap_frame_rate: true, usages: None, format: None }
    }
}

/// Frames presented to a `wgpu::Surface`.
///
/// The surface is configured when a frame begins at a size it isn't
/// configured at, so a target that replaces another on the same window
/// configures it only after the other one has let go of it. A minimized
/// window's frames keep the size the surface was last configured at.
pub struct SurfaceTarget {
    state: Box<State>,
}

struct State {
    /// The surface texture of the frame begun, until it is presented.
    current: Option<wgpu::SurfaceTexture>,
    /// The depth and stencil texture, of the last frame's size.
    depth_stencil: Option<wgpu::Texture>,
    overlay: Option<Overlay>,
    surface: wgpu::Surface<'static>,

    format: wgpu::TextureFormat,
    usage: wgpu::TextureUsages,
    present_mode: wgpu::PresentMode,
    depth_stencil_format: wgpu::TextureFormat,
    /// The size of the frames, as the host last reported it.
    size: Size,
    /// The size the surface is configured at; `None` before the first frame
    /// and once the surface has to be configured again.
    configured: Option<Size>,

    /// The textures of the frame begun, imported into the backend's
    /// `WebGpu`: the surface texture until the frame ends, and the depth
    /// and stencil texture until it is replaced.
    color_import: Option<TextureId>,
    depth_import: Option<TextureId>,

    readback_requested: bool,
    /// The readback of the frame that `request_readback` asked for, and its
    /// size, until it has the texels.
    pending_readback: Option<(ReadbackId, Size)>,
    readback: Option<FramePixels>,
    device: Device,
}

impl SurfaceTarget {
    /// A target on `backend` that presents to `surface`, made with the
    /// instance of the backend's device, at `framebuffer_size` physical
    /// pixels. The surface is configured with the options' format, or the
    /// device's surface format, or else an 8-bit RGBA or BGRA format that
    /// the surface supports: in the browser the one the canvas prefers, and
    /// elsewhere the first of BGRA8 and RGBA8.
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) when the
    /// device's adapter can't present to the surface or the surface supports
    /// none of those formats, and with
    /// [`ErrorKind::InvalidArgument`](mln_gfx::ErrorKind) when the device
    /// has neither an adapter to ask nor a surface format.
    pub fn new(
        backend: &RendererBackend,
        surface: wgpu::Surface<'static>,
        framebuffer_size: Size,
        options: SurfaceOptions,
    ) -> Result<SurfaceTarget, Error> {
        let device = backend.device();
        let (format, mut usage, vsync_present_mode) = if let Some(adapter) = device.adapter() {
            let capabilities = surface.get_capabilities(adapter);
            if capabilities.formats.is_empty() {
                return Err(Error::unsupported("The WebGPU adapter can't present to the surface"));
            }
            let format = match options.format.or(device.surface_format()) {
                Some(format) if capabilities.formats.contains(&format) => format,
                Some(format) => {
                    return Err(Error::unsupported(format!("The surface does not take the {format:?} format")));
                }
                None => {
                    const RENDERED: [wgpu::TextureFormat; 4] = [
                        wgpu::TextureFormat::Bgra8Unorm,
                        wgpu::TextureFormat::Bgra8UnormSrgb,
                        wgpu::TextureFormat::Rgba8Unorm,
                        wgpu::TextureFormat::Rgba8UnormSrgb,
                    ];
                    // A browser lists the canvas format it prefers first
                    // (`getPreferredCanvasFormat()`), which it presents
                    // without a copy.
                    let format = if cfg!(target_family = "wasm") {
                        capabilities.formats.iter().copied().find(|f| RENDERED.contains(f))
                    } else {
                        RENDERED.into_iter().find(|f| capabilities.formats.contains(f))
                    };
                    format
                        .ok_or_else(|| Error::unsupported("The surface takes none of the formats the map renders in"))?
                }
            };
            let usage = wgpu::TextureUsages::RENDER_ATTACHMENT | (capabilities.usages & wgpu::TextureUsages::COPY_SRC);
            // FIFO blocks in acquire and present on Wayland while the window
            // is hidden, which stalls the host's event loop. Mailbox is in
            // step with the display without blocking.
            let present_mode = if capabilities.present_modes.contains(&wgpu::PresentMode::Mailbox) {
                wgpu::PresentMode::Mailbox
            } else {
                wgpu::PresentMode::Fifo
            };
            (format, usage, present_mode)
        } else {
            let format = options.format.or(device.surface_format()).ok_or_else(|| {
                Error::invalid_argument("A surface on a device without an adapter needs the device's surface format")
            })?;
            (format, wgpu::TextureUsages::RENDER_ATTACHMENT, wgpu::PresentMode::Fifo)
        };
        if let Some(usages) = options.usages {
            usage = wgpu::TextureUsages::RENDER_ATTACHMENT | (usages & wgpu::TextureUsages::COPY_SRC);
        }
        let depth_stencil_format = if device.device().features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
            wgpu::TextureFormat::Depth32FloatStencil8
        } else {
            wgpu::TextureFormat::Depth24PlusStencil8
        };

        Ok(SurfaceTarget {
            state: Box::new(State {
                current: None,
                depth_stencil: None,
                overlay: None,
                surface,
                format,
                usage,
                present_mode: if options.cap_frame_rate { vsync_present_mode } else { wgpu::PresentMode::Immediate },
                depth_stencil_format,
                size: framebuffer_size,
                configured: None,
                color_import: None,
                depth_import: None,
                readback_requested: false,
                pending_readback: None,
                readback: None,
                device: device.clone(),
            }),
        })
    }

    /// The format the surface is configured with.
    #[must_use]
    pub fn format(&self) -> wgpu::TextureFormat {
        self.state.format
    }

    /// The size of the frames, in physical pixels.
    #[must_use]
    pub fn size(&self) -> Size {
        self.state.size
    }

    /// Copies the next presented frame, for [`take_readback`](Self::take_readback).
    pub fn request_readback(&mut self) {
        self.state.readback_requested = true;
    }

    /// The frame copied after [`request_readback`](Self::request_readback),
    /// once it is presented and mapped: natively at once, and in the browser
    /// on a later turn of the event loop.
    #[must_use]
    pub fn take_readback(&mut self, gpu: &mut WebGpu) -> Option<FramePixels> {
        self.state.finish_readback(gpu, false);
        self.state.readback.take()
    }

    /// Draws `overlay` over each frame from now on, after the map and before
    /// the frame is presented and read back, or stops with `None`.
    pub fn set_overlay(&mut self, overlay: Option<Overlay>) {
        self.state.overlay = overlay;
    }
}

impl State {
    /// The size of the frame's surface texture, which is acquired, first
    /// configuring the surface, if the frame has none yet. `None` when the
    /// surface gives none, and the frame is skipped.
    fn acquire(&mut self) -> Option<Size> {
        let size_of = |texture: &wgpu::SurfaceTexture| Size::new(texture.texture.width(), texture.texture.height());
        if let Some(current) = &self.current {
            return Some(size_of(current));
        }
        let size = self.size;
        // wgpu rejects a configuration without area, which a minimized
        // window reports.
        if self.configured != Some(size) && size.width != 0 && size.height != 0 {
            self.surface.configure(
                self.device.device(),
                &wgpu::SurfaceConfiguration {
                    usage: self.usage,
                    format: self.format,
                    width: size.width,
                    height: size.height,
                    present_mode: self.present_mode,
                    desired_maximum_frame_latency: 2,
                    alpha_mode: ALPHA_MODE,
                    view_formats: vec![self.format],
                    color_space: wgpu::SurfaceColorSpace::Auto,
                },
            );
            self.configured = Some(size);
        }
        self.configured?;
        let texture = match self.surface.get_current_texture() {
            wgpu::CurrentSurfaceTexture::Success(texture) | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
            wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
                self.configured = None;
                return None;
            }
            wgpu::CurrentSurfaceTexture::Timeout
            | wgpu::CurrentSurfaceTexture::Occluded
            | wgpu::CurrentSurfaceTexture::Validation => return None,
        };
        Some(size_of(self.current.insert(texture)))
    }

    /// The depth and stencil texture of `size`, imported into `gpu`.
    fn depth_stencil_import(&mut self, gpu: &mut WebGpu, size: Size) -> TextureId {
        let texture = match self.depth_stencil.take() {
            Some(texture) if (texture.width(), texture.height()) == (size.width, size.height) => texture,
            _ => {
                if let Some(import) = self.depth_import.take() {
                    destroy_unused(gpu, [ResourceId::Texture(import)]);
                }
                self.device.device().create_texture(&wgpu::TextureDescriptor {
                    label: Some("surface depth and stencil"),
                    size: wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1 },
                    mip_level_count: 1,
                    sample_count: 1,
                    dimension: wgpu::TextureDimension::D2,
                    format: self.depth_stencil_format,
                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                    view_formats: &[],
                })
            }
        };
        let import = *self.depth_import.get_or_insert_with(|| gpu.import_texture(&texture));
        self.depth_stencil = Some(texture);
        import
    }

    /// Starts reading `texture`, the surface's, back.
    fn read_back(&mut self, gpu: &mut WebGpu, texture: &wgpu::Texture) {
        if !self.usage.contains(wgpu::TextureUsages::COPY_SRC) {
            log::warn!(target: log_target::RENDER, "WebGPU: the surface does not support readback (no COPY_SRC)");
            return;
        }
        let size = Size::new(texture.width(), texture.height());
        let imported = gpu.import_texture(texture);
        let readback = gpu.read_texture(imported, TextureRegion::whole(size));
        destroy_unused(gpu, [ResourceId::Texture(imported)]);
        match readback {
            Ok(readback) => {
                if let Some((stale, _)) = self.pending_readback.replace((readback, size)) {
                    destroy_unused(gpu, [ResourceId::Readback(stale)]);
                }
            }
            Err(error) => log::error!(target: log_target::RENDER, "WebGPU: reading the frame back failed: {error}"),
        }
    }

    /// Turns the pending readback into an RGBA image once it has the
    /// texels, waiting for them with `wait` where the platform can.
    fn finish_readback(&mut self, gpu: &mut WebGpu, wait: bool) {
        let Some((readback, size)) = self.pending_readback.take() else {
            return;
        };
        let mut texels = match gpu.take_readback(readback, wait) {
            Ok(Some(texels)) => texels,
            Ok(None) => {
                self.pending_readback = Some((readback, size));
                return;
            }
            Err(error) => {
                return log::error!(target: log_target::RENDER, "WebGPU: reading the frame back failed: {error}");
            }
        };
        if matches!(self.format, wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb) {
            for texel in texels.as_chunks_mut::<4>().0 {
                texel.swap(0, 2);
            }
        }
        self.readback = Some(FramePixels { size, data: texels });
    }
}

impl FrameTarget for SurfaceTarget {
    type Gpu = WebGpu;

    /// Draws the next frame at `size` physical pixels.
    fn resize(&mut self, _gpu: &mut WebGpu, size: Size) {
        self.state.size = size;
    }

    /// Acquires the surface's next texture, unless the frame has one. A
    /// frame without one is skipped.
    fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
        self.state.begin_frame(gpu)
    }

    /// Draws the overlay over the frame, reads it back if that was asked
    /// for, and presents it.
    fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
        self.state.end_frame(gpu)
    }

    fn tear_down(&mut self, gpu: &mut WebGpu) {
        let state = &mut *self.state;
        if let Some((readback, _)) = state.pending_readback.take() {
            destroy_unused(gpu, [ResourceId::Readback(readback)]);
        }
        let imports = [state.color_import.take(), state.depth_import.take()].into_iter().flatten();
        destroy_unused(gpu, imports.map(ResourceId::Texture));
    }
}

impl State {
    fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
        let size = self.acquire()?;
        let depth_stencil = self.depth_stencil_import(gpu, size);
        let current = self.current.as_ref()?;
        let color = *self.color_import.get_or_insert_with(|| gpu.import_texture(&current.texture));
        let targets = TargetFormats {
            color: from_wgpu_format(self.format),
            depth_stencil: from_wgpu_format(self.depth_stencil_format),
        };
        Some(FrameImage { size, color, depth_stencil: Some(depth_stencil), targets })
    }

    fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
        if let Some(color) = self.color_import.take() {
            destroy_unused(gpu, [ResourceId::Texture(color)]);
        }
        let Some(current) = self.current.take() else {
            return Handoff::Dropped;
        };
        if let Some(overlay) = self.overlay.as_mut() {
            let view = current.texture.create_view(&wgpu::TextureViewDescriptor::default());
            overlay(&OverlayTarget {
                device: self.device.device(),
                queue: self.device.queue(),
                view: &view,
                format: self.format,
                size: Size::new(current.texture.width(), current.texture.height()),
            });
        }
        if std::mem::take(&mut self.readback_requested) {
            self.read_back(gpu, &current.texture);
            // Natively this waits for the copy; in the browser the event
            // loop maps it later.
            self.finish_readback(gpu, true);
        }
        self.device.queue().present(current);
        Handoff::Presented
    }
}

impl Drop for State {
    fn drop(&mut self) {
        // The surface texture goes before the surface.
        drop(self.current.take());
        drop(self.depth_stencil.take());
        drop(self.overlay.take());
        // Runs the callbacks still outstanding.
        let _ = self.device.device().poll(wgpu::PollType::Poll);
    }
}