Skip to main content

mln_webgpu/
device.rs

1//! The GPU and queue that WebGPU renderers share.
2//!
3//! Natively, the library's device is on the backends that `WGPU_BACKEND`
4//! names (wgpu's variable, such as "vulkan"), or else Vulkan on Linux, where
5//! tests run on lavapipe (`VK_DRIVER_FILES`), and wgpu's defaults elsewhere.
6//! Every device `Device::new` makes comes from one instance per set of
7//! backends, kept for the life of the process: the Vulkan loader crashes when
8//! one thread names an object (`vkSetDebugUtilsObjectNameEXT`, which wgpu
9//! calls for each labeled object) while another thread destroys an instance.
10//! The instance takes wgpu's other variables too, such as
11//! `WGPU_DISCARD_HAL_LABELS`, which leaves the objects unnamed, and
12//! `WGPU_VALIDATION=1`, which turns on the backend's validation: Khronos'
13//! Vulkan validation layer, or Direct3D 12's debug layer. Debug builds leave
14//! it off, as release builds do.
15
16use std::sync::{Arc, OnceLock};
17
18use mln_gfx::Error;
19#[cfg(not(target_family = "wasm"))]
20use parking_lot::Mutex;
21
22use crate::log_target;
23
24/// A WebGPU device that renderers on any thread share: the library's, or the
25/// host's. Clones share it.
26#[derive(Clone, Debug)]
27pub struct Device {
28    /// What window surfaces are made with: the instance that made the
29    /// device. The host's device may come without it.
30    instance: Option<wgpu::Instance>,
31    /// What surfaces are checked against. The host's device has none.
32    adapter: Option<wgpu::Adapter>,
33    device: wgpu::Device,
34    queue: wgpu::Queue,
35    /// The format the host configures its surfaces with.
36    surface_format: Option<wgpu::TextureFormat>,
37    /// Why the library's device was lost, once it is.
38    lost: Arc<OnceLock<String>>,
39}
40
41/// Records in `lost` why `device` is lost, once it is.
42fn watch_for_loss(device: &wgpu::Device) -> Arc<OnceLock<String>> {
43    let lost = Arc::new(OnceLock::new());
44    let record = Arc::clone(&lost);
45    device.set_device_lost_callback(move |reason, message| {
46        let _ = record.set(format!("the WebGPU device was lost ({reason:?}): {message}"));
47    });
48    lost
49}
50
51#[cfg(not(target_family = "wasm"))]
52fn instance_backends() -> wgpu::Backends {
53    if let Some(backends) = wgpu::Backends::from_env() {
54        return backends;
55    }
56    if cfg!(target_os = "linux") { wgpu::Backends::VULKAN } else { wgpu::Backends::all() }
57}
58
59/// The instance for `backends`: one per set of backends, created on first
60/// use and never destroyed (see the module docs).
61#[cfg(not(target_family = "wasm"))]
62fn shared_instance(backends: wgpu::Backends) -> wgpu::Instance {
63    static INSTANCES: Mutex<Vec<(wgpu::Backends, wgpu::Instance)>> = Mutex::new(Vec::new());
64    let mut instances = INSTANCES.lock();
65    if let Some((_, instance)) = instances.iter().find(|(made_for, _)| *made_for == backends) {
66        return instance.clone();
67    }
68    let mut descriptor =
69        wgpu::InstanceDescriptor { backends, ..wgpu::InstanceDescriptor::new_without_display_handle_from_env() };
70    // The library makes no indirect calls, so the devices skip the pipeline
71    // that validates them, which wgpu otherwise compiles for each device:
72    // on macOS, that compile can wait minutes for Metal's shader cache.
73    // `WGPU_VALIDATION_INDIRECT_CALL=1` turns it back on. The backend's
74    // validation, which wgpu's debug builds turn on wherever its layer is
75    // installed, waits for `WGPU_VALIDATION=1`: on a CPU rasterizer, Vulkan's
76    // layer can hold one frame's submit for over a minute.
77    let skipped = wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL | wgpu::InstanceFlags::VALIDATION;
78    descriptor.flags = descriptor.flags.difference(skipped).with_env();
79    let instance = wgpu::Instance::new(descriptor);
80    instances.push((backends, instance.clone()));
81    instance
82}
83
84/// What the library's device is made with: the WebGPU default limits,
85/// lowered to what `adapter` supports (the Metal of the iOS, tvOS and
86/// visionOS simulators allows fewer inter-stage shader variables than they
87/// ask), with textures as large as `adapter` takes, so that a frame is as
88/// large as on the other backends, and 32-bit float depth with stencil
89/// where `adapter` has it. A
90/// benchmark that measures the render passes also asks for pipeline
91/// statistics and timestamp queries (`bench::features`).
92fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> {
93    #[cfg_attr(not(feature = "bench"), expect(unused_mut, reason = "only a benchmark asks for more"))]
94    let mut features = wgpu::Features::DEPTH32FLOAT_STENCIL8;
95    #[cfg(feature = "bench")]
96    {
97        features |= crate::bench::features();
98    }
99    let limits = adapter.limits();
100    wgpu::DeviceDescriptor {
101        label: Some("MapLibre WebGPU Device"),
102        required_features: adapter.features() & features,
103        required_limits: wgpu::Limits {
104            max_texture_dimension_2d: limits.max_texture_dimension_2d,
105            ..wgpu::Limits::default().or_worse_values_from(&limits)
106        },
107        ..Default::default()
108    }
109}
110
111/// The name of `backend` in a device's log record.
112#[cfg(not(target_family = "wasm"))]
113pub(crate) fn backend_type_to_string(backend: wgpu::Backend) -> &'static str {
114    match backend {
115        wgpu::Backend::Noop => "Null",
116        wgpu::Backend::BrowserWebGpu => "WebGPU",
117        wgpu::Backend::Dx12 => "D3D12",
118        wgpu::Backend::Metal => "Metal",
119        wgpu::Backend::Vulkan => "Vulkan",
120        wgpu::Backend::Gl => "OpenGL",
121    }
122}
123
124impl Device {
125    /// The library's device, on the adapter at `adapter_index` in
126    /// [`wgpu::Instance::enumerate_adapters`] order, or on the
127    /// high-performance adapter when `None`. It logs the adapter it is on,
128    /// and its uncaptured errors.
129    ///
130    /// Fails with [`ErrorKind::NotFound`](mln_gfx::ErrorKind) when there is
131    /// no adapter at `adapter_index`, with
132    /// [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) when there is no
133    /// adapter at all, and with [`ErrorKind::Failed`](mln_gfx::ErrorKind)
134    /// when the adapter can't create the device.
135    #[cfg(not(target_family = "wasm"))]
136    pub fn new(adapter_index: Option<usize>) -> Result<Device, Error> {
137        let backends = instance_backends();
138        let instance = shared_instance(backends);
139        let adapter = match adapter_index {
140            Some(index) => {
141                let mut adapters = pollster::block_on(instance.enumerate_adapters(backends));
142                let count = adapters.len();
143                if index >= count {
144                    return Err(Error::not_found(format!("adapter_index {index} is past the {count} adapters")));
145                }
146                adapters.swap_remove(index)
147            }
148            None => pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
149                power_preference: wgpu::PowerPreference::HighPerformance,
150                ..Default::default()
151            }))
152            .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?,
153        };
154
155        let (device, queue) = pollster::block_on(adapter.request_device(&device_descriptor(&adapter)))
156            .map_err(|e| Error::failed(format!("Failed to create device: {e}")))?;
157        let info = adapter.get_info();
158        tracing::info!(
159            target: log_target::RENDER,
160            adapter = %info.name,
161            backend = backend_type_to_string(info.backend),
162            "Graphics device uses a WebGPU adapter"
163        );
164        Ok(Device::library(instance, adapter, device, queue))
165    }
166
167    /// The library's device in the browser, on the browser's WebGPU and its
168    /// high-performance adapter, which arrive asynchronously. Its uncaptured
169    /// errors are logged.
170    ///
171    /// Fails with [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) when the
172    /// browser has no WebGPU adapter, and with
173    /// [`ErrorKind::Failed`](mln_gfx::ErrorKind) when the adapter can't
174    /// create the device.
175    #[cfg(target_family = "wasm")]
176    pub async fn request() -> Result<Device, Error> {
177        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
178            backends: wgpu::Backends::BROWSER_WEBGPU,
179            ..wgpu::InstanceDescriptor::new_without_display_handle()
180        });
181        let adapter = instance
182            .request_adapter(&wgpu::RequestAdapterOptions {
183                power_preference: wgpu::PowerPreference::HighPerformance,
184                ..Default::default()
185            })
186            .await
187            .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?;
188        let (device, queue) = adapter
189            .request_device(&device_descriptor(&adapter))
190            .await
191            .map_err(|e| Error::failed(format!("Failed to create device: {e}")))?;
192        Ok(Device::library(instance, adapter, device, queue))
193    }
194
195    /// The library's device, which logs its uncaptured errors: wgpu's
196    /// default handler panics.
197    fn library(instance: wgpu::Instance, adapter: wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Device {
198        device.on_uncaptured_error(Arc::new(|error: wgpu::Error| {
199            tracing::error!(target: log_target::RENDER, error = %error, "WebGPU validation error");
200        }));
201        let lost = watch_for_loss(&device);
202        Device { instance: Some(instance), adapter: Some(adapter), device, queue, surface_format: None, lost }
203    }
204
205    /// The host's device and queue. Window surfaces need the `instance` that
206    /// made the device. A surface on it is configured with the format that
207    /// its options name, or else with `surface_format`, which it must
208    /// support. The host keeps the device's uncaptured-error and device-lost
209    /// handlers.
210    #[must_use]
211    pub fn from_wgpu(
212        instance: Option<wgpu::Instance>,
213        device: wgpu::Device,
214        queue: wgpu::Queue,
215        surface_format: Option<wgpu::TextureFormat>,
216    ) -> Device {
217        Device { instance, adapter: None, device, queue, surface_format, lost: Arc::default() }
218    }
219
220    #[must_use]
221    pub fn device(&self) -> &wgpu::Device {
222        &self.device
223    }
224
225    #[must_use]
226    pub fn queue(&self) -> &wgpu::Queue {
227        &self.queue
228    }
229
230    #[must_use]
231    pub fn instance(&self) -> Option<&wgpu::Instance> {
232        self.instance.as_ref()
233    }
234
235    pub(crate) fn adapter(&self) -> Option<&wgpu::Adapter> {
236        self.adapter.as_ref()
237    }
238
239    pub(crate) fn surface_format(&self) -> Option<wgpu::TextureFormat> {
240        self.surface_format
241    }
242
243    /// Why the device was lost, once the library's device is: a browser
244    /// loses it when the GPU process resets or can't present. The host's
245    /// device keeps its own device-lost callback, and reports nothing here.
246    #[must_use]
247    pub fn lost(&self) -> Option<&str> {
248        self.lost.get().map(String::as_str)
249    }
250
251    /// The adapter the device is on (name, backend, driver).
252    #[must_use]
253    pub fn adapter_info(&self) -> wgpu::AdapterInfo {
254        self.device.adapter_info()
255    }
256}