Debian Codegraph @

third_party/rust/wgpu-core/src/instance.rs

raw
1 use alloc::{
2 borrow::{Cow, ToOwned as _},
3 boxed::Box,
4 string::String,
5 sync::Arc,
6 vec,
7 vec::Vec,
8 };
9
10 use hashbrown::HashMap;
11 use thiserror::Error;
12
13 use crate::{
14 api_log, api_log_debug,
15 device::{queue::Queue, resource::Device, DeviceDescriptor, DeviceError},
16 global::Global,
17 hal_api::HalApi,
18 id::{markers, AdapterId, DeviceId, QueueId, SurfaceId},
19 lock::{rank, Mutex},
20 present::Presentation,
21 resource::ResourceType,
22 resource_log,
23 timestamp_normalization::TimestampNormalizerInitError,
24 DOWNLEVEL_WARNING_MESSAGE,
25 };
26
27 use wgt::{Backend, Backends, PowerPreference};
28
29 pub type RequestAdapterOptions = wgt::RequestAdapterOptions<SurfaceId>;
30
31 #[derive(Clone, Debug, Error)]
32 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
33 #[error("Limit '{name}' value {requested} is better than allowed {allowed}")]
34 pub struct FailedLimit {
35 name: Cow<'static, str>,
36 requested: u64,
37 allowed: u64,
38 }
39
40 fn check_limits(requested: &wgt::Limits, allowed: &wgt::Limits) -> Vec<FailedLimit> {
41 let mut failed = Vec::new();
42
43 requested.check_limits_with_fail_fn(allowed, false, |name, requested, allowed| {
44 failed.push(FailedLimit {
45 name: Cow::Borrowed(name),
46 requested,
47 allowed,
48 })
49 });
50
51 failed
52 }
53
54 #[test]
55 fn downlevel_default_limits_less_than_default_limits() {
56 let res = check_limits(&wgt::Limits::downlevel_defaults(), &wgt::Limits::default());
57 assert!(
58 res.is_empty(),
59 "Downlevel limits are greater than default limits",
60 )
61 }
62
63 #[derive(Default)]
64 pub struct Instance {
65 #[allow(dead_code)]
66 name: String,
67
68 /// List of instances per `wgpu-hal` backend.
69 ///
70 /// The ordering in this list implies prioritization and needs to be preserved.
71 instance_per_backend: Vec<(Backend, Box<dyn hal::DynInstance>)>,
72
73 /// The backends that were requested by the user.
74 requested_backends: Backends,
75
76 /// The backends that we could have attempted to obtain from `wgpu-hal` —
77 /// those for which support is compiled in, currently.
78 ///
79 /// The union of this and `requested_backends` is the set of backends that would be used,
80 /// independent of whether accessing the drivers/hardware for them succeeds.
81 /// To obtain the set of backends actually in use by this instance, check
82 /// `instance_per_backend` instead.
83 supported_backends: Backends,
84
85 pub flags: wgt::InstanceFlags,
86 }
87
88 impl Instance {
89 pub fn new(name: &str, instance_desc: &wgt::InstanceDescriptor) -> Self {
90 let mut this = Self {
91 name: name.to_owned(),
92 instance_per_backend: Vec::new(),
93 requested_backends: instance_desc.backends,
94 supported_backends: Backends::empty(),
95 flags: instance_desc.flags,
96 };
97
98 #[cfg(vulkan)]
99 this.try_add_hal(hal::api::Vulkan, instance_desc);
100 #[cfg(metal)]
101 this.try_add_hal(hal::api::Metal, instance_desc);
102 #[cfg(dx12)]
103 this.try_add_hal(hal::api::Dx12, instance_desc);
104 #[cfg(gles)]
105 this.try_add_hal(hal::api::Gles, instance_desc);
106 #[cfg(feature = "noop")]
107 this.try_add_hal(hal::api::Noop, instance_desc);
108
109 this
110 }
111
112 /// Helper for `Instance::new()`; attempts to add a single `wgpu-hal` backend to this instance.
113 fn try_add_hal<A: HalApi>(&mut self, _: A, instance_desc: &wgt::InstanceDescriptor) {
114 // Whether or not the backend was requested, and whether or not it succeeds,
115 // note that we *could* try it.
116 self.supported_backends |= A::VARIANT.into();
117
118 if !instance_desc.backends.contains(A::VARIANT.into()) {
119 log::trace!("Instance::new: backend {:?} not requested", A::VARIANT);
120 return;
121 }
122
123 let hal_desc = hal::InstanceDescriptor {
124 name: "wgpu",
125 flags: self.flags,
126 memory_budget_thresholds: instance_desc.memory_budget_thresholds,
127 backend_options: instance_desc.backend_options.clone(),
128 };
129
130 use hal::Instance as _;
131 match unsafe { A::Instance::init(&hal_desc) } {
132 Ok(instance) => {
133 log::debug!("Instance::new: created {:?} backend", A::VARIANT);
134 self.instance_per_backend
135 .push((A::VARIANT, Box::new(instance)));
136 }
137 Err(err) => {
138 log::debug!(
139 "Instance::new: failed to create {:?} backend: {:?}",
140 A::VARIANT,
141 err
142 );
143 }
144 }
145 }
146
147 pub(crate) fn from_hal_instance<A: HalApi>(
148 name: String,
149 hal_instance: <A as hal::Api>::Instance,
150 ) -> Self {
151 Self {
152 name,
153 instance_per_backend: vec![(A::VARIANT, Box::new(hal_instance))],
154 requested_backends: A::VARIANT.into(),
155 supported_backends: A::VARIANT.into(),
156 flags: wgt::InstanceFlags::default(),
157 }
158 }
159
160 pub fn raw(&self, backend: Backend) -> Option<&dyn hal::DynInstance> {
161 self.instance_per_backend
162 .iter()
163 .find_map(|(instance_backend, instance)| {
164 (*instance_backend == backend).then(|| instance.as_ref())
165 })
166 }
167
168 /// # Safety
169 ///
170 /// - The raw instance handle returned must not be manually destroyed.
171 pub unsafe fn as_hal<A: HalApi>(&self) -> Option<&A::Instance> {
172 self.raw(A::VARIANT).map(|instance| {
173 instance
174 .as_any()
175 .downcast_ref()
176 // This should be impossible. It would mean that backend instance and enum type are mismatching.
177 .expect("Stored instance is not of the correct type")
178 })
179 }
180
181 /// Creates a new surface targeting the given display/window handles.
182 ///
183 /// Internally attempts to create hal surfaces for all enabled backends.
184 ///
185 /// Fails only if creation for surfaces for all enabled backends fails in which case
186 /// the error for each enabled backend is listed.
187 /// Vice versa, if creation for any backend succeeds, success is returned.
188 /// Surface creation errors are logged to the debug log in any case.
189 ///
190 /// # Safety
191 ///
192 /// - `display_handle` must be a valid object to create a surface upon.
193 /// - `window_handle` must remain valid as long as the returned
194 /// [`SurfaceId`] is being used.
195 #[cfg(feature = "raw-window-handle")]
196 pub unsafe fn create_surface(
197 &self,
198 display_handle: raw_window_handle::RawDisplayHandle,
199 window_handle: raw_window_handle::RawWindowHandle,
200 ) -> Result<Surface, CreateSurfaceError> {
201 profiling::scope!("Instance::create_surface");
202
203 let mut errors = HashMap::default();
204 let mut surface_per_backend = HashMap::default();
205
206 for (backend, instance) in &self.instance_per_backend {
207 match unsafe {
208 instance
209 .as_ref()
210 .create_surface(display_handle, window_handle)
211 } {
212 Ok(raw) => {
213 surface_per_backend.insert(*backend, raw);
214 }
215 Err(err) => {
216 log::debug!(
217 "Instance::create_surface: failed to create surface for {:?}: {:?}",
218 backend,
219 err
220 );
221 errors.insert(*backend, err);
222 }
223 }
224 }
225
226 if surface_per_backend.is_empty() {
227 Err(CreateSurfaceError::FailedToCreateSurfaceForAnyBackend(
228 errors,
229 ))
230 } else {
231 let surface = Surface {
232 presentation: Mutex::new(rank::SURFACE_PRESENTATION, None),
233 surface_per_backend,
234 };
235
236 Ok(surface)
237 }
238 }
239
240 /// Creates a new surface from the given drm configuration.
241 ///
242 /// # Safety
243 ///
244 /// - All parameters must point to valid DRM values.
245 ///
246 /// # Platform Support
247 ///
248 /// This function is only available on non-apple Unix-like platforms (Linux, FreeBSD) and
249 /// currently only works with the Vulkan backend.
250 #[cfg(all(unix, not(target_vendor = "apple"), not(target_family = "wasm")))]
251 #[cfg_attr(not(vulkan), expect(unused_variables))]
252 pub unsafe fn create_surface_from_drm(
253 &self,
254 fd: i32,
255 plane: u32,
256 connector_id: u32,
257 width: u32,
258 height: u32,
259 refresh_rate: u32,
260 ) -> Result<Surface, CreateSurfaceError> {
261 profiling::scope!("Instance::create_surface_from_drm");
262
263 let mut errors = HashMap::default();
264 let mut surface_per_backend: HashMap<Backend, Box<dyn hal::DynSurface>> =
265 HashMap::default();
266
267 #[cfg(vulkan)]
268 {
269 let instance = unsafe { self.as_hal::<hal::api::Vulkan>() }
270 .ok_or(CreateSurfaceError::BackendNotEnabled(Backend::Vulkan))?;
271
272 // Safety must be upheld by the caller
273 match unsafe {
274 instance.create_surface_from_drm(
275 fd,
276 plane,
277 connector_id,
278 width,
279 height,
280 refresh_rate,
281 )
282 } {
283 Ok(surface) => {
284 surface_per_backend.insert(Backend::Vulkan, Box::new(surface));
285 }
286 Err(err) => {
287 errors.insert(Backend::Vulkan, err);
288 }
289 }
290 }
291
292 if surface_per_backend.is_empty() {
293 Err(CreateSurfaceError::FailedToCreateSurfaceForAnyBackend(
294 errors,
295 ))
296 } else {
297 let surface = Surface {
298 presentation: Mutex::new(rank::SURFACE_PRESENTATION, None),
299 surface_per_backend,
300 };
301
302 Ok(surface)
303 }
304 }
305
306 /// # Safety
307 ///
308 /// `layer` must be a valid pointer.
309 #[cfg(metal)]
310 pub unsafe fn create_surface_metal(
311 &self,
312 layer: *mut core::ffi::c_void,
313 ) -> Result<Surface, CreateSurfaceError> {
314 profiling::scope!("Instance::create_surface_metal");
315
316 let instance = unsafe { self.as_hal::<hal::api::Metal>() }
317 .ok_or(CreateSurfaceError::BackendNotEnabled(Backend::Metal))?;
318
319 let layer = layer.cast();
320 // SAFETY: We do this cast and deref. (rather than using `metal` to get the
321 // object we want) to avoid direct coupling on the `metal` crate.
322 //
323 // To wit, this pointer…
324 //
325 // - …is properly aligned.
326 // - …is dereferenceable to a `MetalLayerRef` as an invariant of the `metal`
327 // field.
328 // - …points to an _initialized_ `MetalLayerRef`.
329 // - …is only ever aliased via an immutable reference that lives within this
330 // lexical scope.
331 let layer = unsafe { &*layer };
332 let raw_surface: Box<dyn hal::DynSurface> =
333 Box::new(instance.create_surface_from_layer(layer));
334
335 let surface = Surface {
336 presentation: Mutex::new(rank::SURFACE_PRESENTATION, None),
337 surface_per_backend: core::iter::once((Backend::Metal, raw_surface)).collect(),
338 };
339
340 Ok(surface)
341 }
342
343 #[cfg(dx12)]
344 fn create_surface_dx12(
345 &self,
346 create_surface_func: impl FnOnce(&hal::dx12::Instance) -> hal::dx12::Surface,
347 ) -> Result<Surface, CreateSurfaceError> {
348 let instance = unsafe { self.as_hal::<hal::api::Dx12>() }
349 .ok_or(CreateSurfaceError::BackendNotEnabled(Backend::Dx12))?;
350 let surface: Box<dyn hal::DynSurface> = Box::new(create_surface_func(instance));
351
352 let surface = Surface {
353 presentation: Mutex::new(rank::SURFACE_PRESENTATION, None),
354 surface_per_backend: core::iter::once((Backend::Dx12, surface)).collect(),
355 };
356
357 Ok(surface)
358 }
359
360 #[cfg(dx12)]
361 /// # Safety
362 ///
363 /// The visual must be valid and able to be used to make a swapchain with.
364 pub unsafe fn create_surface_from_visual(
365 &self,
366 visual: *mut core::ffi::c_void,
367 ) -> Result<Surface, CreateSurfaceError> {
368 profiling::scope!("Instance::instance_create_surface_from_visual");
369 self.create_surface_dx12(|inst| unsafe { inst.create_surface_from_visual(visual) })
370 }
371
372 #[cfg(dx12)]
373 /// # Safety
374 ///
375 /// The surface_handle must be valid and able to be used to make a swapchain with.
376 pub unsafe fn create_surface_from_surface_handle(
377 &self,
378 surface_handle: *mut core::ffi::c_void,
379 ) -> Result<Surface, CreateSurfaceError> {
380 profiling::scope!("Instance::instance_create_surface_from_surface_handle");
381 self.create_surface_dx12(|inst| unsafe {
382 inst.create_surface_from_surface_handle(surface_handle)
383 })
384 }
385
386 #[cfg(dx12)]
387 /// # Safety
388 ///
389 /// The swap_chain_panel must be valid and able to be used to make a swapchain with.
390 pub unsafe fn create_surface_from_swap_chain_panel(
391 &self,
392 swap_chain_panel: *mut core::ffi::c_void,
393 ) -> Result<Surface, CreateSurfaceError> {
394 profiling::scope!("Instance::instance_create_surface_from_swap_chain_panel");
395 self.create_surface_dx12(|inst| unsafe {
396 inst.create_surface_from_swap_chain_panel(swap_chain_panel)
397 })
398 }
399
400 pub fn enumerate_adapters(&self, backends: Backends) -> Vec<Adapter> {
401 profiling::scope!("Instance::enumerate_adapters");
402 api_log!("Instance::enumerate_adapters");
403
404 let mut adapters = Vec::new();
405 for (_backend, instance) in self
406 .instance_per_backend
407 .iter()
408 .filter(|(backend, _)| backends.contains(Backends::from(*backend)))
409 {
410 // NOTE: We might be using `profiling` without any features. The empty backend of this
411 // macro emits no code, so unused code linting changes depending on the backend.
412 profiling::scope!("enumerating", &*alloc::format!("{:?}", _backend));
413
414 let hal_adapters = unsafe { instance.enumerate_adapters(None) };
415 for raw in hal_adapters {
416 let adapter = Adapter::new(raw);
417 api_log_debug!("Adapter {:?}", adapter.raw.info);
418 adapters.push(adapter);
419 }
420 }
421 adapters
422 }
423
424 pub fn request_adapter(
425 &self,
426 desc: &wgt::RequestAdapterOptions<&Surface>,
427 backends: Backends,
428 ) -> Result<Adapter, wgt::RequestAdapterError> {
429 profiling::scope!("Instance::request_adapter");
430 api_log!("Instance::request_adapter");
431
432 let mut adapters = Vec::new();
433 let mut incompatible_surface_backends = Backends::empty();
434 let mut no_fallback_backends = Backends::empty();
435 let mut no_adapter_backends = Backends::empty();
436
437 for &(backend, ref instance) in self
438 .instance_per_backend
439 .iter()
440 .filter(|&&(backend, _)| backends.contains(Backends::from(backend)))
441 {
442 let compatible_hal_surface = desc
443 .compatible_surface
444 .and_then(|surface| surface.raw(backend));
445
446 let mut backend_adapters =
447 unsafe { instance.enumerate_adapters(compatible_hal_surface) };
448 if backend_adapters.is_empty() {
449 no_adapter_backends |= Backends::from(backend);
450 // by continuing, we avoid setting the further error bits below
451 continue;
452 }
453
454 if desc.force_fallback_adapter {
455 backend_adapters.retain(|exposed| exposed.info.device_type == wgt::DeviceType::Cpu);
456 if backend_adapters.is_empty() {
457 no_fallback_backends |= Backends::from(backend);
458 continue;
459 }
460 }
461
462 if let Some(surface) = desc.compatible_surface {
463 backend_adapters.retain(|exposed| {
464 let capabilities = surface.get_capabilities_with_raw(exposed);
465 if let Err(err) = capabilities {
466 log::debug!(
467 "Adapter {:?} not compatible with surface: {}",
468 exposed.info,
469 err
470 );
471 incompatible_surface_backends |= Backends::from(backend);
472 false
473 } else {
474 true
475 }
476 });
477 if backend_adapters.is_empty() {
478 incompatible_surface_backends |= Backends::from(backend);
479 continue;
480 }
481 }
482 adapters.extend(backend_adapters);
483 }
484
485 match desc.power_preference {
486 PowerPreference::LowPower => {
487 sort(&mut adapters, true);
488 }
489 PowerPreference::HighPerformance => {
490 sort(&mut adapters, false);
491 }
492 PowerPreference::None => {}
493 };
494
495 fn sort(adapters: &mut [hal::DynExposedAdapter], prefer_integrated_gpu: bool) {
496 adapters
497 .sort_by_key(|adapter| get_order(adapter.info.device_type, prefer_integrated_gpu));
498 }
499
500 fn get_order(device_type: wgt::DeviceType, prefer_integrated_gpu: bool) -> u8 {
501 // Since devices of type "Other" might really be "Unknown" and come
502 // from APIs like OpenGL that don't specify device type, Prefer more
503 // Specific types over Other.
504 //
505 // This means that backends which do provide accurate device types
506 // will be preferred if their device type indicates an actual
507 // hardware GPU (integrated or discrete).
508 match device_type {
509 wgt::DeviceType::DiscreteGpu if prefer_integrated_gpu => 2,
510 wgt::DeviceType::IntegratedGpu if prefer_integrated_gpu => 1,
511 wgt::DeviceType::DiscreteGpu => 1,
512 wgt::DeviceType::IntegratedGpu => 2,
513 wgt::DeviceType::Other => 3,
514 wgt::DeviceType::VirtualGpu => 4,
515 wgt::DeviceType::Cpu => 5,
516 }
517 }
518
519 // `request_adapter` can be a bit of a black box.
520 // Shine some light on its decision in debug log.
521 if adapters.is_empty() {
522 log::debug!("Request adapter didn't find compatible adapters.");
523 } else {
524 log::debug!(
525 "Found {} compatible adapters. Sorted by preference:",
526 adapters.len()
527 );
528 for adapter in &adapters {
529 log::debug!("* {:?}", adapter.info);
530 }
531 }
532
533 if let Some(adapter) = adapters.into_iter().next() {
534 api_log_debug!("Request adapter result {:?}", adapter.info);
535 let adapter = Adapter::new(adapter);
536 Ok(adapter)
537 } else {
538 Err(wgt::RequestAdapterError::NotFound {
539 supported_backends: self.supported_backends,
540 requested_backends: self.requested_backends,
541 active_backends: self.active_backends(),
542 no_fallback_backends,
543 no_adapter_backends,
544 incompatible_surface_backends,
545 })
546 }
547 }
548
549 fn active_backends(&self) -> Backends {
550 self.instance_per_backend
551 .iter()
552 .map(|&(backend, _)| Backends::from(backend))
553 .collect()
554 }
555 }
556
557 pub struct Surface {
558 pub(crate) presentation: Mutex<Option<Presentation>>,
559 pub surface_per_backend: HashMap<Backend, Box<dyn hal::DynSurface>>,
560 }
561
562 impl ResourceType for Surface {
563 const TYPE: &'static str = "Surface";
564 }
565 impl crate::storage::StorageItem for Surface {
566 type Marker = markers::Surface;
567 }
568
569 impl Surface {
570 pub fn get_capabilities(
571 &self,
572 adapter: &Adapter,
573 ) -> Result<hal::SurfaceCapabilities, GetSurfaceSupportError> {
574 self.get_capabilities_with_raw(&adapter.raw)
575 }
576
577 pub fn get_capabilities_with_raw(
578 &self,
579 adapter: &hal::DynExposedAdapter,
580 ) -> Result<hal::SurfaceCapabilities, GetSurfaceSupportError> {
581 let backend = adapter.backend();
582 let suf = self
583 .raw(backend)
584 .ok_or(GetSurfaceSupportError::NotSupportedByBackend(backend))?;
585 profiling::scope!("surface_capabilities");
586 let caps = unsafe { adapter.adapter.surface_capabilities(suf) }
587 .ok_or(GetSurfaceSupportError::FailedToRetrieveSurfaceCapabilitiesForAdapter)?;
588 Ok(caps)
589 }
590
591 pub fn raw(&self, backend: Backend) -> Option<&dyn hal::DynSurface> {
592 self.surface_per_backend
593 .get(&backend)
594 .map(|surface| surface.as_ref())
595 }
596 }
597
598 impl Drop for Surface {
599 fn drop(&mut self) {
600 if let Some(present) = self.presentation.lock().take() {
601 for (&backend, surface) in &self.surface_per_backend {
602 if backend == present.device.backend() {
603 unsafe { surface.unconfigure(present.device.raw()) };
604 }
605 }
606 }
607 }
608 }
609
610 pub struct Adapter {
611 pub(crate) raw: hal::DynExposedAdapter,
612 }
613
614 impl Adapter {
615 pub fn new(mut raw: hal::DynExposedAdapter) -> Self {
616 // WebGPU requires this offset alignment as lower bound on all adapters.
617 const MIN_BUFFER_OFFSET_ALIGNMENT_LOWER_BOUND: u32 = 32;
618
619 let limits = &mut raw.capabilities.limits;
620
621 limits.min_uniform_buffer_offset_alignment = limits
622 .min_uniform_buffer_offset_alignment
623 .max(MIN_BUFFER_OFFSET_ALIGNMENT_LOWER_BOUND);
624 limits.min_storage_buffer_offset_alignment = limits
625 .min_storage_buffer_offset_alignment
626 .max(MIN_BUFFER_OFFSET_ALIGNMENT_LOWER_BOUND);
627
628 Self { raw }
629 }
630
631 /// Returns the backend this adapter is using.
632 pub fn backend(&self) -> Backend {
633 self.raw.backend()
634 }
635
636 pub fn is_surface_supported(&self, surface: &Surface) -> bool {
637 // If get_capabilities returns Err, then the API does not advertise support for the surface.
638 //
639 // This could occur if the user is running their app on Wayland but Vulkan does not support
640 // VK_KHR_wayland_surface.
641 surface.get_capabilities(self).is_ok()
642 }
643
644 pub fn get_info(&self) -> wgt::AdapterInfo {
645 self.raw.info.clone()
646 }
647
648 pub fn features(&self) -> wgt::Features {
649 self.raw.features
650 }
651
652 pub fn limits(&self) -> wgt::Limits {
653 self.raw.capabilities.limits.clone()
654 }
655
656 pub fn downlevel_capabilities(&self) -> wgt::DownlevelCapabilities {
657 self.raw.capabilities.downlevel.clone()
658 }
659
660 pub fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp {
661 unsafe { self.raw.adapter.get_presentation_timestamp() }
662 }
663
664 pub fn get_texture_format_features(
665 &self,
666 format: wgt::TextureFormat,
667 ) -> wgt::TextureFormatFeatures {
668 use hal::TextureFormatCapabilities as Tfc;
669
670 let caps = unsafe { self.raw.adapter.texture_format_capabilities(format) };
671 let mut allowed_usages = wgt::TextureUsages::empty();
672
673 allowed_usages.set(wgt::TextureUsages::COPY_SRC, caps.contains(Tfc::COPY_SRC));
674 allowed_usages.set(wgt::TextureUsages::COPY_DST, caps.contains(Tfc::COPY_DST));
675 allowed_usages.set(
676 wgt::TextureUsages::TEXTURE_BINDING,
677 caps.contains(Tfc::SAMPLED),
678 );
679 allowed_usages.set(
680 wgt::TextureUsages::STORAGE_BINDING,
681 caps.intersects(
682 Tfc::STORAGE_WRITE_ONLY
683 | Tfc::STORAGE_READ_ONLY
684 | Tfc::STORAGE_READ_WRITE
685 | Tfc::STORAGE_ATOMIC,
686 ),
687 );
688 allowed_usages.set(
689 wgt::TextureUsages::RENDER_ATTACHMENT,
690 caps.intersects(Tfc::COLOR_ATTACHMENT | Tfc::DEPTH_STENCIL_ATTACHMENT),
691 );
692 allowed_usages.set(
693 wgt::TextureUsages::STORAGE_ATOMIC,
694 caps.contains(Tfc::STORAGE_ATOMIC),
695 );
696
697 let mut flags = wgt::TextureFormatFeatureFlags::empty();
698 flags.set(
699 wgt::TextureFormatFeatureFlags::STORAGE_READ_ONLY,
700 caps.contains(Tfc::STORAGE_READ_ONLY),
701 );
702 flags.set(
703 wgt::TextureFormatFeatureFlags::STORAGE_WRITE_ONLY,
704 caps.contains(Tfc::STORAGE_WRITE_ONLY),
705 );
706 flags.set(
707 wgt::TextureFormatFeatureFlags::STORAGE_READ_WRITE,
708 caps.contains(Tfc::STORAGE_READ_WRITE),
709 );
710
711 flags.set(
712 wgt::TextureFormatFeatureFlags::STORAGE_ATOMIC,
713 caps.contains(Tfc::STORAGE_ATOMIC),
714 );
715
716 flags.set(
717 wgt::TextureFormatFeatureFlags::FILTERABLE,
718 caps.contains(Tfc::SAMPLED_LINEAR),
719 );
720
721 flags.set(
722 wgt::TextureFormatFeatureFlags::BLENDABLE,
723 caps.contains(Tfc::COLOR_ATTACHMENT_BLEND),
724 );
725
726 flags.set(
727 wgt::TextureFormatFeatureFlags::MULTISAMPLE_X2,
728 caps.contains(Tfc::MULTISAMPLE_X2),
729 );
730 flags.set(
731 wgt::TextureFormatFeatureFlags::MULTISAMPLE_X4,
732 caps.contains(Tfc::MULTISAMPLE_X4),
733 );
734 flags.set(
735 wgt::TextureFormatFeatureFlags::MULTISAMPLE_X8,
736 caps.contains(Tfc::MULTISAMPLE_X8),
737 );
738 flags.set(
739 wgt::TextureFormatFeatureFlags::MULTISAMPLE_X16,
740 caps.contains(Tfc::MULTISAMPLE_X16),
741 );
742
743 flags.set(
744 wgt::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE,
745 caps.contains(Tfc::MULTISAMPLE_RESOLVE),
746 );
747
748 wgt::TextureFormatFeatures {
749 allowed_usages,
750 flags,
751 }
752 }
753
754 #[allow(clippy::type_complexity)]
755 fn create_device_and_queue_from_hal(
756 self: &Arc<Self>,
757 hal_device: hal::DynOpenDevice,
758 desc: &DeviceDescriptor,
759 instance_flags: wgt::InstanceFlags,
760 ) -> Result<(Arc<Device>, Arc<Queue>), RequestDeviceError> {
761 api_log!("Adapter::create_device");
762
763 let device = Device::new(hal_device.device, self, desc, instance_flags)?;
764 let device = Arc::new(device);
765
766 let queue = Queue::new(device.clone(), hal_device.queue)?;
767 let queue = Arc::new(queue);
768
769 device.set_queue(&queue);
770 device.late_init_resources_with_queue()?;
771
772 Ok((device, queue))
773 }
774
775 pub fn create_device_and_queue(
776 self: &Arc<Self>,
777 desc: &DeviceDescriptor,
778 instance_flags: wgt::InstanceFlags,
779 ) -> Result<(Arc<Device>, Arc<Queue>), RequestDeviceError> {
780 // Verify all features were exposed by the adapter
781 if !self.raw.features.contains(desc.required_features) {
782 return Err(RequestDeviceError::UnsupportedFeature(
783 desc.required_features - self.raw.features,
784 ));
785 }
786
787 let caps = &self.raw.capabilities;
788 if Backends::PRIMARY.contains(Backends::from(self.backend()))
789 && !caps.downlevel.is_webgpu_compliant()
790 {
791 let missing_flags = wgt::DownlevelFlags::compliant() - caps.downlevel.flags;
792 log::warn!(
793 "Missing downlevel flags: {:?}\n{}",
794 missing_flags,
795 DOWNLEVEL_WARNING_MESSAGE
796 );
797 log::warn!("{:#?}", caps.downlevel);
798 }
799
800 // Verify feature preconditions
801 if desc
802 .required_features
803 .contains(wgt::Features::MAPPABLE_PRIMARY_BUFFERS)
804 && self.raw.info.device_type == wgt::DeviceType::DiscreteGpu
805 {
806 log::warn!(
807 "Feature MAPPABLE_PRIMARY_BUFFERS enabled on a discrete gpu. \
808 This is a massive performance footgun and likely not what you wanted"
809 );
810 }
811
812 if let Some(failed) = check_limits(&desc.required_limits, &caps.limits).pop() {
813 return Err(RequestDeviceError::LimitsExceeded(failed));
814 }
815
816 let open = unsafe {
817 self.raw.adapter.open(
818 desc.required_features,
819 &desc.required_limits,
820 &desc.memory_hints,
821 )
822 }
823 .map_err(DeviceError::from_hal)?;
824
825 self.create_device_and_queue_from_hal(open, desc, instance_flags)
826 }
827 }
828
829 crate::impl_resource_type!(Adapter);
830 crate::impl_storage_item!(Adapter);
831
832 #[derive(Clone, Debug, Error)]
833 #[non_exhaustive]
834 pub enum GetSurfaceSupportError {
835 #[error("Surface is not supported for the specified backend {0}")]
836 NotSupportedByBackend(Backend),
837 #[error("Failed to retrieve surface capabilities for the specified adapter.")]
838 FailedToRetrieveSurfaceCapabilitiesForAdapter,
839 }
840
841 #[derive(Clone, Debug, Error)]
842 /// Error when requesting a device from the adapter
843 #[non_exhaustive]
844 pub enum RequestDeviceError {
845 #[error(transparent)]
846 Device(#[from] DeviceError),
847 #[error(transparent)]
848 LimitsExceeded(#[from] FailedLimit),
849 #[error("Failed to initialize Timestamp Normalizer")]
850 TimestampNormalizerInitFailed(#[from] TimestampNormalizerInitError),
851 #[error("Unsupported features were requested: {0:?}")]
852 UnsupportedFeature(wgt::Features),
853 }
854
855 #[derive(Clone, Debug, Error)]
856 #[non_exhaustive]
857 pub enum CreateSurfaceError {
858 #[error("The backend {0} was not enabled on the instance.")]
859 BackendNotEnabled(Backend),
860 #[error("Failed to create surface for any enabled backend: {0:?}")]
861 FailedToCreateSurfaceForAnyBackend(HashMap<Backend, hal::InstanceError>),
862 }
863
864 impl Global {
865 /// Creates a new surface targeting the given display/window handles.
866 ///
867 /// Internally attempts to create hal surfaces for all enabled backends.
868 ///
869 /// Fails only if creation for surfaces for all enabled backends fails in which case
870 /// the error for each enabled backend is listed.
871 /// Vice versa, if creation for any backend succeeds, success is returned.
872 /// Surface creation errors are logged to the debug log in any case.
873 ///
874 /// id_in:
875 /// - If `Some`, the id to assign to the surface. A new one will be generated otherwise.
876 ///
877 /// # Safety
878 ///
879 /// - `display_handle` must be a valid object to create a surface upon.
880 /// - `window_handle` must remain valid as long as the returned
881 /// [`SurfaceId`] is being used.
882 #[cfg(feature = "raw-window-handle")]
883 pub unsafe fn instance_create_surface(
884 &self,
885 display_handle: raw_window_handle::RawDisplayHandle,
886 window_handle: raw_window_handle::RawWindowHandle,
887 id_in: Option<SurfaceId>,
888 ) -> Result<SurfaceId, CreateSurfaceError> {
889 let surface = unsafe { self.instance.create_surface(display_handle, window_handle) }?;
890 let id = self.surfaces.prepare(id_in).assign(Arc::new(surface));
891 Ok(id)
892 }
893
894 /// Creates a new surface from the given drm configuration.
895 ///
896 /// # Safety
897 ///
898 /// - All parameters must point to valid DRM values.
899 ///
900 /// # Platform Support
901 ///
902 /// This function is only available on non-apple Unix-like platforms (Linux, FreeBSD) and
903 /// currently only works with the Vulkan backend.
904 #[cfg(all(unix, not(target_vendor = "apple"), not(target_family = "wasm")))]
905 pub unsafe fn instance_create_surface_from_drm(
906 &self,
907 fd: i32,
908 plane: u32,
909 connector_id: u32,
910 width: u32,
911 height: u32,
912 refresh_rate: u32,
913 id_in: Option<SurfaceId>,
914 ) -> Result<SurfaceId, CreateSurfaceError> {
915 let surface = unsafe {
916 self.instance.create_surface_from_drm(
917 fd,
918 plane,
919 connector_id,
920 width,
921 height,
922 refresh_rate,
923 )
924 }?;
925 let id = self.surfaces.prepare(id_in).assign(Arc::new(surface));
926
927 Ok(id)
928 }
929
930 /// # Safety
931 ///
932 /// `layer` must be a valid pointer.
933 #[cfg(metal)]
934 pub unsafe fn instance_create_surface_metal(
935 &self,
936 layer: *mut core::ffi::c_void,
937 id_in: Option<SurfaceId>,
938 ) -> Result<SurfaceId, CreateSurfaceError> {
939 let surface = unsafe { self.instance.create_surface_metal(layer) }?;
940 let id = self.surfaces.prepare(id_in).assign(Arc::new(surface));
941 Ok(id)
942 }
943
944 #[cfg(dx12)]
945 /// # Safety
946 ///
947 /// The visual must be valid and able to be used to make a swapchain with.
948 pub unsafe fn instance_create_surface_from_visual(
949 &self,
950 visual: *mut core::ffi::c_void,
951 id_in: Option<SurfaceId>,
952 ) -> Result<SurfaceId, CreateSurfaceError> {
953 let surface = unsafe { self.instance.create_surface_from_visual(visual) }?;
954 let id = self.surfaces.prepare(id_in).assign(Arc::new(surface));
955 Ok(id)
956 }
957
958 #[cfg(dx12)]
959 /// # Safety
960 ///
961 /// The surface_handle must be valid and able to be used to make a swapchain with.
962 pub unsafe fn instance_create_surface_from_surface_handle(
963 &self,
964 surface_handle: *mut core::ffi::c_void,
965 id_in: Option<SurfaceId>,
966 ) -> Result<SurfaceId, CreateSurfaceError> {
967 let surface = unsafe {
968 self.instance
969 .create_surface_from_surface_handle(surface_handle)
970 }?;
971 let id = self.surfaces.prepare(id_in).assign(Arc::new(surface));
972 Ok(id)
973 }
974
975 #[cfg(dx12)]
976 /// # Safety
977 ///
978 /// The swap_chain_panel must be valid and able to be used to make a swapchain with.
979 pub unsafe fn instance_create_surface_from_swap_chain_panel(
980 &self,
981 swap_chain_panel: *mut core::ffi::c_void,
982 id_in: Option<SurfaceId>,
983 ) -> Result<SurfaceId, CreateSurfaceError> {
984 let surface = unsafe {
985 self.instance
986 .create_surface_from_swap_chain_panel(swap_chain_panel)
987 }?;
988 let id = self.surfaces.prepare(id_in).assign(Arc::new(surface));
989 Ok(id)
990 }
991
992 pub fn surface_drop(&self, id: SurfaceId) {
993 profiling::scope!("Surface::drop");
994
995 api_log!("Surface::drop {id:?}");
996
997 self.surfaces.remove(id);
998 }
999
1000 pub fn enumerate_adapters(&self, backends: Backends) -> Vec<AdapterId> {
1001 let adapters = self.instance.enumerate_adapters(backends);
1002 adapters
1003 .into_iter()
1004 .map(|adapter| self.hub.adapters.prepare(None).assign(Arc::new(adapter)))
1005 .collect()
1006 }
1007
1008 pub fn request_adapter(
1009 &self,
1010 desc: &RequestAdapterOptions,
1011 backends: Backends,
1012 id_in: Option<AdapterId>,
1013 ) -> Result<AdapterId, wgt::RequestAdapterError> {
1014 let compatible_surface = desc.compatible_surface.map(|id| self.surfaces.get(id));
1015 let desc = wgt::RequestAdapterOptions {
1016 power_preference: desc.power_preference,
1017 force_fallback_adapter: desc.force_fallback_adapter,
1018 compatible_surface: compatible_surface.as_deref(),
1019 };
1020 let adapter = self.instance.request_adapter(&desc, backends)?;
1021 let id = self.hub.adapters.prepare(id_in).assign(Arc::new(adapter));
1022 Ok(id)
1023 }
1024
1025 /// # Safety
1026 ///
1027 /// `hal_adapter` must be created from this global internal instance handle.
1028 pub unsafe fn create_adapter_from_hal(
1029 &self,
1030 hal_adapter: hal::DynExposedAdapter,
1031 input: Option<AdapterId>,
1032 ) -> AdapterId {
1033 profiling::scope!("Instance::create_adapter_from_hal");
1034
1035 let fid = self.hub.adapters.prepare(input);
1036 let id = fid.assign(Arc::new(Adapter::new(hal_adapter)));
1037
1038 resource_log!("Created Adapter {:?}", id);
1039 id
1040 }
1041
1042 pub fn adapter_get_info(&self, adapter_id: AdapterId) -> wgt::AdapterInfo {
1043 let adapter = self.hub.adapters.get(adapter_id);
1044 adapter.get_info()
1045 }
1046
1047 pub fn adapter_get_texture_format_features(
1048 &self,
1049 adapter_id: AdapterId,
1050 format: wgt::TextureFormat,
1051 ) -> wgt::TextureFormatFeatures {
1052 let adapter = self.hub.adapters.get(adapter_id);
1053 adapter.get_texture_format_features(format)
1054 }
1055
1056 pub fn adapter_features(&self, adapter_id: AdapterId) -> wgt::Features {
1057 let adapter = self.hub.adapters.get(adapter_id);
1058 adapter.features()
1059 }
1060
1061 pub fn adapter_limits(&self, adapter_id: AdapterId) -> wgt::Limits {
1062 let adapter = self.hub.adapters.get(adapter_id);
1063 adapter.limits()
1064 }
1065
1066 pub fn adapter_downlevel_capabilities(
1067 &self,
1068 adapter_id: AdapterId,
1069 ) -> wgt::DownlevelCapabilities {
1070 let adapter = self.hub.adapters.get(adapter_id);
1071 adapter.downlevel_capabilities()
1072 }
1073
1074 pub fn adapter_get_presentation_timestamp(
1075 &self,
1076 adapter_id: AdapterId,
1077 ) -> wgt::PresentationTimestamp {
1078 let adapter = self.hub.adapters.get(adapter_id);
1079 adapter.get_presentation_timestamp()
1080 }
1081
1082 pub fn adapter_drop(&self, adapter_id: AdapterId) {
1083 profiling::scope!("Adapter::drop");
1084 api_log!("Adapter::drop {adapter_id:?}");
1085
1086 self.hub.adapters.remove(adapter_id);
1087 }
1088 }
1089
1090 impl Global {
1091 pub fn adapter_request_device(
1092 &self,
1093 adapter_id: AdapterId,
1094 desc: &DeviceDescriptor,
1095 device_id_in: Option<DeviceId>,
1096 queue_id_in: Option<QueueId>,
1097 ) -> Result<(DeviceId, QueueId), RequestDeviceError> {
1098 profiling::scope!("Adapter::request_device");
1099 api_log!("Adapter::request_device");
1100
1101 let device_fid = self.hub.devices.prepare(device_id_in);
1102 let queue_fid = self.hub.queues.prepare(queue_id_in);
1103
1104 let adapter = self.hub.adapters.get(adapter_id);
1105 let (device, queue) = adapter.create_device_and_queue(desc, self.instance.flags)?;
1106
1107 let device_id = device_fid.assign(device);
1108 resource_log!("Created Device {:?}", device_id);
1109
1110 let queue_id = queue_fid.assign(queue);
1111 resource_log!("Created Queue {:?}", queue_id);
1112
1113 Ok((device_id, queue_id))
1114 }
1115
1116 /// # Safety
1117 ///
1118 /// - `hal_device` must be created from `adapter_id` or its internal handle.
1119 /// - `desc` must be a subset of `hal_device` features and limits.
1120 pub unsafe fn create_device_from_hal(
1121 &self,
1122 adapter_id: AdapterId,
1123 hal_device: hal::DynOpenDevice,
1124 desc: &DeviceDescriptor,
1125 device_id_in: Option<DeviceId>,
1126 queue_id_in: Option<QueueId>,
1127 ) -> Result<(DeviceId, QueueId), RequestDeviceError> {
1128 profiling::scope!("Global::create_device_from_hal");
1129
1130 let devices_fid = self.hub.devices.prepare(device_id_in);
1131 let queues_fid = self.hub.queues.prepare(queue_id_in);
1132
1133 let adapter = self.hub.adapters.get(adapter_id);
1134 let (device, queue) =
1135 adapter.create_device_and_queue_from_hal(hal_device, desc, self.instance.flags)?;
1136
1137 let device_id = devices_fid.assign(device);
1138 resource_log!("Created Device {:?}", device_id);
1139
1140 let queue_id = queues_fid.assign(queue);
1141 resource_log!("Created Queue {:?}", queue_id);
1142
1143 Ok((device_id, queue_id))
1144 }
1145 }