mln-rs-webgpu 0.0.20

Part of mln-rs, a Rust port of the MapLibre Native map rendering core. Depend on mln-rs instead.
Documentation
//! The GPU and queue that WebGPU renderers share.
//!
//! Natively, the library's device is on the backends that `WGPU_BACKEND`
//! names (wgpu's variable, such as "vulkan"), or else Vulkan on Linux, where
//! tests run on lavapipe (`VK_DRIVER_FILES`), and wgpu's defaults elsewhere.
//! Every device `Device::new` makes comes from one instance per set of
//! backends, kept for the life of the process: the Vulkan loader crashes when
//! one thread names an object (`vkSetDebugUtilsObjectNameEXT`, which wgpu
//! calls for each labeled object) while another thread destroys an instance.
//! The instance takes wgpu's other variables too, such as
//! `WGPU_DISCARD_HAL_LABELS`, which leaves the objects unnamed.

use std::sync::{Arc, OnceLock};

use mln_gfx::Error;
#[cfg(not(target_family = "wasm"))]
use parking_lot::Mutex;

use crate::log_target;

/// A WebGPU device that renderers on any thread share: the library's, or the
/// host's. Clones share it.
#[derive(Clone, Debug)]
pub struct Device {
    /// What window surfaces are made with: the instance that made the
    /// device. The host's device may come without it.
    instance: Option<wgpu::Instance>,
    /// What surfaces are checked against. The host's device has none.
    adapter: Option<wgpu::Adapter>,
    device: wgpu::Device,
    queue: wgpu::Queue,
    /// The format the host configures its surfaces with.
    surface_format: Option<wgpu::TextureFormat>,
    /// Why the library's device was lost, once it is.
    lost: Arc<OnceLock<String>>,
}

/// Records in `lost` why `device` is lost, once it is.
fn watch_for_loss(device: &wgpu::Device) -> Arc<OnceLock<String>> {
    let lost = Arc::new(OnceLock::new());
    let record = Arc::clone(&lost);
    device.set_device_lost_callback(move |reason, message| {
        let _ = record.set(format!("the WebGPU device was lost ({reason:?}): {message}"));
    });
    lost
}

#[cfg(not(target_family = "wasm"))]
fn instance_backends() -> wgpu::Backends {
    if let Some(backends) = wgpu::Backends::from_env() {
        return backends;
    }
    if cfg!(target_os = "linux") { wgpu::Backends::VULKAN } else { wgpu::Backends::all() }
}

/// The instance for `backends`: one per set of backends, created on first
/// use and never destroyed (see the module docs).
#[cfg(not(target_family = "wasm"))]
fn shared_instance(backends: wgpu::Backends) -> wgpu::Instance {
    static INSTANCES: Mutex<Vec<(wgpu::Backends, wgpu::Instance)>> = Mutex::new(Vec::new());
    let mut instances = INSTANCES.lock();
    if let Some((_, instance)) = instances.iter().find(|(made_for, _)| *made_for == backends) {
        return instance.clone();
    }
    let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
        backends,
        ..wgpu::InstanceDescriptor::new_without_display_handle_from_env()
    });
    instances.push((backends, instance.clone()));
    instance
}

/// What the library's device is made with: the WebGPU default limits,
/// lowered to what `adapter` supports (the Metal of the iOS, tvOS and
/// visionOS simulators allows fewer inter-stage shader variables than they
/// ask), with textures as large as `adapter` takes, so that a frame is as
/// large as on the other backends, and 32-bit float depth with stencil
/// where `adapter` has it. A
/// benchmark that measures the render passes also asks for pipeline
/// statistics and timestamp queries (`bench::features`).
fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> {
    #[cfg_attr(not(feature = "bench"), expect(unused_mut, reason = "only a benchmark asks for more"))]
    let mut features = wgpu::Features::DEPTH32FLOAT_STENCIL8;
    #[cfg(feature = "bench")]
    {
        features |= crate::bench::features();
    }
    let limits = adapter.limits();
    wgpu::DeviceDescriptor {
        label: Some("MapLibre WebGPU Device"),
        required_features: adapter.features() & features,
        required_limits: wgpu::Limits {
            max_texture_dimension_2d: limits.max_texture_dimension_2d,
            ..wgpu::Limits::default().or_worse_values_from(&limits)
        },
        ..Default::default()
    }
}

/// The name of `backend` in a device's log record.
#[cfg(not(target_family = "wasm"))]
pub(crate) fn backend_type_to_string(backend: wgpu::Backend) -> &'static str {
    match backend {
        wgpu::Backend::Noop => "Null",
        wgpu::Backend::BrowserWebGpu => "WebGPU",
        wgpu::Backend::Dx12 => "D3D12",
        wgpu::Backend::Metal => "Metal",
        wgpu::Backend::Vulkan => "Vulkan",
        wgpu::Backend::Gl => "OpenGL",
    }
}

