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 mut descriptor =
66        wgpu::InstanceDescriptor { backends, ..wgpu::InstanceDescriptor::new_without_display_handle_from_env() };
67    // The library makes no indirect calls, so the devices skip the pipeline
68    // that validates them, which wgpu otherwise compiles for each device:
69    // on macOS, that compile can wait minutes for Metal's shader cache.
70    // `WGPU_VALIDATION_INDIRECT_CALL=1` turns it back on.
71    descriptor.flags = descriptor.flags.difference(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL).with_env();
72    let instance = wgpu::Instance::new(descriptor);
73    instances.push((backends, instance.clone()));
74    instance
75}
76
77/// What the library's device is made with: the WebGPU default limits,
78/// lowered to what `adapter` supports (the Metal of the iOS, tvOS and
79/// visionOS simulators allows fewer inter-stage shader variables than they
80/// ask), with textures as large as `adapter` takes, so that a frame is as
81/// large as on the other backends, and 32-bit float depth with stencil
82/// where `adapter` has it. A
83/// benchmark that measures the render passes also asks for pipeline
84/// statistics and timestamp queries (`bench::features`).
85fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> {
86    #[cfg_attr(not(feature = "bench"), expect(unused_mut, reason = "only a benchmark asks for more"))]
87    let mut features = wgpu::Features::DEPTH32FLOAT_STENCIL8;
88    #[cfg(feature = "bench")]
89    {
90        features |= crate::bench::features();
91    }
92    let limits = adapter.limits();
93    wgpu::DeviceDescriptor {
94        label: Some("MapLibre WebGPU Device"),
95        required_features: adapter.features() & features,
96        required_limits: wgpu::Limits {
97            max_texture_dimension_2d: limits.max_texture_dimension_2d,
98            ..wgpu::Limits::default().or_worse_values_from(&limits)
99        },
100        ..Default::default()
101    }
102}
103
104/// The name of `backend` in a device's log record.
105#[cfg(not(target_family = "wasm"))]
106pub(crate) fn backend_type_to_string(backend: wgpu::Backend) -> &'static str {
107    match backend {
108        wgpu::Backend::Noop => "Null",
109        wgpu::Backend::BrowserWebGpu => "WebGPU",
110        wgpu::Backend::Dx12 => "D3D12",
111        wgpu::Backend::Metal => "Metal",
112        wgpu::Backend::Vulkan => "Vulkan",
113        wgpu::Backend::Gl => "OpenGL",
114    }
115}
116
117impl Device {
118    /// The library's device, on the adapter at `adapter_index` in
119    /// [`wgpu::Instance::enumerate_adapters`] order, or on the
120    /// high-performance adapter when `None`. It logs the adapter it is on,
121    /// and its uncaptured errors.
122    ///
123    /// Fails with [`ErrorKind::NotFound`](mln_gfx::ErrorKind) when there is
124    /// no adapter at `adapter_index`, with
125    /// [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) when there is no
126    /// adapter at all, and with [`ErrorKind::Failed`](mln_gfx::ErrorKind)
127    /// when the adapter can't create the device.
128    #[cfg(not(target_family = "wasm"))]
129    pub fn new(adapter_index: Option<usize>) -> Result<Device, Error> {
130        let backends = instance_backends();
131        let instance = shared_instance(backends);
132        let adapter = match adapter_index {
133            Some(index) => {
134                let mut adapters = pollster::block_on(instance.enumerate_adapters(backends));
135                let count = adapters.len();
136                if index >= count {
137                    return Err(Error::not_found(format!("adapter_index {index} is past the {count} adapters")));
138                }
139                adapters.swap_remove(index)
140            }
141            None => pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
142                power_preference: wgpu::PowerPreference::HighPerformance,
143                ..Default::default()
144            }))
145            .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?,
146        };
147
148        let (device, queue) = pollster::block_on(adapter.request_device(&device_descriptor(&adapter)))
149            .map_err(|e| Error::failed(format!("Failed to create device: {e}")))?;
150        let info = adapter.get_info();
151        tracing::info!(
152            target: log_target::RENDER,
153            adapter = %info.name,
154            backend = backend_type_to_string(info.backend),
155            "Graphics device uses a WebGPU adapter"
156        );
157        Ok(Device::library(instance, adapter, device, queue))
158    }
159
160    /// The library's device in the browser, on the browser's WebGPU and its
161    /// high-performance adapter, which arrive asynchronously. Its uncaptured
162    /// errors are logged.
163    ///
164    /// Fails with [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) when the
165    /// browser has no WebGPU adapter, and with
166    /// [`ErrorKind::Failed`](mln_gfx::ErrorKind) when the adapter can't
167    /// create the device.
168    #[cfg(target_family = "wasm")]
169    pub async fn request() -> Result<Device, Error> {
170        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
171            backends: wgpu::Backends::BROWSER_WEBGPU,
172            ..wgpu::InstanceDescriptor::new_without_display_handle()
173        });
174        let adapter = instance
175            .request_adapter(&wgpu::RequestAdapterOptions {
176                power_preference: wgpu::PowerPreference::HighPerformance,
177                ..Default::default()
178            })
179            .await
180            .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?;
181        let (device, queue) = adapter
182            .request_device(&device_descriptor(&adapter))
183            .await
184            .map_err(|e| Error::failed(format!("Failed to create device: {e}")))?;
185        Ok(Device::library(instance, adapter, device, queue))
186    }
187
188    /// The library's device, which logs its uncaptured errors: wgpu's
189    /// default handler panics.
190    fn library(instance: wgpu::Instance, adapter: wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Device {
191        device.on_uncaptured_error(Arc::new(|error: wgpu::Error| {
192            tracing::error!(target: log_target::RENDER, error = %error, "WebGPU validation error");
193        }));
194        let lost = watch_for_loss(&device);
195        Device { instance: Some(instance), adapter: Some(adapter), device, queue, surface_format: None, lost }
196    }
197
198    /// The host's device and queue. Window surfaces need the `instance` that
199    /// made the device. A surface on it is configured with the format that
200    /// its options name, or else with `surface_format`, which it must
201    /// support. The host keeps the device's uncaptured-error and device-lost
202    /// handlers.
203    #[must_use]
204    pub fn from_wgpu(
205        instance: Option<wgpu::Instance>,
206        device: wgpu::Device,
207        queue: wgpu::Queue,
208        surface_format: Option<wgpu::TextureFormat>,
209    ) -> Device {
210        Device { instance, adapter: None, device, queue, surface_format, lost: Arc::default() }
211    }
212
213    #[must_use]
214    pub fn device(&self) -> &wgpu::Device {
215        &self.device
216    }
217
218    #[must_use]
219    pub fn queue(&self) -> &wgpu::Queue {
220        &self.queue
221    }
222
223    #[must_use]
224    pub fn instance(&self) -> Option<&wgpu::Instance> {
225        self.instance.as_ref()
226    }
227
228    pub(crate) fn adapter(&self) -> Option<&wgpu::Adapter> {
229        self.adapter.as_ref()
230    }
231
232    pub(crate) fn surface_format(&self) -> Option<wgpu::TextureFormat> {
233        self.surface_format
234    }
235
236    /// Why the device was lost, once the library's device is: a browser
237    /// loses it when the GPU process resets or can't present. The host's
238    /// device keeps its own device-lost callback, and reports nothing here.
239    #[must_use]
240    pub fn lost(&self) -> Option<&str> {
241        self.lost.get().map(String::as_str)
242    }
243
244    /// The adapter the device is on (name, backend, driver).
245    #[must_use]
246    pub fn adapter_info(&self) -> wgpu::AdapterInfo {
247        self.device.adapter_info()
248    }
249}