1use std::sync::{Arc, OnceLock};
12
13use mln_util::error::Error;
14use mln_util::logging::{Event, Log};
15#[cfg(not(target_family = "wasm"))]
16use parking_lot::Mutex;
17
18#[derive(Clone, Debug)]
21pub struct Device {
22 instance: Option<wgpu::Instance>,
25 adapter: Option<wgpu::Adapter>,
27 device: wgpu::Device,
28 queue: wgpu::Queue,
29 surface_format: Option<wgpu::TextureFormat>,
31 lost: Arc<OnceLock<String>>,
33}
34
35fn watch_for_loss(device: &wgpu::Device) -> Arc<OnceLock<String>> {
37 let lost = Arc::new(OnceLock::new());
38 let record = Arc::clone(&lost);
39 device.set_device_lost_callback(move |reason, message| {
40 let _ = record.set(format!("the WebGPU device was lost ({reason:?}): {message}"));
41 });
42 lost
43}
44
45#[cfg(not(target_family = "wasm"))]
46fn instance_backends() -> wgpu::Backends {
47 if let Some(backends) = wgpu::Backends::from_env() {
48 return backends;
49 }
50 if cfg!(target_os = "linux") { wgpu::Backends::VULKAN } else { wgpu::Backends::all() }
51}
52
53#[cfg(not(target_family = "wasm"))]
56fn shared_instance(backends: wgpu::Backends) -> wgpu::Instance {
57 static INSTANCES: Mutex<Vec<(wgpu::Backends, wgpu::Instance)>> = Mutex::new(Vec::new());
58 let mut instances = INSTANCES.lock();
59 if let Some((_, instance)) = instances.iter().find(|(made_for, _)| *made_for == backends) {
60 return instance.clone();
61 }
62 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
63 backends,
64 ..wgpu::InstanceDescriptor::new_without_display_handle()
65 });
66 instances.push((backends, instance.clone()));
67 instance
68}
69
70fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> {
75 wgpu::DeviceDescriptor {
76 label: Some("MapLibre WebGPU Device"),
77 required_features: adapter.features() & wgpu::Features::DEPTH32FLOAT_STENCIL8,
78 required_limits: wgpu::Limits::default().or_worse_values_from(&adapter.limits()),
79 ..Default::default()
80 }
81}
82
83#[cfg(not(target_family = "wasm"))]
85pub(crate) fn backend_type_to_string(backend: wgpu::Backend) -> &'static str {
86 match backend {
87 wgpu::Backend::Noop => "Null",
88 wgpu::Backend::BrowserWebGpu => "WebGPU",
89 wgpu::Backend::Dx12 => "D3D12",
90 wgpu::Backend::Metal => "Metal",
91 wgpu::Backend::Vulkan => "Vulkan",
92 wgpu::Backend::Gl => "OpenGL",
93 }
94}
95
96impl Device {
97 #[cfg(not(target_family = "wasm"))]
108 pub fn new(adapter_index: Option<usize>) -> Result<Device, Error> {
109 let backends = instance_backends();
110 let instance = shared_instance(backends);
111 let adapter = match adapter_index {
112 Some(index) => {
113 let mut adapters = pollster::block_on(instance.enumerate_adapters(backends));
114 let count = adapters.len();
115 if index >= count {
116 return Err(Error::not_found(format!("adapter_index {index} is past the {count} adapters")));
117 }
118 adapters.swap_remove(index)
119 }
120 None => pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
121 power_preference: wgpu::PowerPreference::HighPerformance,
122 ..Default::default()
123 }))
124 .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?,
125 };
126
127 let (device, queue) = pollster::block_on(adapter.request_device(&device_descriptor(&adapter)))
128 .map_err(|e| Error::native(format!("Failed to create device: {e}")))?;
129 let info = adapter.get_info();
130 Log::info(
131 Event::Render,
132 format!("graphics device uses WebGPU adapter {} on {}", info.name, backend_type_to_string(info.backend)),
133 );
134 Ok(Device::library(instance, adapter, device, queue))
135 }
136
137 #[cfg(target_family = "wasm")]
146 pub async fn request() -> Result<Device, Error> {
147 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
148 backends: wgpu::Backends::BROWSER_WEBGPU,
149 ..wgpu::InstanceDescriptor::new_without_display_handle()
150 });
151 let adapter = instance
152 .request_adapter(&wgpu::RequestAdapterOptions {
153 power_preference: wgpu::PowerPreference::HighPerformance,
154 ..Default::default()
155 })
156 .await
157 .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?;
158 let (device, queue) = adapter
159 .request_device(&device_descriptor(&adapter))
160 .await
161 .map_err(|e| Error::native(format!("Failed to create device: {e}")))?;
162 Ok(Device::library(instance, adapter, device, queue))
163 }
164
165 fn library(instance: wgpu::Instance, adapter: wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Device {
168 device.on_uncaptured_error(Arc::new(|error: wgpu::Error| {
169 Log::error(Event::Render, format!("WebGPU validation error: {error}"));
170 }));
171 let lost = watch_for_loss(&device);
172 Device { instance: Some(instance), adapter: Some(adapter), device, queue, surface_format: None, lost }
173 }
174
175 #[must_use]
181 pub fn from_wgpu(
182 instance: Option<wgpu::Instance>,
183 device: wgpu::Device,
184 queue: wgpu::Queue,
185 surface_format: Option<wgpu::TextureFormat>,
186 ) -> Device {
187 Device { instance, adapter: None, device, queue, surface_format, lost: Arc::default() }
188 }
189
190 #[must_use]
191 pub fn device(&self) -> &wgpu::Device {
192 &self.device
193 }
194
195 #[must_use]
196 pub fn queue(&self) -> &wgpu::Queue {
197 &self.queue
198 }
199
200 #[must_use]
201 pub fn instance(&self) -> Option<&wgpu::Instance> {
202 self.instance.as_ref()
203 }
204
205 pub(crate) fn adapter(&self) -> Option<&wgpu::Adapter> {
206 self.adapter.as_ref()
207 }
208
209 pub(crate) fn surface_format(&self) -> Option<wgpu::TextureFormat> {
210 self.surface_format
211 }
212
213 #[must_use]
217 pub fn lost(&self) -> Option<&str> {
218 self.lost.get().map(String::as_str)
219 }
220
221 #[must_use]
223 pub fn adapter_info(&self) -> wgpu::AdapterInfo {
224 self.device.adapter_info()
225 }
226}