wgpu_hal/vulkan/mod.rs
1/*!
2# Vulkan API internals.
3
4## Stack memory
5
6Ash expects slices, which we don't generally have available.
7We cope with this requirement by the combination of the following ways:
8 - temporarily allocating `Vec` on heap, where overhead is permitted
9 - growing temporary local storage
10
11## Framebuffers and Render passes
12
13Render passes are cached on the device and kept forever.
14
15Framebuffers are also cached on the device, but they are removed when
16any of the image views (they have) gets removed.
17If Vulkan supports image-less framebuffers,
18then the actual views are excluded from the framebuffer key.
19
20## Fences
21
22If timeline semaphores are available, they are used 1:1 with wgpu-hal fences.
23Otherwise, we manage a pool of `VkFence` objects behind each `hal::Fence`.
24
25!*/
26
27mod adapter;
28mod command;
29pub mod conv;
30mod descriptor;
31mod device;
32mod drm;
33mod instance;
34mod memory;
35mod pnext_chain;
36mod sampler;
37mod semaphore_list;
38mod swapchain;
39
40pub use adapter::PhysicalDeviceFeatures;
41pub(crate) use pnext_chain::PnextChain;
42
43use alloc::{boxed::Box, ffi::CString, sync::Arc, vec::Vec};
44use core::{
45 borrow::Borrow,
46 ffi::{c_void, CStr},
47 fmt,
48 marker::PhantomData,
49 mem,
50 num::NonZeroU32,
51};
52
53use arrayvec::ArrayVec;
54use ash::{ext, khr, vk};
55use bytemuck::{Pod, Zeroable};
56use hashbrown::HashSet;
57use wgpu_sync::{Mutex, RwLock};
58
59use naga::FastHashMap;
60use wgt::InternalCounter;
61
62use semaphore_list::SemaphoreList;
63
64pub use memory::MemoryAllocation;
65use memory::{MemoryAllocators, MemoryPool};
66
67use crate::vulkan::semaphore_list::{SemaphoreListMode, SemaphoreType};
68
69const MAX_TOTAL_ATTACHMENTS: usize = crate::MAX_COLOR_ATTACHMENTS * 2 + 1;
70
71#[derive(Clone, Debug)]
72pub struct Api;
73
74impl crate::Api for Api {
75 const VARIANT: wgt::Backend = wgt::Backend::Vulkan;
76
77 type Instance = Instance;
78 type Surface = Surface;
79 type Adapter = Adapter;
80 type Device = Device;
81
82 type Queue = Queue;
83 type CommandEncoder = CommandEncoder;
84 type CommandBuffer = CommandBuffer;
85
86 type Buffer = Buffer;
87 type Texture = Texture;
88 type SurfaceTexture = SurfaceTexture;
89 type TextureView = TextureView;
90 type Sampler = Sampler;
91 type QuerySet = QuerySet;
92 type Fence = Fence;
93 type AccelerationStructure = AccelerationStructure;
94 type PipelineCache = PipelineCache;
95
96 type BindGroupLayout = BindGroupLayout;
97 type BindGroup = BindGroup;
98 type PipelineLayout = PipelineLayout;
99 type ShaderModule = ShaderModule;
100 type RenderPipeline = RenderPipeline;
101 type ComputePipeline = ComputePipeline;
102 type RayTracingPipeline = RayTracingPipeline;
103}
104
105crate::impl_dyn_resource!(
106 Adapter,
107 AccelerationStructure,
108 BindGroup,
109 BindGroupLayout,
110 Buffer,
111 CommandBuffer,
112 CommandEncoder,
113 ComputePipeline,
114 Device,
115 Fence,
116 Instance,
117 PipelineCache,
118 PipelineLayout,
119 QuerySet,
120 Queue,
121 RenderPipeline,
122 RayTracingPipeline,
123 Sampler,
124 ShaderModule,
125 Surface,
126 SurfaceTexture,
127 Texture,
128 TextureView
129);
130
131struct DebugUtils {
132 extension: ext::debug_utils::Instance,
133 messenger: vk::DebugUtilsMessengerEXT,
134
135 /// Owning pointer to the debug messenger callback user data.
136 ///
137 /// `InstanceShared::drop` destroys the debug messenger before
138 /// dropping this, so the callback should never receive a dangling
139 /// user data pointer.
140 #[allow(dead_code)]
141 callback_data: Box<DebugUtilsMessengerUserData>,
142}
143
144#[derive(Debug)]
145pub struct DebugUtilsCreateInfo {
146 severity: vk::DebugUtilsMessageSeverityFlagsEXT,
147 message_type: vk::DebugUtilsMessageTypeFlagsEXT,
148 callback_data: Box<DebugUtilsMessengerUserData>,
149}
150
151#[derive(Debug)]
152/// The properties related to the validation layer needed for the
153/// DebugUtilsMessenger for their workarounds
154struct ValidationLayerProperties {
155 /// Validation layer description, from `vk::LayerProperties`.
156 layer_description: CString,
157
158 /// Validation layer specification version, from `vk::LayerProperties`.
159 layer_spec_version: u32,
160}
161
162/// User data needed by `instance::debug_utils_messenger_callback`.
163///
164/// When we create the [`vk::DebugUtilsMessengerEXT`], the `pUserData`
165/// pointer refers to one of these values.
166#[derive(Debug)]
167pub struct DebugUtilsMessengerUserData {
168 /// The properties related to the validation layer, if present
169 validation_layer_properties: Option<ValidationLayerProperties>,
170
171 /// If the OBS layer is present. OBS never increments the version of their layer,
172 /// so there's no reason to have the version.
173 has_obs_layer: bool,
174}
175
176pub struct InstanceShared {
177 raw: ash::Instance,
178 extensions: Vec<&'static CStr>,
179 flags: wgt::InstanceFlags,
180 memory_budget_thresholds: wgt::MemoryBudgetThresholds,
181 debug_utils: Option<DebugUtils>,
182 get_physical_device_properties: Option<khr::get_physical_device_properties2::Instance>,
183 entry: ash::Entry,
184 has_nv_optimus: bool,
185 android_sdk_version: u32,
186 /// The instance API version.
187 ///
188 /// Which is the version of Vulkan supported for instance-level functionality.
189 ///
190 /// It is associated with a `VkInstance` and its children,
191 /// except for a `VkPhysicalDevice` and its children.
192 instance_api_version: u32,
193
194 /// The kind of swapchain used by surfaces created by this instance.
195 ///
196 /// Resolved at instance creation from `VulkanBackendOptions`; a requested DXGI kind is
197 /// downgraded to `Native` if DXGI is unavailable.
198 swapchain_kind: wgt::VulkanSwapchainKind,
199
200 /// Instance-wide DXGI state backing the interop swapchain; `Some` only when
201 /// [`Self::swapchain_kind`] is a DXGI kind and DXGI is available.
202 #[cfg(windows)]
203 dxgi_instance: Option<swapchain::DxgiInstance>,
204
205 // The `drop_guard` field must be the last field of this struct so it is dropped last.
206 // Do not add new fields after it.
207 drop_guard: Option<crate::DropGuard>,
208}
209
210impl fmt::Debug for InstanceShared {
211 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212 let Self {
213 raw: _,
214 extensions,
215 flags,
216 memory_budget_thresholds,
217 debug_utils: _,
218 get_physical_device_properties: _,
219 entry: _,
220 has_nv_optimus,
221 android_sdk_version,
222 instance_api_version,
223 swapchain_kind,
224 #[cfg(windows)]
225 dxgi_instance: _,
226 drop_guard: _,
227 } = self;
228 f.debug_struct("InstanceShared")
229 .field("extensions", extensions)
230 .field("flags", flags)
231 .field("memory_budget_thresholds", memory_budget_thresholds)
232 .field("has_nv_optimus", has_nv_optimus)
233 .field("android_sdk_version", android_sdk_version)
234 .field("instance_api_version", instance_api_version)
235 .field("swapchain_kind", swapchain_kind)
236 .finish_non_exhaustive()
237 }
238}
239
240#[derive(Debug)]
241pub struct Instance {
242 shared: Arc<InstanceShared>,
243}
244
245#[expect(missing_debug_implementations, reason = "TODO?")]
246pub struct Surface {
247 swapchain: RwLock<Option<Box<dyn swapchain::Swapchain>>>,
248 inner: Box<dyn swapchain::Surface>,
249}
250
251impl Surface {
252 /// Returns the raw Vulkan surface handle.
253 ///
254 /// Returns `None` if the surface is a DXGI surface.
255 pub unsafe fn raw_native_handle(&self) -> Option<vk::SurfaceKHR> {
256 Some(
257 self.inner
258 .as_any()
259 .downcast_ref::<swapchain::NativeSurface>()?
260 .as_raw(),
261 )
262 }
263
264 /// Get the raw Vulkan swapchain associated with this surface.
265 ///
266 /// Returns [`None`] if the surface is not configured or if the swapchain
267 /// is a DXGI swapchain.
268 pub fn raw_native_swapchain(&self) -> Option<vk::SwapchainKHR> {
269 let read = self.swapchain.read();
270 Some(
271 read.as_ref()?
272 .as_any()
273 .downcast_ref::<swapchain::NativeSwapchain>()?
274 .as_raw(),
275 )
276 }
277
278 /// Set the present timing information which will be used for the next [presentation](crate::Queue::present()) of this surface,
279 /// using [VK_GOOGLE_display_timing].
280 ///
281 /// This can be used to give an id to presentations, for future use of [`vk::PastPresentationTimingGOOGLE`].
282 /// Note that `wgpu-hal` does *not* provide a way to use that API - you should manually access this through [`ash`].
283 ///
284 /// This can also be used to add a "not before" timestamp to the presentation.
285 ///
286 /// The exact semantics of the fields are also documented in the [specification](https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkPresentTimeGOOGLE.html) for the extension.
287 ///
288 /// # Panics
289 ///
290 /// - If the surface hasn't been configured.
291 /// - If the surface has been configured for a DXGI swapchain.
292 /// - If the device doesn't have the [VK_GOOGLE_display_timing] extension enabled.
293 ///
294 /// [VK_GOOGLE_display_timing]: https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_GOOGLE_display_timing.html
295 #[track_caller]
296 pub fn set_next_present_time(&self, present_timing: vk::PresentTimeGOOGLE) {
297 let mut swapchain = self.swapchain.write();
298 swapchain
299 .as_mut()
300 .expect("Surface should have been configured")
301 .as_any_mut()
302 .downcast_mut::<swapchain::NativeSwapchain>()
303 .expect("Surface should have a native Vulkan swapchain")
304 .set_next_present_time(present_timing);
305 }
306
307 /// Set a `pNext` chain of extension structs to be attached to the [`vk::PresentInfoKHR`]
308 /// of the next [presentation](crate::Queue::present()) of this surface.
309 ///
310 /// This supports presentation extensions that `wgpu-hal` has no dedicated support
311 /// for, such as [VK_NV_present_metering]. The corresponding device extension must be
312 /// enabled at device creation, e.g. with
313 /// [`Adapter::open_with_callback()`](super::vulkan::Adapter::open_with_callback).
314 ///
315 /// The chain is consumed by the next presentation: it replaces any chain set by a
316 /// previous call that hasn't been presented yet, and is discarded unread if the
317 /// surface is reconfigured first.
318 ///
319 /// # Safety
320 ///
321 /// - `chain` must point to a valid `pNext` chain of structs that can extend
322 /// [`vk::PresentInfoKHR`], whose extensions are enabled on the device.
323 /// - The chain must stay valid, and must not be read or written, until the next
324 /// presentation of this surface completes or the surface is reconfigured. Fields
325 /// the driver wrote during presentation may be read afterwards.
326 ///
327 /// # Panics
328 ///
329 /// - If the surface hasn't been configured.
330 /// - If the surface has been configured for a DXGI swapchain.
331 ///
332 /// [VK_NV_present_metering]: https://registry.khronos.org/vulkan/specs/latest/man/html/VK_NV_present_metering.html
333 #[track_caller]
334 pub unsafe fn set_next_present_chain(&self, chain: *mut c_void) {
335 let mut swapchain = self.swapchain.write();
336 let swapchain = swapchain
337 .as_mut()
338 .expect("Surface should have been configured")
339 .as_any_mut()
340 .downcast_mut::<swapchain::NativeSwapchain>()
341 .expect("Surface should have a native Vulkan swapchain");
342 unsafe { swapchain.set_next_present_chain(chain) };
343 }
344
345 /// Set a `pNext` chain of extension structs to attach to the
346 /// [`vk::SwapchainCreateInfoKHR`] used by the next configuration of this surface.
347 ///
348 /// This supports swapchain extensions that `wgpu-hal` has no dedicated support
349 /// for. One example is `VkSwapchainLatencyCreateInfoNV` from [VK_NV_low_latency2].
350 /// The device extension itself must be enabled at device creation, for example
351 /// with [`Adapter::open_with_callback()`](super::vulkan::Adapter::open_with_callback).
352 ///
353 /// The next configuration consumes the chain. A later call replaces a chain that
354 /// hasn't been consumed yet. If the surface is dropped first, the chain is
355 /// discarded unread. Every configuration creates a new swapchain, so you must set
356 /// the chain again before each configuration, including on resize.
357 ///
358 /// # Safety
359 ///
360 /// - `chain` must point to a valid `pNext` chain of structs that can extend
361 /// [`vk::SwapchainCreateInfoKHR`]. The extensions in the chain must be enabled
362 /// on the device the surface is configured with.
363 /// - The chain must stay valid until the configuration that consumes it returns
364 /// or the surface is dropped. Don't read or write the chain during that time.
365 /// Fields the driver wrote during swapchain creation may be read afterwards.
366 ///
367 /// # Panics
368 ///
369 /// - If the surface isn't a native Vulkan surface, such as a DXGI surface.
370 ///
371 /// [VK_NV_low_latency2]: https://registry.khronos.org/vulkan/specs/latest/man/html/VK_NV_low_latency2.html
372 #[track_caller]
373 pub unsafe fn set_next_swapchain_create_chain(&self, chain: *mut c_void) {
374 let surface = self
375 .inner
376 .as_any()
377 .downcast_ref::<swapchain::NativeSurface>()
378 .expect("Surface should be a native Vulkan surface");
379 unsafe { surface.set_next_swapchain_create_chain(chain) };
380 }
381}
382
383#[derive(Debug)]
384pub struct SurfaceTexture {
385 index: u32,
386 texture: Texture,
387 metadata: Box<dyn swapchain::SurfaceTextureMetadata>,
388}
389
390impl crate::DynSurfaceTexture for SurfaceTexture {}
391
392impl Borrow<Texture> for SurfaceTexture {
393 fn borrow(&self) -> &Texture {
394 &self.texture
395 }
396}
397
398impl Borrow<dyn crate::DynTexture> for SurfaceTexture {
399 fn borrow(&self) -> &dyn crate::DynTexture {
400 &self.texture
401 }
402}
403
404#[derive(Debug)]
405pub struct Adapter {
406 raw: vk::PhysicalDevice,
407 instance: Arc<InstanceShared>,
408 //queue_families: Vec<vk::QueueFamilyProperties>,
409 known_memory_flags: vk::MemoryPropertyFlags,
410 phd_capabilities: adapter::PhysicalDeviceProperties,
411 phd_features: PhysicalDeviceFeatures,
412 downlevel_flags: wgt::DownlevelFlags,
413 private_caps: PrivateCapabilities,
414 workarounds: Workarounds,
415}
416
417// TODO there's no reason why this can't be unified--the function pointers should all be the same--it's not clear how to do this with `ash`.
418enum ExtensionFn<T> {
419 /// The loaded function pointer struct for an extension.
420 Extension(T),
421 /// The extension was promoted to a core version of Vulkan and the functions on `ash`'s `DeviceV1_x` traits should be used.
422 Promoted,
423}
424
425struct DeviceExtensionFunctions {
426 debug_utils: Option<ext::debug_utils::Device>,
427 draw_indirect_count: Option<khr::draw_indirect_count::Device>,
428 timeline_semaphore: Option<ExtensionFn<khr::timeline_semaphore::Device>>,
429 ray_tracing: Option<RayTracingDeviceExtensionFunctions>,
430 ray_tracing_pipelines: Option<khr::ray_tracing_pipeline::Device>,
431 mesh_shading: Option<ext::mesh_shader::Device>,
432 #[cfg_attr(not(unix), allow(dead_code))]
433 external_memory_fd: Option<khr::external_memory_fd::Device>,
434 #[cfg_attr(not(windows), allow(dead_code))]
435 external_memory_win32: Option<khr::external_memory_win32::Device>,
436 #[cfg_attr(not(windows), allow(dead_code))]
437 external_semaphore_win32: Option<khr::external_semaphore_win32::Device>,
438}
439
440struct RayTracingDeviceExtensionFunctions {
441 acceleration_structure: khr::acceleration_structure::Device,
442 buffer_device_address: khr::buffer_device_address::Device,
443}
444
445/// Set of internal capabilities, which don't show up in the exposed
446/// device geometry, but affect the code paths taken internally.
447#[derive(Clone, Debug)]
448struct PrivateCapabilities {
449 image_view_usage: bool,
450 timeline_semaphores: bool,
451 texture_d24: bool,
452 texture_d24_s8: bool,
453 texture_s8: bool,
454 /// Ability to present contents to any screen. Only needed to work around broken platform configurations.
455 can_present: bool,
456 /// The device LUID from `VK_KHR_external_memory_capabilities`, used to match this Vulkan
457 /// physical device against a DXGI adapter for the Windows interop swapchain. `None` when the
458 /// device does not report a valid LUID.
459 #[cfg_attr(not(windows), allow(dead_code))]
460 device_luid: Option<[u8; vk::LUID_SIZE]>,
461 non_coherent_map_mask: wgt::BufferAddress,
462 multi_draw_indirect: bool,
463 max_draw_indirect_count: u32,
464
465 /// True if this adapter advertises the [`robustBufferAccess`][vrba] feature.
466 ///
467 /// Note that Vulkan's `robustBufferAccess` is not sufficient to implement
468 /// `wgpu_hal`'s guarantee that shaders will not access buffer contents via
469 /// a given bindgroup binding outside that binding's [accessible
470 /// region][ar]. Enabling `robustBufferAccess` does ensure that
471 /// out-of-bounds reads and writes are not undefined behavior (that's good),
472 /// but still permits out-of-bounds reads to return data from anywhere
473 /// within the buffer, not just the accessible region.
474 ///
475 /// [ar]: ../struct.BufferBinding.html#accessible-region
476 /// [vrba]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#features-robustBufferAccess
477 robust_buffer_access: bool,
478
479 robust_image_access: bool,
480
481 /// True if this adapter supports the [`VK_EXT_robustness2`] extension's
482 /// [`robustBufferAccess2`] feature.
483 ///
484 /// This is sufficient to implement `wgpu_hal`'s [required bounds-checking][ar] of
485 /// shader accesses to buffer contents. If this feature is not available,
486 /// this backend must have Naga inject bounds checks in the generated
487 /// SPIR-V.
488 ///
489 /// [`VK_EXT_robustness2`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_EXT_robustness2.html
490 /// [`robustBufferAccess2`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkPhysicalDeviceRobustness2FeaturesEXT.html#features-robustBufferAccess2
491 /// [ar]: ../struct.BufferBinding.html#accessible-region
492 robust_buffer_access2: bool,
493
494 robust_image_access2: bool,
495 zero_initialize_workgroup_memory: bool,
496 image_format_list: bool,
497 maximum_samplers: u32,
498
499 /// True if this adapter supports the [`VK_KHR_shader_integer_dot_product`] extension
500 /// (promoted to Vulkan 1.3).
501 ///
502 /// This is used to generate optimized code for WGSL's `dot4{I, U}8Packed`.
503 ///
504 /// [`VK_KHR_shader_integer_dot_product`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_shader_integer_dot_product.html
505 shader_integer_dot_product: bool,
506
507 /// True if this adapter supports 8-bit integers provided by the
508 /// [`VK_KHR_shader_float16_int8`] extension (promoted to Vulkan 1.2).
509 ///
510 /// Allows shaders to declare the "Int8" capability. Note, however, that this
511 /// feature alone allows the use of 8-bit integers "only in the `Private`,
512 /// `Workgroup` (for non-Block variables), and `Function` storage classes"
513 /// ([see spec]). To use 8-bit integers in the interface storage classes (e.g.,
514 /// `StorageBuffer`), you also need to enable the corresponding feature in
515 /// `VkPhysicalDevice8BitStorageFeatures` and declare the corresponding SPIR-V
516 /// capability (e.g., `StorageBuffer8BitAccess`).
517 ///
518 /// [`VK_KHR_shader_float16_int8`]: https://registry.khronos.org/vulkan/specs/latest/man/html/VK_KHR_shader_float16_int8.html
519 /// [see spec]: https://registry.khronos.org/vulkan/specs/latest/man/html/VkPhysicalDeviceShaderFloat16Int8Features.html#extension-features-shaderInt8
520 shader_int8: bool,
521
522 /// This is done to panic before undefined behavior, and is imperfect.
523 /// Basically, to allow implementations to emulate mv using instancing, if you
524 /// want to draw `n` instances to VR, you must draw `2n` instances, but you
525 /// can never draw more than `u32::MAX` instances. Therefore, when drawing
526 /// multiview on some vulkan implementations, it might restrict the instance
527 /// count, which isn't usually a thing in webgpu. We don't expose this limit
528 /// because its strange, i.e. only occurs on certain vulkan implementations
529 /// if you are drawing more than 128 million instances. We still want to avoid
530 /// undefined behavior in this situation, so we panic if the limit is violated.
531 multiview_instance_index_limit: u32,
532
533 /// BufferUsages::ACCELERATION_STRUCTURE_SCRATCH allows usage as a scratch buffer.
534 /// Vulkan has no way to specify this as a usage, and it maps to other usages, but
535 /// these usages do not have as high of an alignment requirement using the buffer as
536 /// a scratch buffer when building acceleration structures.
537 scratch_buffer_alignment: u32,
538
539 /// Indicating that depth/stencil texturing operations with `VK_COMPONENT_SWIZZLE_ONE` have defined behavior.
540 depth_stencil_swizzle_one_support: bool,
541
542 /// `get_raytracing_pipeline_group_data` requires both a group count and a data size.
543 /// The data size parameter is just this * the group count, so we store this to not
544 /// require an unnecessary parameter.
545 ray_tracing_pipeline_group_data_size: u32,
546
547 /// `shaderGroupBaseAlignment`. Shader binding table regions must start at a device
548 /// address that is a multiple of this, so shader binding table buffers use it as their alignment.
549 shader_binding_table_alignment: u32,
550
551 /// Whether `VK_ATTACHMENT_STORE_OP_NONE` is supported. This includes:
552 /// - `VK_ATTACHMENT_STORE_OP_NONE` provided by `VK_VERSION_1_3`.
553 /// - `VK_ATTACHMENT_STORE_OP_NONE_KHR` provided by `VK_KHR_dynamic_rendering`, or `VK_KHR_load_store_op_none` (promoted to Vulkan 1.4).
554 /// - `VK_ATTACHMENT_STORE_OP_NONE_QCOM` provided by `VK_QCOM_render_pass_store_ops`.
555 /// - `VK_ATTACHMENT_STORE_OP_NONE_EXT` provided by `VK_EXT_load_store_op_none`.
556 store_op_none: bool,
557
558 /// True if `VK_KHR_incremental_present` is enabled on the device.
559 incremental_present: bool,
560}
561
562bitflags::bitflags!(
563 /// Workaround flags.
564 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
565 pub struct Workarounds: u32 {
566 /// Only generate SPIR-V for one entry point at a time.
567 const SEPARATE_ENTRY_POINTS = 1 << 0;
568 /// Qualcomm OOMs when there are zero color attachments but a non-null pointer
569 /// to a subpass resolve attachment array. This nulls out that pointer in that case.
570 const EMPTY_RESOLVE_ATTACHMENT_LISTS = 1 << 1;
571 /// If the following code returns false, then nvidia will end up filling the wrong range.
572 ///
573 /// ```skip
574 /// fn nvidia_succeeds() -> bool {
575 /// # let (copy_length, start_offset) = (0, 0);
576 /// if copy_length >= 4096 {
577 /// if start_offset % 16 != 0 {
578 /// if copy_length == 4096 {
579 /// return true;
580 /// }
581 /// if copy_length % 16 == 0 {
582 /// return false;
583 /// }
584 /// }
585 /// }
586 /// true
587 /// }
588 /// ```
589 ///
590 /// As such, we need to make sure all calls to vkCmdFillBuffer are aligned to 16 bytes
591 /// if they cover a range of 4096 bytes or more.
592 const FORCE_FILL_BUFFER_WITH_SIZE_GREATER_4096_ALIGNED_OFFSET_16 = 1 << 2;
593 /// AMD's proprietary driver fails with VK_ERROR_INITIALIZATION_FAILED on mesh
594 /// and task shaders that zero-initialize workgroup memory with `OpVariable`
595 /// initializers, so polyfill it in those stages.
596 const POLYFILL_MESH_TASK_WORKGROUP_ZERO_INIT = 1 << 3;
597 /// Don't use timeline semaphores, even if the device supports them, and fall back
598 /// to binary fences ([`FencePool`]) for [`Fence`]s instead.
599 ///
600 /// Arm's proprietary Mali driver keeps memory for every value a timeline semaphore
601 /// has ever been signaled with, and only releases it when the semaphore is
602 /// destroyed. wgpu signals the device's timeline semaphore once per submission, so
603 /// the memory grows without bound until the kernel driver's limit is reached and the
604 /// device is lost. Observed with driver `v1.g18p0-01eac0` on a Mali-G610 (RK3588,
605 /// Android 12): 16 bytes per signal, device lost after ~4.2 million submissions,
606 /// i.e. ~35 minutes for a 960 FPS `Mailbox` loop or ~10 hours at 60 FPS.
607 ///
608 /// Set for Arm drivers older than `r46` and Rockchip drivers older than `g24`, and
609 /// for drivers whose version is not known.
610 ///
611 /// [`Fence`]: super::Fence
612 /// [`FencePool`]: super::FencePool
613 const DISABLE_TIMELINE_SEMAPHORES = 1 << 4;
614 }
615);
616
617#[derive(Clone, Debug, Eq, Hash, PartialEq)]
618struct AttachmentKey {
619 format: vk::Format,
620 layout: vk::ImageLayout,
621 ops: crate::AttachmentOps,
622}
623
624impl AttachmentKey {
625 /// Returns an attachment key for a compatible attachment.
626 fn compatible(format: vk::Format, layout: vk::ImageLayout) -> Self {
627 Self {
628 format,
629 layout,
630 ops: crate::AttachmentOps::all(),
631 }
632 }
633}
634
635#[derive(Clone, Eq, Hash, PartialEq)]
636struct ColorAttachmentKey {
637 base: AttachmentKey,
638 resolve: Option<AttachmentKey>,
639}
640
641#[derive(Clone, Eq, Hash, PartialEq)]
642struct DepthStencilAttachmentKey {
643 base: AttachmentKey,
644 stencil_ops: crate::AttachmentOps,
645}
646
647#[derive(Clone, Eq, Default, Hash, PartialEq)]
648struct RenderPassKey {
649 colors: ArrayVec<Option<ColorAttachmentKey>, { crate::MAX_COLOR_ATTACHMENTS }>,
650 depth_stencil: Option<DepthStencilAttachmentKey>,
651 sample_count: u32,
652 multiview_mask: Option<NonZeroU32>,
653 depth_read_only: bool,
654 stencil_read_only: bool,
655}
656
657struct DeviceShared {
658 raw: ash::Device,
659 family_index: u32,
660 queue_flags: vk::QueueFlags,
661 queue_index: u32,
662 raw_queue: vk::Queue,
663 instance: Arc<InstanceShared>,
664 physical_device: vk::PhysicalDevice,
665 enabled_extensions: Vec<&'static CStr>,
666 extension_fns: DeviceExtensionFunctions,
667 vendor_id: u32,
668 pipeline_cache_validation_key: [u8; 16],
669 timestamp_period: f32,
670 private_caps: PrivateCapabilities,
671 workarounds: Workarounds,
672 features: wgt::Features,
673 render_passes: Mutex<FastHashMap<RenderPassKey, vk::RenderPass>>,
674 sampler_cache: Mutex<sampler::SamplerCache>,
675 memory_allocations_counter: InternalCounter,
676
677 /// Because we have cached framebuffers which are not deleted from until
678 /// the device is destroyed, if the implementation of vulkan re-uses handles
679 /// we need some way to differentiate between the old handle and the new handle.
680 /// This factory allows us to have a dedicated identity value for each texture.
681 texture_identity_factory: ResourceIdentityFactory<vk::Image>,
682 /// As above, for texture views.
683 texture_view_identity_factory: ResourceIdentityFactory<vk::ImageView>,
684
685 empty_descriptor_set_layout: vk::DescriptorSetLayout,
686
687 /// The D3D12 device used for the DXGI interop swapchain, created lazily and shared by all
688 /// DXGI surfaces configured against this device. See [`swapchain::InteropDevice`].
689 #[cfg(windows)]
690 dxgi_interop: wgpu_sync::OnceCell<swapchain::InteropDevice>,
691
692 // The `drop_guard` field must be the last field of this struct so it is dropped last.
693 // Do not add new fields after it.
694 drop_guard: Option<crate::DropGuard>,
695}
696
697impl Drop for DeviceShared {
698 fn drop(&mut self) {
699 for &raw in self.render_passes.lock().values() {
700 unsafe { self.raw.destroy_render_pass(raw, None) };
701 }
702 unsafe {
703 self.raw
704 .destroy_descriptor_set_layout(self.empty_descriptor_set_layout, None)
705 };
706 if self.drop_guard.is_none() {
707 unsafe { self.raw.destroy_device(None) };
708 }
709 }
710}
711
712#[expect(
713 missing_debug_implementations,
714 reason = "needs work to not be disastrously verbose"
715)]
716pub struct Device {
717 mem_allocator: MemoryAllocators,
718 desc_allocator: Mutex<descriptor::DescriptorAllocator>,
719 valid_ash_memory_types: u32,
720 naga_options: naga::back::spv::Options<'static>,
721 #[cfg(feature = "renderdoc")]
722 render_doc: crate::auxil::renderdoc::RenderDoc,
723 counters: Arc<wgt::HalCounters>,
724 // Struct members are dropped from first to last, put the Device last to ensure that
725 // all resources that depends on it are destroyed before it like the mem_allocator
726 shared: Arc<DeviceShared>,
727}
728
729impl Drop for Device {
730 fn drop(&mut self) {}
731}
732
733/// Semaphores for forcing queue submissions to run in order.
734///
735/// The [`wgpu_hal::Queue`] trait promises that if two calls to [`submit`] are
736/// ordered, then the first submission will finish on the GPU before the second
737/// submission begins. To get this behavior on Vulkan we need to pass semaphores
738/// to [`vkQueueSubmit`] for the commands to wait on before beginning execution,
739/// and to signal when their execution is done.
740///
741/// Normally this can be done with a single semaphore, waited on and then
742/// signalled for each submission. At any given time there's exactly one
743/// submission that would signal the semaphore, and exactly one waiting on it,
744/// as Vulkan requires.
745///
746/// However, as of Oct 2021, bug [#5508] in the Mesa ANV drivers caused them to
747/// hang if we use a single semaphore. The workaround is to alternate between
748/// two semaphores. The bug has been fixed in Mesa, but we should probably keep
749/// the workaround until, say, Oct 2026.
750///
751/// [`wgpu_hal::Queue`]: crate::Queue
752/// [`submit`]: crate::Queue::submit
753/// [`vkQueueSubmit`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueueSubmit
754/// [#5508]: https://gitlab.freedesktop.org/mesa/mesa/-/issues/5508
755#[derive(Clone)]
756struct RelaySemaphores {
757 /// The semaphore the next submission should wait on before beginning
758 /// execution on the GPU. This is `None` for the first submission, which
759 /// should not wait on anything at all.
760 wait: Option<vk::Semaphore>,
761
762 /// The semaphore the next submission should signal when it has finished
763 /// execution on the GPU.
764 signal: vk::Semaphore,
765}
766
767impl RelaySemaphores {
768 fn new(device: &DeviceShared) -> Result<Self, crate::DeviceError> {
769 Ok(Self {
770 wait: None,
771 signal: device.new_binary_semaphore("RelaySemaphores: 1")?,
772 })
773 }
774
775 /// Advances the semaphores, returning the semaphores that should be used for a submission.
776 fn advance(&mut self, device: &DeviceShared) -> Result<Self, crate::DeviceError> {
777 let old = self.clone();
778
779 // Build the state for the next submission.
780 match self.wait {
781 None => {
782 // The `old` values describe the first submission to this queue.
783 // The second submission should wait on `old.signal`, and then
784 // signal a new semaphore which we'll create now.
785 self.wait = Some(old.signal);
786 self.signal = device.new_binary_semaphore("RelaySemaphores: 2")?;
787 }
788 Some(ref mut wait) => {
789 // What this submission signals, the next should wait.
790 mem::swap(wait, &mut self.signal);
791 }
792 };
793
794 Ok(old)
795 }
796
797 /// Destroys the semaphores.
798 unsafe fn destroy(&self, device: &ash::Device) {
799 unsafe {
800 if let Some(wait) = self.wait {
801 device.destroy_semaphore(wait, None);
802 }
803 device.destroy_semaphore(self.signal, None);
804 }
805 }
806}
807
808pub struct Queue {
809 raw: vk::Queue,
810 device: Arc<DeviceShared>,
811 family_index: u32,
812 relay_semaphores: Mutex<RelaySemaphores>,
813 signal_semaphores: Mutex<SemaphoreList>,
814 wait_semaphores: Mutex<SemaphoreList>,
815 /// A caller-provided `pNext` chain to attach to the [`vk::SubmitInfo`] of the
816 /// next call to [`submit()`](crate::Queue::submit).
817 ///
818 /// Set only through [`Queue::set_next_submit_chain()`].
819 next_submit_chain: Mutex<Option<PnextChain>>,
820}
821
822impl fmt::Debug for Queue {
823 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
824 let Self {
825 raw: _,
826 device: _,
827 family_index,
828 relay_semaphores: _,
829 signal_semaphores: _,
830 wait_semaphores: _,
831 next_submit_chain: _,
832 } = self;
833 f.debug_struct("Queue")
834 .field("family_index", family_index)
835 .finish_non_exhaustive()
836 }
837}
838
839impl Queue {
840 pub fn as_raw(&self) -> vk::Queue {
841 self.raw
842 }
843}
844
845impl Drop for Queue {
846 fn drop(&mut self) {
847 unsafe { self.relay_semaphores.lock().destroy(&self.device.raw) };
848 }
849}
850#[derive(Debug)]
851enum BufferMemoryBacking {
852 Managed(MemoryAllocation),
853 VulkanMemory {
854 memory: vk::DeviceMemory,
855 offset: u64,
856 size: u64,
857 },
858}
859impl BufferMemoryBacking {
860 fn memory(&self) -> vk::DeviceMemory {
861 match self {
862 Self::Managed(m) => unsafe { m.memory() },
863 Self::VulkanMemory { memory, .. } => *memory,
864 }
865 }
866 fn offset(&self) -> u64 {
867 match self {
868 Self::Managed(m) => m.offset(),
869 Self::VulkanMemory { offset, .. } => *offset,
870 }
871 }
872 fn size(&self) -> u64 {
873 match self {
874 Self::Managed(m) => m.size(),
875 Self::VulkanMemory { size, .. } => *size,
876 }
877 }
878}
879/// Describes who owns a [`Buffer`]'s `vk::Buffer` handle and its backing memory,
880/// and therefore what cleanup is required when the buffer is destroyed.
881#[derive(Debug)]
882enum BufferOwnership {
883 /// wgpu-hal owns the `vk::Buffer` and its backing memory. On cleanup the buffer
884 /// handle is destroyed and the memory is released.
885 Managed(Mutex<BufferMemoryBacking>),
886 /// wgpu-hal owns the `vk::Buffer` handle but the backing memory is kept alive
887 /// by the caller. On cleanup only the buffer handle is destroyed.
888 RawHandle,
889 /// Caller owns the `vk::Buffer` and its backing memory. On cleanup the
890 /// [`crate::DropGuard`] runs the caller's cleanup callback and wgpu-hal touches
891 /// neither the handle nor the memory.
892 External(crate::DropGuard),
893}
894
895#[derive(Debug)]
896pub struct Buffer {
897 raw: vk::Buffer,
898
899 // This field must be last, because it may contain a `DropGuard` which needs to be dropped after all other fields.
900 ownership: BufferOwnership,
901}
902impl Buffer {
903 /// # Safety
904 ///
905 /// - `vk_buffer`'s memory must be managed by the caller
906 /// - Externally imported buffers can't be mapped by `wgpu`
907 /// - If `vk_buffer` is used for an indirect trace rays call, it must have been created with
908 /// `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT`.
909 pub unsafe fn from_raw(vk_buffer: vk::Buffer) -> Self {
910 Self {
911 raw: vk_buffer,
912 ownership: BufferOwnership::RawHandle,
913 }
914 }
915
916 /// # Safety
917 /// - `vk_buffer` must outlive the returned `Buffer`.
918 /// - wgpu-hal will NOT call `vkDestroyBuffer`; the caller remains responsible for the buffer handle's destruction.
919 /// The `drop_callback` runs when the `Buffer` drops and may be used to release caller-side bookkeeping.
920 /// - Externally imported buffers can't be mapped by `wgpu`.
921 /// - If `vk_buffer` is used for an indirect trace rays call, it must have been created with
922 /// `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT`.
923 pub unsafe fn from_raw_externally_owned(
924 vk_buffer: vk::Buffer,
925 drop_callback: crate::DropCallback,
926 ) -> Self {
927 Self {
928 raw: vk_buffer,
929 ownership: BufferOwnership::External(crate::DropGuard::new(drop_callback)),
930 }
931 }
932
933 /// # Safety
934 /// - We will use this buffer and the buffer's backing memory range as if we have exclusive ownership over it, until the wgpu resource is dropped and the wgpu-hal object is cleaned up
935 /// - Externally imported buffers can't be mapped by `wgpu`
936 /// - `offset` and `size` must be valid with the allocation of `memory`
937 /// - If `vk_buffer` is used for an indirect trace rays call, it must have been created with
938 /// `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT`.
939 pub unsafe fn from_raw_managed(
940 vk_buffer: vk::Buffer,
941 memory: vk::DeviceMemory,
942 offset: u64,
943 size: u64,
944 ) -> Self {
945 Self {
946 raw: vk_buffer,
947 ownership: BufferOwnership::Managed(Mutex::new(BufferMemoryBacking::VulkanMemory {
948 memory,
949 offset,
950 size,
951 })),
952 }
953 }
954
955 /// # Safety
956 /// - The buffer handle must not be manually destroyed
957 pub unsafe fn raw_handle(&self) -> vk::Buffer {
958 self.raw
959 }
960}
961
962impl crate::DynBuffer for Buffer {}
963
964#[derive(Debug)]
965pub struct AccelerationStructure {
966 raw: vk::AccelerationStructureKHR,
967 buffer: vk::Buffer,
968 allocation: MemoryAllocation,
969 compacted_size_query: Option<vk::QueryPool>,
970}
971
972impl crate::DynAccelerationStructure for AccelerationStructure {}
973
974impl AccelerationStructure {
975 /// Returns the raw Vulkan acceleration structure handle.
976 ///
977 /// This allows recording acceleration structure commands that `wgpu-hal` doesn't
978 /// support. If those commands come from a device extension, enable it with
979 /// [`Adapter::open_with_callback`].
980 ///
981 /// For a device address, use
982 /// [`crate::Device::get_acceleration_structure_device_address`] instead.
983 ///
984 /// `wgpu` doesn't observe an external build, and rejects an acceleration structure
985 /// that it never built. Call `wgpu::CommandEncoder::mark_acceleration_structures_built`
986 /// on the encoder that recorded the build.
987 ///
988 /// # Safety
989 ///
990 /// - The acceleration structure handle must not be manually destroyed, or used after
991 /// the acceleration structure is dropped
992 /// - External work using the handle must be synchronized against `wgpu`'s own reads
993 /// and writes, such as compaction
994 /// - An external build must not write more data than the size the acceleration
995 /// structure was created with
996 pub unsafe fn raw_handle(&self) -> vk::AccelerationStructureKHR {
997 self.raw
998 }
999}
1000
1001#[derive(Debug)]
1002pub enum TextureMemory {
1003 // shared memory in GPU allocator (owned by wgpu-hal)
1004 Allocation(MemoryAllocation),
1005
1006 // dedicated memory (owned by wgpu-hal)
1007 Dedicated(vk::DeviceMemory),
1008
1009 // memory not owned by wgpu
1010 External,
1011}
1012
1013/// What a transition of a [`Texture`] to `TextureUses::PRESENT` does.
1014#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1015enum PresentTransition {
1016 /// Transitions to `PRESENT_SRC_KHR`. Used by all textures except DXGI back buffers.
1017 PresentSrc,
1018 /// Releases to `VK_QUEUE_FAMILY_EXTERNAL` in `GENERAL`; the transition back acquires it.
1019 ReleaseToExternal,
1020}
1021
1022#[derive(Debug)]
1023pub struct Texture {
1024 raw: vk::Image,
1025 memory: TextureMemory,
1026 format: wgt::TextureFormat,
1027 copy_size: crate::CopyExtent,
1028 identity: ResourceIdentity<vk::Image>,
1029 /// What a transition of this texture to `TextureUses::PRESENT` does.
1030 present_transition: PresentTransition,
1031
1032 // The `drop_guard` field must be the last field of this struct so it is dropped last.
1033 // Do not add new fields after it.
1034 drop_guard: Option<crate::DropGuard>,
1035}
1036
1037impl crate::DynTexture for Texture {}
1038
1039impl Texture {
1040 /// # Safety
1041 ///
1042 /// - The image handle must not be manually destroyed
1043 pub unsafe fn raw_handle(&self) -> vk::Image {
1044 self.raw
1045 }
1046
1047 /// # Safety
1048 ///
1049 /// - The caller must not free the `vk::DeviceMemory` or
1050 /// `gpu_alloc::MemoryBlock` in the returned `TextureMemory`.
1051 pub unsafe fn memory(&self) -> &TextureMemory {
1052 &self.memory
1053 }
1054}
1055
1056#[derive(Debug)]
1057pub struct TextureView {
1058 raw_texture: vk::Image,
1059 raw: vk::ImageView,
1060 _layers: NonZeroU32,
1061 format: wgt::TextureFormat,
1062 raw_format: vk::Format,
1063 base_mip_level: u32,
1064 dimension: wgt::TextureViewDimension,
1065 texture_identity: ResourceIdentity<vk::Image>,
1066 view_identity: ResourceIdentity<vk::ImageView>,
1067}
1068
1069impl crate::DynTextureView for TextureView {}
1070
1071impl TextureView {
1072 /// # Safety
1073 ///
1074 /// - The image view handle must not be manually destroyed
1075 pub unsafe fn raw_handle(&self) -> vk::ImageView {
1076 self.raw
1077 }
1078
1079 /// Returns the raw texture view, along with its identity.
1080 fn identified_raw_view(&self) -> IdentifiedTextureView {
1081 IdentifiedTextureView {
1082 raw: self.raw,
1083 identity: self.view_identity,
1084 }
1085 }
1086}
1087
1088#[derive(Debug)]
1089pub struct Sampler {
1090 raw: vk::Sampler,
1091 create_info: vk::SamplerCreateInfo<'static>,
1092}
1093
1094impl crate::DynSampler for Sampler {}
1095
1096/// Information about a binding within a specific BindGroupLayout / BindGroup.
1097/// This will be used to construct a [`naga::back::spv::BindingInfo`], where
1098/// the descriptor set value will be taken from the index of the group.
1099#[derive(Copy, Clone, Debug)]
1100struct BindingInfo {
1101 binding: u32,
1102 binding_array_size: Option<NonZeroU32>,
1103 external_texture: bool,
1104}
1105
1106#[derive(Debug)]
1107pub struct BindGroupLayout {
1108 raw: vk::DescriptorSetLayout,
1109 desc_count: descriptor::DescriptorCounts,
1110 /// Sorted list of entries.
1111 entries: Box<[wgt::BindGroupLayoutEntry]>,
1112 /// Map of original binding index to remapped binding index and optional
1113 /// array size.
1114 binding_map: Vec<(u32, BindingInfo)>,
1115 contains_binding_arrays: bool,
1116}
1117
1118impl crate::DynBindGroupLayout for BindGroupLayout {}
1119
1120#[derive(Debug)]
1121pub struct PipelineLayout {
1122 raw: vk::PipelineLayout,
1123 binding_map: naga::back::spv::BindingMap,
1124}
1125
1126impl crate::DynPipelineLayout for PipelineLayout {}
1127
1128#[derive(Debug)]
1129pub struct BindGroup {
1130 set: descriptor::DescriptorSet,
1131}
1132
1133impl crate::DynBindGroup for BindGroup {}
1134
1135/// Miscellaneous allocation recycling pool for `CommandAllocator`.
1136#[derive(Default)]
1137struct Temp {
1138 marker: Vec<u8>,
1139 buffer_barriers: Vec<vk::BufferMemoryBarrier<'static>>,
1140 image_barriers: Vec<vk::ImageMemoryBarrier<'static>>,
1141}
1142
1143impl Temp {
1144 fn clear(&mut self) {
1145 self.marker.clear();
1146 self.buffer_barriers.clear();
1147 self.image_barriers.clear();
1148 }
1149
1150 fn make_c_str(&mut self, name: &str) -> &CStr {
1151 self.marker.clear();
1152 self.marker.extend_from_slice(name.as_bytes());
1153 self.marker.push(0);
1154 unsafe { CStr::from_bytes_with_nul_unchecked(&self.marker) }
1155 }
1156}
1157
1158/// Generates unique IDs for each resource of type `T`.
1159///
1160/// Because vk handles are not permanently unique, this
1161/// provides a way to generate unique IDs for each resource.
1162struct ResourceIdentityFactory<T> {
1163 #[cfg(not(target_has_atomic = "64"))]
1164 next_id: Mutex<u64>,
1165 #[cfg(target_has_atomic = "64")]
1166 next_id: wgpu_sync::atomic::AtomicU64,
1167 _phantom: PhantomData<T>,
1168}
1169
1170impl<T> ResourceIdentityFactory<T> {
1171 fn new() -> Self {
1172 Self {
1173 #[cfg(not(target_has_atomic = "64"))]
1174 next_id: Mutex::new(0),
1175 #[cfg(target_has_atomic = "64")]
1176 next_id: wgpu_sync::atomic::AtomicU64::new(0),
1177 _phantom: PhantomData,
1178 }
1179 }
1180
1181 /// Returns a new unique ID for a resource of type `T`.
1182 fn next(&self) -> ResourceIdentity<T> {
1183 #[cfg(not(target_has_atomic = "64"))]
1184 {
1185 let mut next_id = self.next_id.lock();
1186 let id = *next_id;
1187 *next_id += 1;
1188 ResourceIdentity {
1189 id,
1190 _phantom: PhantomData,
1191 }
1192 }
1193
1194 #[cfg(target_has_atomic = "64")]
1195 ResourceIdentity {
1196 id: self
1197 .next_id
1198 .fetch_add(1, core::sync::atomic::Ordering::Relaxed),
1199 _phantom: PhantomData,
1200 }
1201 }
1202}
1203
1204/// A unique identifier for a resource of type `T`.
1205///
1206/// This is used as a hashable key for resources, which
1207/// is permanently unique through the lifetime of the program.
1208#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq)]
1209struct ResourceIdentity<T> {
1210 id: u64,
1211 _phantom: PhantomData<T>,
1212}
1213
1214#[derive(Clone, Eq, Hash, PartialEq)]
1215struct FramebufferKey {
1216 raw_pass: vk::RenderPass,
1217 /// Because this is used as a key in a hash map, we need to include the identity
1218 /// so that this hashes differently, even if the ImageView handles are the same
1219 /// between different views.
1220 attachment_identities: ArrayVec<ResourceIdentity<vk::ImageView>, { MAX_TOTAL_ATTACHMENTS }>,
1221 /// While this is redundant for calculating the hash, we need access to an array
1222 /// of all the raw ImageViews when we are creating the actual framebuffer,
1223 /// so we store this here.
1224 attachment_views: ArrayVec<vk::ImageView, { MAX_TOTAL_ATTACHMENTS }>,
1225 extent: wgt::Extent3d,
1226}
1227
1228impl FramebufferKey {
1229 fn push_view(&mut self, view: IdentifiedTextureView) {
1230 self.attachment_identities.push(view.identity);
1231 self.attachment_views.push(view.raw);
1232 }
1233}
1234
1235/// A texture view paired with its identity.
1236#[derive(Copy, Clone)]
1237struct IdentifiedTextureView {
1238 raw: vk::ImageView,
1239 identity: ResourceIdentity<vk::ImageView>,
1240}
1241
1242#[derive(Clone, Eq, Hash, PartialEq)]
1243struct TempTextureViewKey {
1244 texture: vk::Image,
1245 /// As this is used in a hashmap, we need to
1246 /// include the identity so that this hashes differently,
1247 /// even if the Image handles are the same between different images.
1248 texture_identity: ResourceIdentity<vk::Image>,
1249 format: vk::Format,
1250 mip_level: u32,
1251 depth_slice: u32,
1252}
1253
1254// Any state in this struct that may be dirty after an abandoned encoding must
1255// be reset for reused encoders in `begin_encoding`.
1256pub struct CommandEncoder {
1257 raw: vk::CommandPool,
1258 device: Arc<DeviceShared>,
1259
1260 /// The current command buffer, if `self` is in the ["recording"]
1261 /// state.
1262 ///
1263 /// ["recording"]: crate::CommandEncoder
1264 ///
1265 /// If non-`null`, the buffer is in the Vulkan "recording" state.
1266 active: vk::CommandBuffer,
1267
1268 /// What kind of pass we are currently within: compute or render.
1269 bind_point: vk::PipelineBindPoint,
1270
1271 /// Allocation recycling pool for this encoder.
1272 temp: Temp,
1273
1274 /// A pool of available command buffers.
1275 ///
1276 /// These are all in the Vulkan "initial" state.
1277 free: Vec<vk::CommandBuffer>,
1278
1279 /// A pool of discarded command buffers.
1280 ///
1281 /// These could be in any Vulkan state except "pending".
1282 discarded: Vec<vk::CommandBuffer>,
1283
1284 /// If this is true, the active renderpass enabled a debug span,
1285 /// and needs to be disabled on renderpass close.
1286 rpass_debug_marker_active: bool,
1287
1288 /// If set, the end of the next render/compute pass will write a timestamp at
1289 /// the given pool & location.
1290 end_of_pass_timer_query: Option<(vk::QueryPool, u32)>,
1291
1292 framebuffers: FastHashMap<FramebufferKey, vk::Framebuffer>,
1293 temp_texture_views: FastHashMap<TempTextureViewKey, IdentifiedTextureView>,
1294
1295 counters: Arc<wgt::HalCounters>,
1296
1297 current_pipeline_is_multiview: bool,
1298}
1299
1300impl Drop for CommandEncoder {
1301 fn drop(&mut self) {
1302 // SAFETY:
1303 //
1304 // VUID-vkDestroyCommandPool-commandPool-00041: wgpu_hal requires that a
1305 // `CommandBuffer` must live until its execution is complete, and that a
1306 // `CommandBuffer` must not outlive the `CommandEncoder` that built it.
1307 // Thus, we know that none of our `CommandBuffers` are in the "pending"
1308 // state.
1309 //
1310 // The other VUIDs are pretty obvious.
1311 unsafe {
1312 // `vkDestroyCommandPool` also frees any command buffers allocated
1313 // from that pool, so there's no need to explicitly call
1314 // `vkFreeCommandBuffers` on `cmd_encoder`'s `free` and `discarded`
1315 // fields.
1316 self.device.raw.destroy_command_pool(self.raw, None);
1317 }
1318
1319 for (_, fb) in self.framebuffers.drain() {
1320 unsafe { self.device.raw.destroy_framebuffer(fb, None) };
1321 }
1322
1323 for (_, view) in self.temp_texture_views.drain() {
1324 unsafe { self.device.raw.destroy_image_view(view.raw, None) };
1325 }
1326
1327 self.counters.command_encoders.sub(1);
1328 }
1329}
1330
1331impl CommandEncoder {
1332 /// # Safety
1333 ///
1334 /// - The command buffer handle must not be manually destroyed
1335 pub unsafe fn raw_handle(&self) -> vk::CommandBuffer {
1336 self.active
1337 }
1338}
1339
1340impl fmt::Debug for CommandEncoder {
1341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1342 f.debug_struct("CommandEncoder")
1343 .field("raw", &self.raw)
1344 .finish()
1345 }
1346}
1347
1348#[derive(Debug)]
1349pub struct CommandBuffer {
1350 raw: vk::CommandBuffer,
1351}
1352
1353impl crate::DynCommandBuffer for CommandBuffer {}
1354
1355#[derive(Debug)]
1356pub enum ShaderModule {
1357 Raw(vk::ShaderModule),
1358 Intermediate {
1359 naga_shader: crate::NagaShader,
1360 runtime_checks: wgt::ShaderRuntimeChecks,
1361 },
1362}
1363
1364impl crate::DynShaderModule for ShaderModule {}
1365
1366#[derive(Debug)]
1367pub struct RenderPipeline {
1368 raw: vk::Pipeline,
1369 is_multiview: bool,
1370}
1371
1372impl crate::DynRenderPipeline for RenderPipeline {}
1373
1374#[derive(Debug)]
1375pub struct ComputePipeline {
1376 raw: vk::Pipeline,
1377}
1378
1379impl crate::ComputePipeline for ComputePipeline {
1380 fn get_subgroup_size(&self) -> Option<u32> {
1381 None
1382 }
1383}
1384
1385#[derive(Debug)]
1386pub struct RayTracingPipeline {
1387 raw: vk::Pipeline,
1388}
1389
1390impl crate::DynRayTracingPipeline for RayTracingPipeline {}
1391
1392#[derive(Debug)]
1393pub struct PipelineCache {
1394 raw: vk::PipelineCache,
1395}
1396
1397impl crate::DynPipelineCache for PipelineCache {}
1398
1399#[derive(Debug)]
1400pub struct QuerySet {
1401 raw: vk::QueryPool,
1402}
1403
1404impl crate::DynQuerySet for QuerySet {}
1405
1406/// The [`Api::Fence`] type for [`vulkan::Api`].
1407///
1408/// This is an `enum` because there are two possible implementations of
1409/// `wgpu-hal` fences on Vulkan: Vulkan fences, which work on any version of
1410/// Vulkan, and Vulkan timeline semaphores, which are easier and cheaper but
1411/// require non-1.0 features.
1412///
1413/// [`Device::create_fence`] returns a [`TimelineSemaphore`] if
1414/// [`VK_KHR_timeline_semaphore`] is available and enabled, and a [`FencePool`]
1415/// otherwise.
1416///
1417/// [`Api::Fence`]: crate::Api::Fence
1418/// [`vulkan::Api`]: Api
1419/// [`Device::create_fence`]: crate::Device::create_fence
1420/// [`TimelineSemaphore`]: Fence::TimelineSemaphore
1421/// [`VK_KHR_timeline_semaphore`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VK_KHR_timeline_semaphore
1422/// [`FencePool`]: Fence::FencePool
1423#[derive(Debug)]
1424pub enum Fence {
1425 /// A Vulkan [timeline semaphore].
1426 ///
1427 /// These are simpler to use than Vulkan fences, since timeline semaphores
1428 /// work exactly the way [`wpgu_hal::Api::Fence`] is specified to work.
1429 ///
1430 /// [timeline semaphore]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-semaphores
1431 /// [`wpgu_hal::Api::Fence`]: crate::Api::Fence
1432 TimelineSemaphore(vk::Semaphore),
1433
1434 /// A collection of Vulkan [fence]s, each associated with a [`FenceValue`].
1435 ///
1436 /// The effective [`FenceValue`] of this variant is the greater of
1437 /// `last_completed` and the maximum value associated with a signalled fence
1438 /// in `active`.
1439 ///
1440 /// Fences are available in all versions of Vulkan, but since they only have
1441 /// two states, "signaled" and "unsignaled", we need to use a separate fence
1442 /// for each queue submission we might want to wait for, and remember which
1443 /// [`FenceValue`] each one represents.
1444 ///
1445 /// One should keep the fence pool read while there are any references to the
1446 /// fences inside of them. This ensures there are no race conditions when
1447 /// resetting the fences
1448 ///
1449 /// [fence]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-fences
1450 /// [`FenceValue`]: crate::FenceValue
1451 FencePool(RwLock<FencePool>),
1452}
1453
1454/// A shared fence type. The arc is expect to have a ref-count of one once a function has finished being called
1455///
1456/// A fence should have access synchronised as fence resetting might happen at any point. Resetting checks the ref-count
1457/// of the fence, so instead of copying the fence, it should have its `Arc` container cloned which shows not to reset
1458/// this fence as it is being used.
1459pub(super) type SynchronizedFence = Arc<vk::Fence>;
1460
1461#[derive(Debug)]
1462pub struct FencePool {
1463 last_completed: crate::FenceValue,
1464 /// The pending fence values have to be ascending.
1465 active: Vec<(crate::FenceValue, SynchronizedFence)>,
1466 // Don't need extra synchronisation around the fences here, if they are used they should be put into active.
1467 free: Vec<vk::Fence>,
1468}
1469
1470impl crate::DynFence for Fence {}
1471
1472impl Fence {
1473 /// Return the highest [`FenceValue`] among the signalled fences in `active`.
1474 ///
1475 /// As an optimization, assume that we already know that the fence has
1476 /// reached `last_completed`, and don't bother checking fences whose values
1477 /// are less than that: those fences remain in the `active` array only
1478 /// because we haven't called `maintain` yet to clean them up.
1479 ///
1480 /// [`FenceValue`]: crate::FenceValue
1481 fn check_active(
1482 device: &ash::Device,
1483 mut last_completed: crate::FenceValue,
1484 active: &[(crate::FenceValue, SynchronizedFence)],
1485 ) -> Result<crate::FenceValue, crate::DeviceError> {
1486 for &(value, ref raw) in active.iter() {
1487 unsafe {
1488 if value > last_completed
1489 && device
1490 // Don't need to clone as active should be from a read or
1491 // write lock which means this is already synchronised.
1492 .get_fence_status(**raw)
1493 .map_err(map_host_device_oom_and_lost_err)?
1494 {
1495 last_completed = value;
1496 }
1497 }
1498 }
1499 Ok(last_completed)
1500 }
1501
1502 /// Return the highest signalled [`FenceValue`] for `self`.
1503 ///
1504 /// [`FenceValue`]: crate::FenceValue
1505 fn get_latest(
1506 &self,
1507 device: &ash::Device,
1508 extension: Option<&ExtensionFn<khr::timeline_semaphore::Device>>,
1509 ) -> Result<crate::FenceValue, crate::DeviceError> {
1510 match *self {
1511 Self::TimelineSemaphore(raw) => unsafe {
1512 Ok(match *extension.unwrap() {
1513 ExtensionFn::Extension(ref ext) => ext
1514 .get_semaphore_counter_value(raw)
1515 .map_err(map_host_device_oom_and_lost_err)?,
1516 ExtensionFn::Promoted => device
1517 .get_semaphore_counter_value(raw)
1518 .map_err(map_host_device_oom_and_lost_err)?,
1519 })
1520 },
1521 Self::FencePool(ref pool) => {
1522 let FencePool {
1523 last_completed,
1524 ref active,
1525 free: _,
1526 } = *pool.read();
1527 Self::check_active(device, last_completed, active)
1528 }
1529 }
1530 }
1531
1532 /// Trim the internal state of this [`Fence`].
1533 ///
1534 /// This function has no externally visible effect, but you should call it
1535 /// periodically to keep this fence's resource consumption under control.
1536 ///
1537 /// For fences using the [`FencePool`] implementation, this function
1538 /// recycles fences that have been signaled. If you don't call this,
1539 /// [`Queue::submit`] will just keep allocating a new Vulkan fence every
1540 /// time it's called.
1541 ///
1542 /// [`FencePool`]: Fence::FencePool
1543 /// [`Queue::submit`]: crate::Queue::submit
1544 fn maintain(&self, device: &ash::Device) -> Result<(), crate::DeviceError> {
1545 match *self {
1546 Self::TimelineSemaphore(_) => {}
1547 Self::FencePool(ref pool) => {
1548 let FencePool {
1549 ref mut last_completed,
1550 ref mut active,
1551 ref mut free,
1552 } = *pool.write();
1553
1554 let base_free = free.len();
1555 let latest = Self::check_active(device, *last_completed, active)?;
1556
1557 active.retain_mut(|&mut (value, ref mut fence)| {
1558 if value > latest {
1559 true
1560 } else if let Some(fence) = Arc::get_mut(fence) {
1561 // No other references to these, so we have exclusive access. Add them to free and reset them later,
1562 // but drop them from active immediately
1563 free.push(*fence);
1564 false
1565 } else {
1566 // some other function is using it. Although this shouldn't be to long,
1567 // maintain shouldn't block, and it should be cleared up by the next time it happens
1568 true
1569 }
1570 });
1571
1572 if free.len() != base_free {
1573 unsafe { device.reset_fences(&free[base_free..]) }
1574 .map_err(map_device_oom_err)?
1575 }
1576 *last_completed = latest;
1577 }
1578 }
1579 Ok(())
1580 }
1581}
1582
1583impl crate::Queue for Queue {
1584 type A = Api;
1585
1586 unsafe fn submit(
1587 &self,
1588 command_buffers: &[&CommandBuffer],
1589 surface_textures: &[&SurfaceTexture],
1590 (signal_fence, signal_value): (&Fence, crate::FenceValue),
1591 ) -> Result<(), crate::DeviceError> {
1592 let mut fence_raw = vk::Fence::null();
1593
1594 let mut wait_semaphores = SemaphoreList::new(SemaphoreListMode::Wait);
1595 let mut signal_semaphores = SemaphoreList::new(SemaphoreListMode::Signal);
1596
1597 // Assert that we will not deadlock as we try to lock each `SurfaceTexture`'s
1598 // metadata.
1599 //
1600 // The documentation for [`wgpu_hal::Queue::submit`] requires that
1601 // `surface_textures` must not contain duplicates, so simply iterating over
1602 // the slice and locking each one should be fine.
1603 debug_assert!(
1604 {
1605 let mut check = HashSet::with_capacity(surface_textures.len());
1606 // We compare the Box by pointer, as Eq isn't well defined for SurfaceSemaphores.
1607 for st in surface_textures {
1608 let ptr: *const () = <*const _>::cast(&*st.metadata);
1609 check.insert(ptr as usize);
1610 }
1611 check.len() == surface_textures.len()
1612 },
1613 "More than one surface texture is being used from the same swapchain. This will cause a deadlock in release."
1614 );
1615
1616 let locked_swapchain_semaphores = surface_textures
1617 .iter()
1618 .map(|st| st.metadata.get_semaphore_guard())
1619 .collect::<Vec<_>>();
1620
1621 for mut semaphores in locked_swapchain_semaphores {
1622 semaphores.set_used_fence_value(signal_value);
1623
1624 // If we're the first submission to operate on this image, wait on
1625 // its acquire semaphore, to make sure the presentation engine is
1626 // done with it.
1627 if let Some(sem) = semaphores.get_acquire_wait_semaphore() {
1628 wait_semaphores.push_wait(sem, vk::PipelineStageFlags::TOP_OF_PIPE);
1629 }
1630
1631 // Get a semaphore to signal when we're done writing to this surface
1632 // image. Presentation of this image will wait for this.
1633 let signal_semaphore = semaphores.get_submit_signal_semaphore(&self.device)?;
1634 signal_semaphores.push_signal(signal_semaphore);
1635 }
1636
1637 let mut guard = self.signal_semaphores.lock();
1638 if !guard.is_empty() {
1639 signal_semaphores.append(&mut guard);
1640 }
1641
1642 let mut wait_guard = self.wait_semaphores.lock();
1643 if !wait_guard.is_empty() {
1644 wait_semaphores.append(&mut wait_guard);
1645 }
1646
1647 // In order for submissions to be strictly ordered, we encode a dependency between each submission
1648 // using a pair of semaphores. This adds a wait if it is needed, and signals the next semaphore.
1649 let semaphore_state = self.relay_semaphores.lock().advance(&self.device)?;
1650
1651 if let Some(sem) = semaphore_state.wait {
1652 wait_semaphores.push_wait(
1653 SemaphoreType::Binary(sem),
1654 vk::PipelineStageFlags::TOP_OF_PIPE,
1655 );
1656 }
1657
1658 signal_semaphores.push_signal(SemaphoreType::Binary(semaphore_state.signal));
1659
1660 // We need to signal our wgpu::Fence if we have one, this adds it to the signal list.
1661 signal_fence.maintain(&self.device.raw)?;
1662 // `vkQueueSubmit` requires its fence to be externally synchronized, and other threads
1663 // access the fences in `active` (for example with `vkGetFenceStatus`) while holding the
1664 // pool's lock. Holding the lock across the submit keeps them off the new fence.
1665 let mut pool_guard = None;
1666 match *signal_fence {
1667 Fence::TimelineSemaphore(raw) => {
1668 signal_semaphores.push_signal(SemaphoreType::Timeline(raw, signal_value));
1669 }
1670 Fence::FencePool(ref pool) => {
1671 let locked_pool = pool_guard.insert(pool.write());
1672 let FencePool {
1673 ref mut active,
1674 ref mut free,
1675 ..
1676 } = **locked_pool;
1677 let shared_fence = match free.pop() {
1678 Some(raw) => Arc::new(raw),
1679 None => unsafe {
1680 let fence = self
1681 .device
1682 .raw
1683 .create_fence(&vk::FenceCreateInfo::default(), None)
1684 .map_err(map_host_device_oom_err)?;
1685 Arc::new(fence)
1686 },
1687 };
1688 fence_raw = *shared_fence;
1689 active.push((signal_value, shared_fence));
1690 }
1691 }
1692
1693 let vk_cmd_buffers = command_buffers
1694 .iter()
1695 .map(|cmd| cmd.raw)
1696 .collect::<Vec<_>>();
1697
1698 let mut vk_info = vk::SubmitInfo::default().command_buffers(&vk_cmd_buffers);
1699 let mut vk_timeline_info = mem::MaybeUninit::uninit();
1700 vk_info = SemaphoreList::add_to_submit(
1701 &mut wait_semaphores,
1702 &mut signal_semaphores,
1703 vk_info,
1704 &mut vk_timeline_info,
1705 );
1706
1707 let submit_chain = self.next_submit_chain.lock().take();
1708 if let Some(chain) = submit_chain {
1709 // SAFETY: The contract on `Queue::set_next_submit_chain()` keeps the chain
1710 // valid and unaliased until this submission is made.
1711 vk_info.p_next = unsafe { chain.splice_into(vk_info.p_next) };
1712 }
1713
1714 profiling::scope!("vkQueueSubmit");
1715 unsafe {
1716 self.device
1717 .raw
1718 .queue_submit(self.raw, &[vk_info], fence_raw)
1719 .map_err(map_host_device_oom_and_lost_err)?
1720 };
1721 Ok(())
1722 }
1723
1724 unsafe fn present(
1725 &self,
1726 surface: &Surface,
1727 texture: SurfaceTexture,
1728 damage_rects: &[wgt::Rect<u32>],
1729 ) -> Result<(), crate::SurfaceError> {
1730 let mut swapchain = surface.swapchain.write();
1731
1732 unsafe {
1733 swapchain
1734 .as_mut()
1735 .unwrap()
1736 .present(self, texture, damage_rects)
1737 }
1738 }
1739
1740 unsafe fn get_timestamp_period(&self) -> f32 {
1741 self.device.timestamp_period
1742 }
1743
1744 unsafe fn wait_for_idle(&self) -> Result<(), crate::DeviceError> {
1745 unsafe { self.device.raw.queue_wait_idle(self.raw) }
1746 .map_err(map_host_device_oom_and_lost_err)
1747 }
1748}
1749
1750impl Queue {
1751 pub fn raw_device(&self) -> &ash::Device {
1752 &self.device.raw
1753 }
1754
1755 pub fn add_signal_semaphore(&self, semaphore: vk::Semaphore, semaphore_value: Option<u64>) {
1756 let mut guard = self.signal_semaphores.lock();
1757 if let Some(value) = semaphore_value {
1758 guard.push_signal(SemaphoreType::Timeline(semaphore, value));
1759 } else {
1760 guard.push_signal(SemaphoreType::Binary(semaphore));
1761 }
1762 }
1763
1764 /// Remove `semaphore` from the pending signal list if it is still present.
1765 ///
1766 /// Returns `true` if the semaphore was found and removed. If the submit
1767 /// already consumed it, this is a harmless no-op that returns `false`.
1768 pub fn remove_signal_semaphore(&self, semaphore: vk::Semaphore) -> bool {
1769 self.signal_semaphores.lock().remove(semaphore)
1770 }
1771
1772 /// Stage a semaphore wait on the next [`crate::Queue::submit`] call.
1773 ///
1774 /// `semaphore_value` selects the kind of payload the wait targets:
1775 ///
1776 /// - `Some(value)` - wait until `semaphore` (a timeline semaphore) has been signalled to at least `value`.
1777 /// - `None` - wait on a binary semaphore signal.
1778 ///
1779 /// `stage` is the pipeline stage at which the wait blocks downstream
1780 /// work (e.g. `vk::PipelineStageFlags::TOP_OF_PIPE` to gate the
1781 /// entire submission, or a more specific stage when only that stage
1782 /// reads the synchronised resource).
1783 pub fn add_wait_semaphore(
1784 &self,
1785 semaphore: vk::Semaphore,
1786 semaphore_value: Option<u64>,
1787 stage: vk::PipelineStageFlags,
1788 ) {
1789 let mut guard = self.wait_semaphores.lock();
1790 if let Some(value) = semaphore_value {
1791 guard.push_wait(SemaphoreType::Timeline(semaphore, value), stage);
1792 } else {
1793 guard.push_wait(SemaphoreType::Binary(semaphore), stage);
1794 }
1795 }
1796
1797 /// Remove `semaphore` from the pending wait list if it is still present.
1798 ///
1799 /// Returns `true` if the semaphore was found and removed. If the submit
1800 /// already consumed it, this is a no-op that returns `false`.
1801 pub fn remove_wait_semaphore(&self, semaphore: vk::Semaphore) -> bool {
1802 self.wait_semaphores.lock().remove(semaphore)
1803 }
1804
1805 /// Set a `pNext` chain of extension structs to attach to the [`vk::SubmitInfo`]
1806 /// of the next [`submit()`](crate::Queue::submit) on this queue.
1807 ///
1808 /// This supports submission extensions that `wgpu-hal` has no dedicated support
1809 /// for. One example is `VkLatencySubmissionPresentIdNV` from `VK_NV_low_latency2`.
1810 /// The device extension itself must be enabled at device creation, for example
1811 /// with [`Adapter::open_with_callback()`](super::vulkan::Adapter::open_with_callback).
1812 ///
1813 /// The next submission on this queue consumes the chain, and a later call
1814 /// replaces a chain that hasn't been submitted yet. One `wgpu` or `wgpu-core`
1815 /// submit maps to one submission here, but layers above `wgpu-hal` also make
1816 /// housekeeping submissions of their own, for example when a buffer is mapped,
1817 /// and those consume the chain too. Set the chain right before the submission
1818 /// it applies to, with no other queue or buffer-mapping work in between.
1819 ///
1820 /// # Safety
1821 ///
1822 /// - `chain` must point to a valid `pNext` chain of structs that can extend
1823 /// [`vk::SubmitInfo`]. The extensions in the chain must be enabled on this
1824 /// queue's device.
1825 /// - The chain must stay valid until the next submission on this queue is made
1826 /// or the queue is dropped. Don't read or write the chain during that time.
1827 /// Fields the driver wrote during submission may be read afterwards.
1828 pub unsafe fn set_next_submit_chain(&self, chain: *mut c_void) {
1829 *self.next_submit_chain.lock() = Some(PnextChain::new(chain));
1830 }
1831}
1832
1833/// Maps
1834///
1835/// - VK_ERROR_OUT_OF_HOST_MEMORY
1836/// - VK_ERROR_OUT_OF_DEVICE_MEMORY
1837fn map_host_device_oom_err(err: vk::Result) -> crate::DeviceError {
1838 match err {
1839 vk::Result::ERROR_OUT_OF_HOST_MEMORY | vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => {
1840 get_oom_err(err)
1841 }
1842 e => get_unexpected_err(e),
1843 }
1844}
1845
1846/// Maps
1847///
1848/// - VK_ERROR_OUT_OF_HOST_MEMORY
1849/// - VK_ERROR_OUT_OF_DEVICE_MEMORY
1850/// - VK_ERROR_DEVICE_LOST
1851fn map_host_device_oom_and_lost_err(err: vk::Result) -> crate::DeviceError {
1852 match err {
1853 vk::Result::ERROR_DEVICE_LOST => get_lost_err(),
1854 other => map_host_device_oom_err(other),
1855 }
1856}
1857
1858/// Maps
1859///
1860/// - VK_ERROR_OUT_OF_HOST_MEMORY
1861/// - VK_ERROR_OUT_OF_DEVICE_MEMORY
1862/// - VK_ERROR_FRAGMENTATION
1863fn map_host_device_oom_and_fragmentation_err(err: vk::Result) -> crate::DeviceError {
1864 match err {
1865 vk::Result::ERROR_FRAGMENTATION => get_oom_err(err),
1866 other => map_host_device_oom_err(other),
1867 }
1868}
1869
1870/// Maps
1871///
1872/// - VK_ERROR_OUT_OF_HOST_MEMORY
1873/// - VK_ERROR_OUT_OF_DEVICE_MEMORY
1874/// - VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR
1875fn map_host_device_oom_and_ioca_err(err: vk::Result) -> crate::DeviceError {
1876 // We don't use VK_KHR_buffer_device_address
1877 // VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR
1878 map_host_device_oom_err(err)
1879}
1880
1881/// Maps
1882///
1883/// - VK_ERROR_OUT_OF_HOST_MEMORY
1884fn map_host_oom_err(err: vk::Result) -> crate::DeviceError {
1885 match err {
1886 vk::Result::ERROR_OUT_OF_HOST_MEMORY => get_oom_err(err),
1887 e => get_unexpected_err(e),
1888 }
1889}
1890
1891/// Maps
1892///
1893/// - VK_ERROR_OUT_OF_DEVICE_MEMORY
1894fn map_device_oom_err(err: vk::Result) -> crate::DeviceError {
1895 match err {
1896 vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => get_oom_err(err),
1897 e => get_unexpected_err(e),
1898 }
1899}
1900
1901/// Maps
1902///
1903/// - VK_ERROR_OUT_OF_HOST_MEMORY
1904/// - VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR
1905fn map_host_oom_and_ioca_err(err: vk::Result) -> crate::DeviceError {
1906 // We don't use VK_KHR_buffer_device_address
1907 // VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR
1908 map_host_oom_err(err)
1909}
1910
1911/// Maps
1912///
1913/// - VK_ERROR_OUT_OF_HOST_MEMORY
1914/// - VK_ERROR_OUT_OF_DEVICE_MEMORY
1915/// - VK_PIPELINE_COMPILE_REQUIRED_EXT
1916/// - VK_ERROR_INVALID_SHADER_NV
1917fn map_pipeline_err(err: vk::Result) -> crate::DeviceError {
1918 // We don't use VK_EXT_pipeline_creation_cache_control
1919 // VK_PIPELINE_COMPILE_REQUIRED_EXT
1920 // We don't use VK_NV_glsl_shader
1921 // VK_ERROR_INVALID_SHADER_NV
1922 map_host_device_oom_err(err)
1923}
1924
1925/// Returns [`crate::DeviceError::Unexpected`] or panics if the `internal_error_panic`
1926/// feature flag is enabled.
1927fn get_unexpected_err(err: vk::Result) -> crate::DeviceError {
1928 #[cfg(feature = "internal_error_panic")]
1929 panic!("Unexpected Vulkan error: {err:?}");
1930
1931 // `DeviceError::Unexpected` cannot carry the result, so log it here.
1932 #[allow(unreachable_code)]
1933 {
1934 log::error!("Unexpected Vulkan error: {err:?}");
1935 crate::DeviceError::Unexpected
1936 }
1937}
1938
1939/// Returns [`crate::DeviceError::OutOfMemory`].
1940fn get_oom_err(_err: vk::Result) -> crate::DeviceError {
1941 crate::DeviceError::OutOfMemory
1942}
1943
1944/// Returns [`crate::DeviceError::Lost`] or panics if the `device_lost_panic`
1945/// feature flag is enabled.
1946fn get_lost_err() -> crate::DeviceError {
1947 #[cfg(feature = "device_lost_panic")]
1948 panic!("Device lost");
1949
1950 #[allow(unreachable_code)]
1951 crate::DeviceError::Lost
1952}
1953
1954#[derive(Clone, Copy, Pod, Zeroable)]
1955#[repr(C)]
1956struct RawTlasInstance {
1957 transform: [f32; 12],
1958 custom_data_and_mask: u32,
1959 shader_binding_table_record_offset_and_flags: u32,
1960 acceleration_structure_reference: u64,
1961}
1962
1963/// Arguments to the [`CreateDeviceCallback`].
1964#[derive(Debug)]
1965pub struct CreateDeviceCallbackArgs<'arg, 'pnext, 'this>
1966where
1967 'this: 'pnext,
1968{
1969 /// The extensions to enable for the device. You must not remove anything from this list,
1970 /// but you may add to it.
1971 pub extensions: &'arg mut Vec<&'static CStr>,
1972 /// The physical device features to enable. You may enable features, but must not disable any.
1973 pub device_features: &'arg mut PhysicalDeviceFeatures,
1974 /// The queue create infos for the device. You may substitute a different queue, but:
1975 /// 1. Any queue you provide must be compatible with `wgpu`'s usage,
1976 /// 2. You must not leave the vector empty,
1977 /// 3. `wgpu` currently only uses the first entry.
1978 pub queue_create_infos: &'arg mut Vec<vk::DeviceQueueCreateInfo<'pnext>>,
1979 /// The create info for the device. You may add or modify things in the pnext chain, but
1980 /// do not turn features off. Additionally, do not add things to the list of extensions,
1981 /// or to the feature set, as all changes to that member will be overwritten.
1982 pub create_info: &'arg mut vk::DeviceCreateInfo<'pnext>,
1983 /// We need to have `'this` in the struct, so we can declare that all lifetimes coming from
1984 /// captures in the closure will live longer (and hence satisfy) `'pnext`. However, we
1985 /// don't actually directly use `'this`
1986 _phantom: PhantomData<&'this ()>,
1987}
1988
1989/// Callback to allow changing the vulkan device creation parameters.
1990///
1991/// # Safety:
1992/// - If you want to add extensions, add the to the `Vec<'static CStr>` not the create info,
1993/// as the create info value will be overwritten.
1994/// - Callback must not remove features.
1995/// - Callback must not change anything to what the instance does not support.
1996pub type CreateDeviceCallback<'this> =
1997 dyn for<'arg, 'pnext> FnOnce(CreateDeviceCallbackArgs<'arg, 'pnext, 'this>) + 'this;
1998
1999/// Arguments to the [`CreateInstanceCallback`].
2000#[expect(missing_debug_implementations, reason = "TODO?")]
2001pub struct CreateInstanceCallbackArgs<'arg, 'pnext, 'this>
2002where
2003 'this: 'pnext,
2004{
2005 /// The extensions to enable for the instance. You must not remove anything from this list,
2006 /// but you may add to it.
2007 pub extensions: &'arg mut Vec<&'static CStr>,
2008 /// The create info for the instance. You may add or modify things in the pnext chain, but
2009 /// do not turn features off. Additionally, do not add things to the list of extensions,
2010 /// all changes to that member will be overwritten.
2011 pub create_info: &'arg mut vk::InstanceCreateInfo<'pnext>,
2012 /// Vulkan entry point.
2013 pub entry: &'arg ash::Entry,
2014 /// We need to have `'this` in the struct, so we can declare that all lifetimes coming from
2015 /// captures in the closure will live longer (and hence satisfy) `'pnext`. However, we
2016 /// don't actually directly use `'this`
2017 _phantom: PhantomData<&'this ()>,
2018}
2019
2020/// Callback to allow changing the vulkan instance creation parameters.
2021///
2022/// # Safety:
2023/// - If you want to add extensions, add the to the `Vec<'static CStr>` not the create info,
2024/// as the create info value will be overwritten.
2025/// - Callback must not remove features.
2026/// - Callback must not change anything to what the instance does not support.
2027pub type CreateInstanceCallback<'this> =
2028 dyn for<'arg, 'pnext> FnOnce(CreateInstanceCallbackArgs<'arg, 'pnext, 'this>) + 'this;