1use std::future::Future;
8use std::pin::Pin;
9use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
10use std::sync::{Arc, Mutex, OnceLock, RwLock, Weak};
11
12#[derive(Clone, Copy, Debug, Default)]
13pub struct AdapterOptions {
14 pub power_preference: wgpu::PowerPreference,
15 pub force_fallback_adapter: bool,
16}
17
18#[derive(Clone)]
19pub struct Adapter {
20 pub raw: Arc<wgpu::Adapter>,
21 pub shared: Option<Arc<Context>>,
22}
23
24#[derive(Clone, Debug)]
26pub struct DeviceLoss {
27 pub reason: &'static str,
28 pub message: String,
29}
30
31pub struct Context {
38 pub device: Arc<wgpu::Device>,
39 pub queue: Arc<wgpu::Queue>,
40 pub adapter: Arc<wgpu::Adapter>,
41 loss: Arc<Mutex<Option<DeviceLoss>>>,
42 _owner: Option<Arc<dyn std::any::Any + Send + Sync>>,
44}
45
46impl Context {
47 pub fn from_shared(
48 adapter: Arc<wgpu::Adapter>,
49 device: Arc<wgpu::Device>,
50 queue: Arc<wgpu::Queue>,
51 ) -> Self {
52 Self {
53 adapter,
54 device,
55 queue,
56 loss: Arc::new(Mutex::new(None)),
57 _owner: None,
58 }
59 }
60
61 pub fn from_shared_with_owner(
64 adapter: Arc<wgpu::Adapter>,
65 device: Arc<wgpu::Device>,
66 queue: Arc<wgpu::Queue>,
67 owner: Arc<dyn std::any::Any + Send + Sync>,
68 ) -> Self {
69 Self {
70 _owner: Some(owner),
71 ..Self::from_shared(adapter, device, queue)
72 }
73 }
74
75 pub fn notify_lost(&self, reason: &'static str, message: impl Into<String>) {
76 let mut loss = self.loss.lock().unwrap();
77 if loss.is_none() {
78 *loss = Some(DeviceLoss {
79 reason,
80 message: message.into(),
81 });
82 }
83 }
84
85 pub fn loss(&self) -> Option<DeviceLoss> {
86 self.loss.lock().unwrap().clone()
87 }
88}
89
90pub type AdapterFuture =
91 Pin<Box<dyn Future<Output = Result<Option<Adapter>, String>> + Send + 'static>>;
92
93pub trait GpuHost: Send + Sync {
94 fn request_adapter(&self, options: AdapterOptions) -> AdapterFuture;
98}
99
100fn host_slot() -> &'static RwLock<Option<Arc<dyn GpuHost>>> {
101 static HOST: OnceLock<RwLock<Option<Arc<dyn GpuHost>>>> = OnceLock::new();
102 HOST.get_or_init(|| RwLock::new(None))
103}
104
105pub fn set_host(host: Option<Arc<dyn GpuHost>>) {
108 *host_slot().write().unwrap() = host;
109}
110
111pub async fn request_adapter(options: AdapterOptions) -> Result<Option<Adapter>, String> {
112 let host = host_slot().read().unwrap().clone();
113 if let Some(host) = host {
114 return host.request_adapter(options).await;
115 }
116 let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle();
120 descriptor.backends = if cfg!(target_os = "windows") {
121 wgpu::Backends::DX12
122 } else {
123 wgpu::Backends::PRIMARY
124 };
125 let instance = wgpu::Instance::new(descriptor);
126 match instance
127 .request_adapter(&wgpu::RequestAdapterOptions {
128 power_preference: options.power_preference,
129 force_fallback_adapter: options.force_fallback_adapter,
130 compatible_surface: None,
131 ..Default::default()
132 })
133 .await
134 {
135 Ok(raw) => Ok(Some(Adapter {
136 raw: Arc::new(raw),
137 shared: None,
138 })),
139 Err(_) => Ok(None),
141 }
142}
143
144impl Adapter {
145 pub async fn request_device(
146 &self,
147 features: wgpu::Features,
148 limits: wgpu::Limits,
149 ) -> Result<Arc<Context>, String> {
150 let available_features = self
151 .shared
152 .as_ref()
153 .map_or_else(|| self.raw.features(), |c| c.device.features());
154 if !available_features.contains(features) {
155 return Err(format!(
156 "Unsupported requiredFeatures: {:?}",
157 features - available_features
158 ));
159 }
160 let available_limits = self
161 .shared
162 .as_ref()
163 .map_or_else(|| self.raw.limits(), |c| c.device.limits());
164 if !limits.check_limits(&available_limits) {
165 let mut failures = Vec::new();
166 limits.check_limits_with_fail_fn(
167 &available_limits,
168 false,
169 |name, requested, allowed| {
170 failures.push(format!(
171 "{name}: requested {requested}, available {allowed}"
172 ));
173 },
174 );
175 return Err(format!(
176 "Unsupported requiredLimits: {}",
177 failures.join(", ")
178 ));
179 }
180 if let Some(context) = &self.shared {
181 if features != context.device.features() || limits != context.device.limits() {
185 return Err(
186 "Shared WebGPU clients currently require matching physical capabilities".into(),
187 );
188 }
189 if context.adapter.as_ref() != self.raw.as_ref() {
190 return Err("Shared GPU context belongs to a different adapter".into());
191 }
192 if let Some(loss) = context.loss() {
193 return Err(format!("Shared GPU device is lost: {}", loss.message));
194 }
195 return Ok(context.clone());
196 }
197 let (device, queue) = self
198 .raw
199 .request_device(&wgpu::DeviceDescriptor {
200 label: Some("redjs WebGPU"),
201 required_features: features,
202 required_limits: limits,
203 memory_hints: wgpu::MemoryHints::MemoryUsage,
204 ..Default::default()
205 })
206 .await
207 .map_err(|e| e.to_string())?;
208 let context = Arc::new(Context::from_shared(
209 self.raw.clone(),
210 Arc::new(device),
211 Arc::new(queue),
212 ));
213 let loss = context.loss.clone();
216 context
217 .device
218 .set_device_lost_callback(move |reason, message| {
219 let mut state = loss.lock().unwrap();
220 if state.is_none() {
221 *state = Some(DeviceLoss {
222 reason: if reason == wgpu::DeviceLostReason::Destroyed {
223 "destroyed"
224 } else {
225 "unknown"
226 },
227 message,
228 });
229 }
230 });
231 Ok(context)
232 }
233}
234
235#[derive(Clone, Debug)]
236pub struct GpuError {
237 pub kind: &'static str,
239 pub message: String,
240}
241
242#[derive(Default)]
243struct Resources {
244 buffers: Vec<Weak<wgpu::Buffer>>,
245 textures: Vec<Weak<wgpu::Texture>>,
246}
247
248pub struct Client {
251 pub context: Arc<Context>,
252 pub id: u64,
253 pub features: wgpu::Features,
254 pub limits: wgpu::Limits,
255 pub destroyed: AtomicBool,
256 resources: Mutex<Resources>,
257 errors: Mutex<Vec<GpuError>>,
258}
259
260impl Client {
261 pub fn new(context: Arc<Context>) -> Arc<Self> {
262 let features = context.device.features();
263 let limits = context.device.limits();
264 Self::new_with_capabilities(context, features, limits)
265 }
266
267 pub fn new_with_capabilities(
268 context: Arc<Context>,
269 features: wgpu::Features,
270 limits: wgpu::Limits,
271 ) -> Arc<Self> {
272 static NEXT: AtomicU64 = AtomicU64::new(1);
273 Arc::new(Self {
274 context,
275 id: NEXT.fetch_add(1, Ordering::Relaxed),
276 features,
277 limits,
278 destroyed: AtomicBool::new(false),
279 resources: Mutex::new(Resources::default()),
280 errors: Mutex::new(Vec::new()),
281 })
282 }
283
284 pub fn check(&self) -> Result<(), String> {
285 if self.destroyed.load(Ordering::Acquire) {
286 return Err("GPUDevice has been destroyed".into());
287 }
288 if let Some(loss) = self.context.loss() {
289 return Err(format!("GPUDevice is lost: {}", loss.message));
290 }
291 Ok(())
292 }
293
294 pub fn track_buffer(&self, buffer: &Arc<wgpu::Buffer>) {
295 let mut resources = self.resources.lock().unwrap();
296 if self.destroyed.load(Ordering::Acquire) {
297 drop(resources);
298 buffer.destroy();
299 } else {
300 resources.buffers.retain(|b| b.strong_count() != 0);
301 resources.buffers.push(Arc::downgrade(buffer));
302 }
303 }
304
305 pub fn track_texture(&self, texture: &Arc<wgpu::Texture>) {
306 let mut resources = self.resources.lock().unwrap();
307 if self.destroyed.load(Ordering::Acquire) {
308 drop(resources);
309 texture.destroy();
310 } else {
311 resources.textures.retain(|t| t.strong_count() != 0);
312 resources.textures.push(Arc::downgrade(texture));
313 }
314 }
315
316 pub(super) fn release_presented_texture(&self, texture: &Arc<wgpu::Texture>) -> bool {
319 let mut resources = self.resources.lock().unwrap();
320 if self.destroyed.load(Ordering::Acquire) {
321 return false;
322 }
323 resources.textures.retain(|weak| {
324 weak.upgrade()
325 .is_some_and(|raw| !Arc::ptr_eq(&raw, texture))
326 });
327 true
328 }
329
330 pub fn destroy(&self) {
332 let resources = {
333 let mut resources = self.resources.lock().unwrap();
334 if self.destroyed.swap(true, Ordering::AcqRel) {
335 return;
336 }
337 std::mem::take(&mut *resources)
338 };
339 for buffer in resources.buffers.into_iter().filter_map(|b| b.upgrade()) {
340 buffer.destroy();
341 }
342 for texture in resources.textures.into_iter().filter_map(|t| t.upgrade()) {
343 texture.destroy();
344 }
345 }
346
347 pub fn record_error(&self, kind: &'static str, message: impl Into<String>) {
348 self.errors.lock().unwrap().push(GpuError {
349 kind,
350 message: message.into(),
351 });
352 }
353
354 pub fn has_errors(&self) -> bool {
355 !self.errors.lock().unwrap().is_empty()
356 }
357
358 pub fn take_errors(&self) -> Vec<GpuError> {
359 std::mem::take(&mut *self.errors.lock().unwrap())
360 }
361
362 pub fn checked<T>(&self, operation: impl FnOnce() -> T) -> T {
367 let device = &self.context.device;
368 let internal = device.push_error_scope(wgpu::ErrorFilter::Internal);
369 let oom = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
370 let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
371 let result = operation();
372 for error in [
373 pollster::block_on(validation.pop()),
374 pollster::block_on(oom.pop()),
375 pollster::block_on(internal.pop()),
376 ]
377 .into_iter()
378 .flatten()
379 {
380 let kind = match &error {
381 wgpu::Error::Validation { .. } => "validation",
382 wgpu::Error::OutOfMemory { .. } => "out-of-memory",
383 wgpu::Error::Internal { .. } => "internal",
384 };
385 self.record_error(kind, error.to_string());
386 }
387 result
388 }
389}