wgpu/api/adapter.rs
1use core::future::Future;
2#[cfg(wgpu_core)]
3use core::ops::Deref;
4
5use crate::*;
6
7/// Handle to a physical graphics and/or compute device.
8///
9/// Adapters can be created using [`Instance::request_adapter`]
10/// or other [`Instance`] methods.
11///
12/// Adapters can be used to open a connection to the corresponding [`Device`]
13/// on the host system by using [`Adapter::request_device`].
14///
15/// Does not have to be kept alive.
16///
17/// Corresponds to [WebGPU `GPUAdapter`](https://gpuweb.github.io/gpuweb/#gpu-adapter).
18#[derive(Debug, Clone)]
19pub struct Adapter {
20 pub(crate) inner: dispatch::DispatchAdapter,
21}
22#[cfg(send_sync)]
23static_assertions::assert_impl_all!(Adapter: Send, Sync);
24
25crate::cmp::impl_eq_ord_hash_proxy!(Adapter => .inner);
26
27pub use wgt::RequestAdapterOptions as RequestAdapterOptionsBase;
28/// Additional information required when requesting an adapter.
29///
30/// For use with [`Instance::request_adapter`].
31///
32/// Corresponds to [WebGPU `GPURequestAdapterOptions`](
33/// https://gpuweb.github.io/gpuweb/#dictdef-gpurequestadapteroptions).
34pub type RequestAdapterOptions<'a, 'b> = RequestAdapterOptionsBase<&'a Surface<'b>>;
35#[cfg(send_sync)]
36static_assertions::assert_impl_all!(RequestAdapterOptions<'_, '_>: Send, Sync);
37
38impl Adapter {
39 /// Requests a connection to a physical device, creating a logical device.
40 ///
41 /// Returns the [`Device`] together with a [`Queue`] that executes command buffers.
42 ///
43 /// [Per the WebGPU specification], an [`Adapter`] may only be used once to create a device.
44 /// If another device is wanted, call [`Instance::request_adapter()`] again to get a fresh
45 /// [`Adapter`].
46 /// However, `wgpu` does not currently enforce this restriction.
47 ///
48 /// # Panics
49 ///
50 /// - `request_device()` was already called on this `Adapter`.
51 /// - Features specified by `desc` are not supported by this adapter.
52 /// - Unsafe features were requested but not enabled when requesting the adapter.
53 /// - Limits requested exceed the values provided by the adapter.
54 /// - Adapter does not support all features wgpu requires to safely operate.
55 ///
56 /// [Per the WebGPU specification]: https://www.w3.org/TR/webgpu/#dom-gpuadapter-requestdevice
57 pub fn request_device(
58 &self,
59 desc: &DeviceDescriptor<'_>,
60 ) -> impl Future<Output = Result<(Device, Queue), RequestDeviceError>> + WasmNotSend {
61 let device = self.inner.request_device(desc);
62 async move {
63 device
64 .await
65 .map(|(device, queue)| (Device { inner: device }, Queue { inner: queue }))
66 }
67 }
68
69 /// Create a wgpu [`Device`] and [`Queue`] from a wgpu-hal `OpenDevice`
70 ///
71 /// # Safety
72 ///
73 /// - `hal_device` must be created from this adapter internal handle.
74 /// - `desc.features` must be a subset of `hal_device` features.
75 #[cfg(wgpu_core)]
76 pub unsafe fn create_device_from_hal<A: wgc::hal_api::HalApi>(
77 &self,
78 hal_device: hal::OpenDevice<A>,
79 desc: &DeviceDescriptor<'_>,
80 ) -> Result<(Device, Queue), RequestDeviceError> {
81 let core_adapter = self.inner.as_core();
82 let (device, queue) = unsafe {
83 core_adapter
84 .context
85 .create_device_from_hal(core_adapter, hal_device, desc)
86 }?;
87
88 Ok((
89 Device {
90 inner: device.into(),
91 },
92 Queue {
93 inner: queue.into(),
94 },
95 ))
96 }
97
98 /// Get the [`wgpu_hal`] adapter from this `Adapter`.
99 ///
100 /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`],
101 /// and pass that struct to the to the `A` type parameter.
102 ///
103 /// Returns a guard that dereferences to the type of the hal backend
104 /// which implements [`A::Adapter`].
105 ///
106 /// # Errors
107 ///
108 /// This method will return None if:
109 /// - The adapter is not from the backend specified by `A`.
110 /// - The adapter is from the `webgpu` or `custom` backend.
111 ///
112 /// # Safety
113 ///
114 /// - The returned resource must not be destroyed unless the guard
115 /// is the last reference to it and it is not in use by the GPU.
116 /// The guard and handle may be dropped at any time however.
117 /// - All the safety requirements of wgpu-hal must be upheld.
118 ///
119 /// [`A::Adapter`]: hal::Api::Adapter
120 #[cfg(wgpu_core)]
121 pub unsafe fn as_hal<A: wgc::hal_api::HalApi>(
122 &self,
123 ) -> Option<impl Deref<Target = A::Adapter> + WasmNotSendSync> {
124 let adapter = self.inner.as_core_opt()?;
125
126 unsafe { adapter.context.adapter_as_hal::<A>(adapter) }
127 }
128
129 #[cfg(custom)]
130 /// Returns custom implementation of adapter (if custom backend and is internally T)
131 pub fn as_custom<T: custom::AdapterInterface>(&self) -> Option<&T> {
132 self.inner.as_custom()
133 }
134
135 #[cfg(custom)]
136 /// Creates Adapter from custom implementation
137 pub fn from_custom<T: custom::AdapterInterface>(adapter: T) -> Self {
138 Self {
139 inner: dispatch::DispatchAdapter::custom(adapter),
140 }
141 }
142
143 /// Returns whether this adapter may present to the passed surface.
144 pub fn is_surface_supported(&self, surface: &Surface<'_>) -> bool {
145 self.inner.is_surface_supported(&surface.inner)
146 }
147
148 /// The features which can be used to create devices on this adapter.
149 pub fn features(&self) -> Features {
150 self.inner.features()
151 }
152
153 /// The best limits which can be used to create devices on this adapter.
154 pub fn limits(&self) -> Limits {
155 self.inner.limits()
156 }
157
158 /// Get info about the adapter itself.
159 pub fn get_info(&self) -> AdapterInfo {
160 self.inner.get_info()
161 }
162
163 /// Get info about the adapter itself.
164 pub fn get_downlevel_capabilities(&self) -> DownlevelCapabilities {
165 self.inner.downlevel_capabilities()
166 }
167
168 /// Returns the features supported for a given texture format by this adapter.
169 ///
170 /// Note that the WebGPU spec further restricts the available usages/features.
171 /// To disable these restrictions on a device, request the [`Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`] feature.
172 pub fn get_texture_format_features(&self, format: TextureFormat) -> TextureFormatFeatures {
173 self.inner.get_texture_format_features(format)
174 }
175
176 /// Generates a timestamp using the clock used by the presentation engine.
177 ///
178 /// When comparing completely opaque timestamp systems, we need a way of generating timestamps that signal
179 /// the exact same time. You can do this by calling your own timestamp function immediately after a call to
180 /// this function. This should result in timestamps that are 0.5 to 5 microseconds apart. There are locks
181 /// that must be taken during the call, so don't call your function before.
182 ///
183 /// ```no_run
184 /// # let adapter: wgpu::Adapter = panic!();
185 /// # let some_code = || wgpu::PresentationTimestamp::INVALID_TIMESTAMP;
186 /// use std::time::{Duration, Instant};
187 /// let presentation = adapter.get_presentation_timestamp();
188 /// let instant = Instant::now();
189 ///
190 /// // We can now turn a new presentation timestamp into an Instant.
191 /// let some_pres_timestamp = some_code();
192 /// let duration = Duration::from_nanos((some_pres_timestamp.0 - presentation.0) as u64);
193 /// let new_instant: Instant = instant + duration;
194 /// ```
195 //
196 /// [Instant]: std::time::Instant
197 pub fn get_presentation_timestamp(&self) -> PresentationTimestamp {
198 self.inner.get_presentation_timestamp()
199 }
200}