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 parent: Option<Arc<Context>>,
44 _owner: Option<Arc<dyn std::any::Any + Send + Sync>>,
46}
47
48impl Context {
49 pub fn from_shared(
50 adapter: Arc<wgpu::Adapter>,
51 device: Arc<wgpu::Device>,
52 queue: Arc<wgpu::Queue>,
53 ) -> Self {
54 Self {
55 adapter,
56 device,
57 queue,
58 loss: Arc::new(Mutex::new(None)),
59 parent: None,
60 _owner: None,
61 }
62 }
63
64 pub fn from_shared_with_owner(
67 adapter: Arc<wgpu::Adapter>,
68 device: Arc<wgpu::Device>,
69 queue: Arc<wgpu::Queue>,
70 owner: Arc<dyn std::any::Any + Send + Sync>,
71 ) -> Self {
72 Self {
73 _owner: Some(owner),
74 ..Self::from_shared(adapter, device, queue)
75 }
76 }
77
78 pub fn notify_lost(&self, reason: &'static str, message: impl Into<String>) {
79 let mut loss = self.loss.lock().unwrap();
80 if loss.is_none() {
81 *loss = Some(DeviceLoss {
82 reason,
83 message: message.into(),
84 });
85 }
86 }
87
88 pub fn loss(&self) -> Option<DeviceLoss> {
89 self.loss
90 .lock()
91 .unwrap()
92 .clone()
93 .or_else(|| self.parent.as_ref()?.loss())
94 }
95}
96
97pub type AdapterFuture =
98 Pin<Box<dyn Future<Output = Result<Option<Adapter>, String>> + Send + 'static>>;
99
100pub trait GpuHost: Send + Sync {
101 fn request_adapter(&self, options: AdapterOptions) -> AdapterFuture;
105}
106
107fn host_slot() -> &'static RwLock<Option<Arc<dyn GpuHost>>> {
108 static HOST: OnceLock<RwLock<Option<Arc<dyn GpuHost>>>> = OnceLock::new();
109 HOST.get_or_init(|| RwLock::new(None))
110}
111
112pub fn set_host(host: Option<Arc<dyn GpuHost>>) {
115 *host_slot().write().unwrap() = host;
116}
117
118pub async fn request_adapter(options: AdapterOptions) -> Result<Option<Adapter>, String> {
119 let host = host_slot().read().unwrap().clone();
120 if let Some(host) = host {
121 return host.request_adapter(options).await;
122 }
123 let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle();
127 descriptor.backends = if cfg!(target_os = "windows") {
128 wgpu::Backends::DX12
129 } else {
130 wgpu::Backends::PRIMARY
131 };
132 descriptor.flags |= wgpu::InstanceFlags::AUTOMATIC_TIMESTAMP_NORMALIZATION;
133 let instance = wgpu::Instance::new(descriptor);
134 match instance
135 .request_adapter(&wgpu::RequestAdapterOptions {
136 power_preference: options.power_preference,
137 force_fallback_adapter: options.force_fallback_adapter,
138 compatible_surface: None,
139 ..Default::default()
140 })
141 .await
142 {
143 Ok(raw) => Ok(Some(Adapter {
144 raw: Arc::new(raw),
145 shared: None,
146 })),
147 Err(_) => Ok(None),
149 }
150}
151
152pub const VIRTUALIZED_FEATURES: wgpu::Features = wgpu::Features::TIMESTAMP_QUERY
155 .union(wgpu::Features::IMMEDIATES)
156 .union(wgpu::Features::EXTERNAL_TEXTURE);
157
158pub fn shareable_capabilities(adapter: &wgpu::Adapter) -> (wgpu::Features, wgpu::Limits) {
162 let features = adapter.features() & VIRTUALIZED_FEATURES;
163 let mut limits = wgpu::Limits::default();
164 if features.contains(wgpu::Features::IMMEDIATES) {
165 limits.max_immediate_size = adapter.limits().max_immediate_size;
166 }
167 (features, limits)
168}
169
170impl Adapter {
171 pub fn features(&self) -> wgpu::Features {
172 match &self.shared {
173 Some(c) if c.queue.get_timestamp_period() != 1.0 => {
176 self.raw.features() - wgpu::Features::TIMESTAMP_QUERY
177 }
178 _ => self.raw.features(),
179 }
180 }
181
182 pub fn limits(&self) -> wgpu::Limits {
183 self.raw.limits()
184 }
185
186 pub async fn request_device(
187 &self,
188 features: wgpu::Features,
189 limits: wgpu::Limits,
190 ) -> Result<Arc<Context>, String> {
191 let available_features = self.features();
192 if !available_features.contains(features) {
193 return Err(format!(
194 "Unsupported requiredFeatures: {:?}",
195 features - available_features
196 ));
197 }
198 let available_limits = self.limits();
199 if !limits.check_limits(&available_limits) {
200 let mut failures = Vec::new();
201 limits.check_limits_with_fail_fn(
202 &available_limits,
203 false,
204 |name, requested, allowed| {
205 failures.push(format!(
206 "{name}: requested {requested}, available {allowed}"
207 ));
208 },
209 );
210 return Err(format!(
211 "Unsupported requiredLimits: {}",
212 failures.join(", ")
213 ));
214 }
215 let mut native_features =
216 features | (available_features & wgpu::Features::EXTERNAL_TEXTURE);
217 if limits.max_immediate_size > 0 {
218 native_features |= wgpu::Features::IMMEDIATES;
219 }
220 if let Some(context) = &self.shared {
221 let physical = context.device.limits();
222 let comparable = wgpu::Limits {
223 max_immediate_size: physical.max_immediate_size,
224 ..limits.clone()
225 };
226 if context.adapter.as_ref() != self.raw.as_ref() {
227 return Err("Shared GPU context belongs to a different adapter".into());
228 }
229 if let Some(loss) = context.loss() {
230 return Err(format!("Shared GPU device is lost: {}", loss.message));
231 }
232 let enabled = context.device.features();
235 if enabled.contains(native_features)
236 && VIRTUALIZED_FEATURES.contains(enabled - native_features)
237 && comparable == physical
238 && limits.max_immediate_size <= physical.max_immediate_size
239 {
240 return Ok(context.clone());
241 }
242 }
243 let (device, queue) = self
244 .raw
245 .request_device(&wgpu::DeviceDescriptor {
246 label: Some("redjs WebGPU"),
247 required_features: native_features,
248 required_limits: limits,
249 memory_hints: wgpu::MemoryHints::MemoryUsage,
250 ..Default::default()
251 })
252 .await
253 .map_err(|e| e.to_string())?;
254 let context = Arc::new(Context {
255 parent: self.shared.clone(),
256 ..Context::from_shared(self.raw.clone(), Arc::new(device), Arc::new(queue))
257 });
258 let loss = context.loss.clone();
261 context
262 .device
263 .set_device_lost_callback(move |reason, message| {
264 let mut state = loss.lock().unwrap();
265 if state.is_none() {
266 *state = Some(DeviceLoss {
267 reason: if reason == wgpu::DeviceLostReason::Destroyed {
268 "destroyed"
269 } else {
270 "unknown"
271 },
272 message,
273 });
274 }
275 });
276 Ok(context)
277 }
278}
279
280pub fn scoped<T>(device: &wgpu::Device, operation: impl FnOnce() -> T) -> (T, Option<wgpu::Error>) {
283 let internal = device.push_error_scope(wgpu::ErrorFilter::Internal);
284 let oom = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
285 let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
286 let result = operation();
287 let error = [
288 pollster::block_on(validation.pop()),
289 pollster::block_on(oom.pop()),
290 pollster::block_on(internal.pop()),
291 ]
292 .into_iter()
293 .flatten()
294 .next();
295 (result, error)
296}
297
298pub(crate) fn pump(
302 device: &wgpu::Device,
303 pause: &mut std::time::Duration,
304) -> Result<wgpu::PollStatus, wgpu::PollError> {
305 std::thread::sleep(*pause);
306 *pause = (*pause * 2).clamp(
307 std::time::Duration::from_micros(50),
308 std::time::Duration::from_millis(1),
309 );
310 device.poll(wgpu::PollType::Poll)
311}
312
313#[derive(Clone, Debug)]
314pub struct GpuError {
315 pub kind: &'static str,
317 pub message: String,
318}
319
320#[derive(Default)]
321struct Resources {
322 buffers: Vec<Weak<wgpu::Buffer>>,
323 textures: Vec<Weak<wgpu::Texture>>,
324}
325
326pub struct Client {
329 pub context: Arc<Context>,
330 pub id: u64,
331 pub features: wgpu::Features,
332 pub limits: wgpu::Limits,
333 pub destroyed: AtomicBool,
334 resources: Mutex<Resources>,
335 pub(crate) video_blits:
336 Mutex<std::collections::HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>,
337 errors: Mutex<Vec<GpuError>>,
338}
339
340impl Client {
341 pub fn new(context: Arc<Context>) -> Arc<Self> {
342 let features = context.device.features();
343 let limits = context.device.limits();
344 Self::new_with_capabilities(context, features, limits)
345 }
346
347 pub fn new_with_capabilities(
348 context: Arc<Context>,
349 features: wgpu::Features,
350 limits: wgpu::Limits,
351 ) -> Arc<Self> {
352 static NEXT: AtomicU64 = AtomicU64::new(1);
353 Arc::new(Self {
354 context,
355 id: NEXT.fetch_add(1, Ordering::Relaxed),
356 features,
357 limits,
358 destroyed: AtomicBool::new(false),
359 resources: Mutex::new(Resources::default()),
360 video_blits: Mutex::default(),
361 errors: Mutex::new(Vec::new()),
362 })
363 }
364
365 pub fn check(&self) -> Result<(), String> {
366 if self.destroyed.load(Ordering::Acquire) {
367 return Err("GPUDevice has been destroyed".into());
368 }
369 if let Some(loss) = self.context.loss() {
370 return Err(format!("GPUDevice is lost: {}", loss.message));
371 }
372 Ok(())
373 }
374
375 pub fn track_buffer(&self, buffer: &Arc<wgpu::Buffer>) {
376 let mut resources = self.resources.lock().unwrap();
377 if self.destroyed.load(Ordering::Acquire) {
378 drop(resources);
379 buffer.destroy();
380 } else {
381 resources.buffers.retain(|b| b.strong_count() != 0);
382 resources.buffers.push(Arc::downgrade(buffer));
383 }
384 }
385
386 pub fn track_texture(&self, texture: &Arc<wgpu::Texture>) {
387 let mut resources = self.resources.lock().unwrap();
388 if self.destroyed.load(Ordering::Acquire) {
389 drop(resources);
390 texture.destroy();
391 } else {
392 resources.textures.retain(|t| t.strong_count() != 0);
393 resources.textures.push(Arc::downgrade(texture));
394 }
395 }
396
397 pub(super) fn release_presented_texture(&self, texture: &Arc<wgpu::Texture>) -> bool {
400 let mut resources = self.resources.lock().unwrap();
401 if self.destroyed.load(Ordering::Acquire) {
402 return false;
403 }
404 resources.textures.retain(|weak| {
405 weak.upgrade()
406 .is_some_and(|raw| !Arc::ptr_eq(&raw, texture))
407 });
408 true
409 }
410
411 pub fn destroy(&self) {
413 let resources = {
414 let mut resources = self.resources.lock().unwrap();
415 if self.destroyed.swap(true, Ordering::AcqRel) {
416 return;
417 }
418 std::mem::take(&mut *resources)
419 };
420 for buffer in resources.buffers.into_iter().filter_map(|b| b.upgrade()) {
421 buffer.destroy();
422 }
423 for texture in resources.textures.into_iter().filter_map(|t| t.upgrade()) {
424 texture.destroy();
425 }
426 }
427
428 pub fn record_error(&self, kind: &'static str, message: impl Into<String>) {
429 self.errors.lock().unwrap().push(GpuError {
430 kind,
431 message: message.into(),
432 });
433 }
434
435 pub fn has_errors(&self) -> bool {
436 !self.errors.lock().unwrap().is_empty()
437 }
438
439 pub fn take_errors(&self) -> Vec<GpuError> {
440 std::mem::take(&mut *self.errors.lock().unwrap())
441 }
442
443 pub fn checked<T>(&self, operation: impl FnOnce() -> T) -> T {
448 let device = &self.context.device;
449 let internal = device.push_error_scope(wgpu::ErrorFilter::Internal);
450 let oom = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
451 let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
452 let result = operation();
453 for error in [
454 pollster::block_on(validation.pop()),
455 pollster::block_on(oom.pop()),
456 pollster::block_on(internal.pop()),
457 ]
458 .into_iter()
459 .flatten()
460 {
461 let kind = match &error {
462 wgpu::Error::Validation { .. } => "validation",
463 wgpu::Error::OutOfMemory { .. } => "out-of-memory",
464 wgpu::Error::Internal { .. } => "internal",
465 };
466 self.record_error(kind, error.to_string());
467 }
468 result
469 }
470}