impl Device {
    /// The library's device, on the adapter at `adapter_index` in
    /// [`wgpu::Instance::enumerate_adapters`] order, or on the
    /// high-performance adapter when `None`. It logs the adapter it is on,
    /// and its uncaptured errors.
    ///
    /// Fails with [`ErrorKind::NotFound`](mln_gfx::ErrorKind) when there is
    /// no adapter at `adapter_index`, with
    /// [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) when there is no
    /// adapter at all, and with [`ErrorKind::Native`](mln_gfx::ErrorKind)
    /// when the adapter can't create the device.
    #[cfg(not(target_family = "wasm"))]
    pub fn new(adapter_index: Option<usize>) -> Result<Device, Error> {
        let backends = instance_backends();
        let instance = shared_instance(backends);
        let adapter = match adapter_index {
            Some(index) => {
                let mut adapters = pollster::block_on(instance.enumerate_adapters(backends));
                let count = adapters.len();
                if index >= count {
                    return Err(Error::not_found(format!("adapter_index {index} is past the {count} adapters")));
                }
                adapters.swap_remove(index)
            }
            None => pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                ..Default::default()
            }))
            .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?,
        };

        let (device, queue) = pollster::block_on(adapter.request_device(&device_descriptor(&adapter)))
            .map_err(|e| Error::native(format!("Failed to create device: {e}")))?;
        let info = adapter.get_info();
        log::info!(
            target: log_target::RENDER,
            "graphics device uses WebGPU adapter {} on {}",
            info.name,
            backend_type_to_string(info.backend)
        );
        Ok(Device::library(instance, adapter, device, queue))
    }

    /// The library's device in the browser, on the browser's WebGPU and its
    /// high-performance adapter, which arrive asynchronously. Its uncaptured
    /// errors are logged.
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) when the
    /// browser has no WebGPU adapter, and with
    /// [`ErrorKind::Native`](mln_gfx::ErrorKind) when the adapter can't
    /// create the device.
    #[cfg(target_family = "wasm")]
    pub async fn request() -> Result<Device, Error> {
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: wgpu::Backends::BROWSER_WEBGPU,
            ..wgpu::InstanceDescriptor::new_without_display_handle()
        });
        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                ..Default::default()
            })
            .await
            .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?;
        let (device, queue) = adapter
            .request_device(&device_descriptor(&adapter))
            .await
            .map_err(|e| Error::native(format!("Failed to create device: {e}")))?;
        Ok(Device::library(instance, adapter, device, queue))
    }

    /// The library's device, which logs its uncaptured errors: wgpu's
    /// default handler panics.
    fn library(instance: wgpu::Instance, adapter: wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Device {
        device.on_uncaptured_error(Arc::new(|error: wgpu::Error| {
            log::error!(target: log_target::RENDER, "WebGPU validation error: {error}");
        }));
        let lost = watch_for_loss(&device);
        Device { instance: Some(instance), adapter: Some(adapter), device, queue, surface_format: None, lost }
    }

    /// The host's device and queue. Window surfaces need the `instance` that
    /// made the device. A surface on it is configured with the format that
    /// its options name, or else with `surface_format`, which it must
    /// support. The host keeps the device's uncaptured-error and device-lost
    /// handlers.
    #[must_use]
    pub fn from_wgpu(
        instance: Option<wgpu::Instance>,
        device: wgpu::Device,
        queue: wgpu::Queue,
        surface_format: Option<wgpu::TextureFormat>,
    ) -> Device {
        Device { instance, adapter: None, device, queue, surface_format, lost: Arc::default() }
    }

    #[must_use]
    pub fn device(&self) -> &wgpu::Device {
        &self.device
    }

    #[must_use]
    pub fn queue(&self) -> &wgpu::Queue {
        &self.queue
    }

    #[must_use]
    pub fn instance(&self) -> Option<&wgpu::Instance> {
        self.instance.as_ref()
    }

    pub(crate) fn adapter(&self) -> Option<&wgpu::Adapter> {
        self.adapter.as_ref()
    }

    pub(crate) fn surface_format(&self) -> Option<wgpu::TextureFormat> {
        self.surface_format
    }

    /// Why the device was lost, once the library's device is: a browser
    /// loses it when the GPU process resets or can't present. The host's
    /// device keeps its own device-lost callback, and reports nothing here.
    #[must_use]
    pub fn lost(&self) -> Option<&str> {
        self.lost.get().map(String::as_str)
    }

    /// The adapter the device is on (name, backend, driver).
    #[must_use]
    pub fn adapter_info(&self) -> wgpu::AdapterInfo {
        self.device.adapter_info()
    }
}