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