use std::sync::{Arc, OnceLock};
use mln_util::error::Error;
use mln_util::logging::{Event, Log};
#[cfg(not(target_family = "wasm"))]
use parking_lot::Mutex;
#[derive(Clone, Debug)]
pub struct Device {
instance: Option<wgpu::Instance>,
adapter: Option<wgpu::Adapter>,
device: wgpu::Device,
queue: wgpu::Queue,
surface_format: Option<wgpu::TextureFormat>,
lost: Arc<OnceLock<String>>,
}
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() }
}
#[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()
});
instances.push((backends, instance.clone()));
instance
}
fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> {
wgpu::DeviceDescriptor {
label: Some("MapLibre WebGPU Device"),
required_features: adapter.features() & wgpu::Features::DEPTH32FLOAT_STENCIL8,
required_limits: wgpu::Limits::default().or_worse_values_from(&adapter.limits()),
..Default::default()
}
}
#[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 {
#[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(
Event::Render,
format!("graphics device uses WebGPU adapter {} on {}", info.name, backend_type_to_string(info.backend)),
);
Ok(Device::library(instance, adapter, device, queue))
}
#[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))
}
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(Event::Render, format!("WebGPU validation error: {error}"));
}));
let lost = watch_for_loss(&device);
Device { instance: Some(instance), adapter: Some(adapter), device, queue, surface_format: None, lost }
}
#[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
}
#[must_use]
pub fn lost(&self) -> Option<&str> {
self.lost.get().map(String::as_str)
}
#[must_use]
pub fn adapter_info(&self) -> wgpu::AdapterInfo {
self.device.adapter_info()
}
}