Skip to main content

wgpu_hal/vulkan/
adapter.rs

1use alloc::{borrow::ToOwned as _, boxed::Box, collections::BTreeMap, sync::Arc, vec::Vec};
2use core::{ffi::CStr, marker::PhantomData};
3
4use ash::{ext, google, khr, vk};
5use wgpu_sync::Mutex;
6
7use crate::{vulkan::semaphore_list::SemaphoreList, AllocationSizes};
8
9use super::semaphore_list::SemaphoreListMode;
10
11fn depth_stencil_required_flags() -> vk::FormatFeatureFlags {
12    vk::FormatFeatureFlags::SAMPLED_IMAGE | vk::FormatFeatureFlags::DEPTH_STENCIL_ATTACHMENT
13}
14
15const INDEXING_FEATURES: wgt::Features = wgt::Features::TEXTURE_BINDING_ARRAY
16    .union(wgt::Features::BUFFER_BINDING_ARRAY)
17    .union(wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY)
18    .union(wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING)
19    .union(wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING)
20    .union(wgt::Features::UNIFORM_BUFFER_BINDING_ARRAYS)
21    .union(wgt::Features::PARTIALLY_BOUND_BINDING_ARRAY);
22
23/// Features that need `VK_KHR_ray_tracing_pipeline`, either directly or as a dependency.
24const RAY_TRACING_PIPELINE_FEATURES: wgt::Features =
25    wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES
26        .union(wgt::Features::EXPERIMENTAL_RAY_TRACING_INVOCATION_REORDER);
27
28/// `VK_EXT_ray_tracing_invocation_reorder`, which provides `SPV_EXT_shader_invocation_reorder`.
29///
30/// `ash` has no bindings for this, so we create bindings ad-hoc as needed. See also:
31///
32/// - <https://registry.khronos.org/vulkan/specs/latest/man/html/VK_EXT_ray_tracing_invocation_reorder.html>
33mod ray_tracing_invocation_reorder {
34    use ash::vk;
35    use core::{
36        ffi::{c_void, CStr},
37        ptr,
38    };
39
40    pub const NAME: &CStr = c"VK_EXT_ray_tracing_invocation_reorder";
41
42    /// `VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_INVOCATION_REORDER_FEATURES_EXT`.
43    const FEATURES_STRUCTURE_TYPE: vk::StructureType = vk::StructureType::from_raw(1_000_581_000);
44
45    /// `VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_INVOCATION_REORDER_PROPERTIES_EXT`.
46    const PROPERTIES_STRUCTURE_TYPE: vk::StructureType = vk::StructureType::from_raw(1_000_581_001);
47
48    /// `VK_RAY_TRACING_INVOCATION_REORDER_MODE_REORDER_EXT`.
49    const MODE_REORDER: i32 = 1;
50
51    /// <https://registry.khronos.org/vulkan/specs/latest/man/html/VkPhysicalDeviceRayTracingInvocationReorderFeaturesEXT.html>
52    #[repr(C)]
53    #[derive(Clone, Copy, Debug)]
54    pub struct FeaturesEXT {
55        pub s_type: vk::StructureType,
56        pub p_next: *mut c_void,
57        pub ray_tracing_invocation_reorder: vk::Bool32,
58    }
59
60    impl Default for FeaturesEXT {
61        fn default() -> Self {
62            Self {
63                s_type: FEATURES_STRUCTURE_TYPE,
64                p_next: ptr::null_mut(),
65                ray_tracing_invocation_reorder: vk::FALSE,
66            }
67        }
68    }
69
70    // SAFETY: The layout and `structextends` match `vk.xml`. `p_next` is only a chain pointer.
71    unsafe impl vk::ExtendsDeviceCreateInfo for FeaturesEXT {}
72    unsafe impl vk::ExtendsPhysicalDeviceFeatures2 for FeaturesEXT {}
73    unsafe impl Send for FeaturesEXT {}
74    unsafe impl Sync for FeaturesEXT {}
75
76    /// <https://registry.khronos.org/vulkan/specs/latest/man/html/VkPhysicalDeviceRayTracingInvocationReorderPropertiesEXT.html>
77    #[repr(C)]
78    #[derive(Clone, Copy, Debug)]
79    pub struct PropertiesEXT {
80        pub s_type: vk::StructureType,
81        pub p_next: *mut c_void,
82        /// A `VkRayTracingInvocationReorderModeEXT` hint that tells if the implementation is
83        /// likely to reorder invocations.
84        pub ray_tracing_invocation_reorder_reordering_hint: i32,
85        /// Unused: naga exposes no way to set a hit object's shader binding table record index.
86        pub max_shader_binding_table_record_index: u32,
87    }
88
89    impl Default for PropertiesEXT {
90        fn default() -> Self {
91            Self {
92                s_type: PROPERTIES_STRUCTURE_TYPE,
93                p_next: ptr::null_mut(),
94                ray_tracing_invocation_reorder_reordering_hint: 0,
95                max_shader_binding_table_record_index: 0,
96            }
97        }
98    }
99
100    impl PropertiesEXT {
101        pub fn mode(&self) -> wgt::RayTracingInvocationReorderMode {
102            if self.ray_tracing_invocation_reorder_reordering_hint == MODE_REORDER {
103                wgt::RayTracingInvocationReorderMode::Reorder
104            } else {
105                wgt::RayTracingInvocationReorderMode::None
106            }
107        }
108    }
109
110    // SAFETY: The layout and `structextends` match `vk.xml`. `p_next` is only a chain pointer.
111    unsafe impl vk::ExtendsPhysicalDeviceProperties2 for PropertiesEXT {}
112    unsafe impl Send for PropertiesEXT {}
113    unsafe impl Sync for PropertiesEXT {}
114}
115#[expect(rustdoc::private_intra_doc_links)]
116/// Features supported by a [`vk::PhysicalDevice`] and its extensions.
117///
118/// This is used in two phases:
119///
120/// - When enumerating adapters, this represents the features offered by the
121///   adapter. [`Instance::expose_adapter`] calls `vkGetPhysicalDeviceFeatures2`
122///   (or `vkGetPhysicalDeviceFeatures` if that is not available) to collect
123///   this information about the `VkPhysicalDevice` represented by the
124///   `wgpu_hal::ExposedAdapter`.
125///
126/// - When opening a device, this represents the features we would like to
127///   enable. At `wgpu_hal::Device` construction time,
128///   [`PhysicalDeviceFeatures::from_extensions_and_requested_features`]
129///   constructs an value of this type indicating which Vulkan features to
130///   enable, based on the `wgpu_types::Features` requested.
131///
132/// [`Instance::expose_adapter`]: super::Instance::expose_adapter
133#[derive(Debug, Default)]
134pub struct PhysicalDeviceFeatures {
135    /// Basic Vulkan 1.0 features.
136    core: vk::PhysicalDeviceFeatures,
137
138    /// Features provided by `VK_EXT_descriptor_indexing`, promoted to Vulkan 1.2.
139    pub(super) descriptor_indexing:
140        Option<vk::PhysicalDeviceDescriptorIndexingFeaturesEXT<'static>>,
141
142    /// Features provided by `VK_KHR_timeline_semaphore`, promoted to Vulkan 1.2
143    timeline_semaphore: Option<vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR<'static>>,
144
145    /// Features provided by `VK_EXT_image_robustness`, promoted to Vulkan 1.3
146    image_robustness: Option<vk::PhysicalDeviceImageRobustnessFeaturesEXT<'static>>,
147
148    /// Features provided by `VK_EXT_robustness2`.
149    robustness2: Option<vk::PhysicalDeviceRobustness2FeaturesEXT<'static>>,
150
151    /// Features provided by `VK_KHR_multiview`, promoted to Vulkan 1.1.
152    multiview: Option<vk::PhysicalDeviceMultiviewFeaturesKHR<'static>>,
153
154    /// Features provided by `VK_KHR_sampler_ycbcr_conversion`, promoted to Vulkan 1.1.
155    sampler_ycbcr_conversion: Option<vk::PhysicalDeviceSamplerYcbcrConversionFeatures<'static>>,
156
157    /// Features provided by `VK_EXT_texture_compression_astc_hdr`, promoted to Vulkan 1.3.
158    astc_hdr: Option<vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT<'static>>,
159
160    /// Features provided by `VK_KHR_shader_float16_int8`, promoted to Vulkan 1.2
161    shader_float16_int8: Option<vk::PhysicalDeviceShaderFloat16Int8Features<'static>>,
162
163    /// Features provided by `VK_KHR_16bit_storage`, promoted to Vulkan 1.1
164    _16bit_storage: Option<vk::PhysicalDevice16BitStorageFeatures<'static>>,
165
166    /// Features provided by `VK_KHR_acceleration_structure`.
167    acceleration_structure: Option<vk::PhysicalDeviceAccelerationStructureFeaturesKHR<'static>>,
168
169    /// Features provided by `VK_KHR_buffer_device_address`, promoted to Vulkan 1.2.
170    ///
171    /// We only use this feature for
172    /// [`Features::EXPERIMENTAL_RAY_QUERY`], which requires
173    /// `VK_KHR_acceleration_structure`, which depends on
174    /// `VK_KHR_buffer_device_address`, so [`Instance::expose_adapter`] only
175    /// bothers to check if `VK_KHR_acceleration_structure` is available,
176    /// leaving this `None`.
177    ///
178    /// However, we do populate this when creating a device if
179    /// [`Features::EXPERIMENTAL_RAY_QUERY`] is requested.
180    ///
181    /// [`Instance::expose_adapter`]: super::Instance::expose_adapter
182    /// [`Features::EXPERIMENTAL_RAY_QUERY`]: wgt::Features::EXPERIMENTAL_RAY_QUERY
183    buffer_device_address: Option<vk::PhysicalDeviceBufferDeviceAddressFeaturesKHR<'static>>,
184
185    /// Features provided by `VK_KHR_ray_query`,
186    ///
187    /// Vulkan requires that the feature be present if the `VK_KHR_ray_query`
188    /// extension is present, so [`Instance::expose_adapter`] doesn't bother retrieving
189    /// this from `vkGetPhysicalDeviceFeatures2`.
190    ///
191    /// However, we do populate this when creating a device if ray tracing is requested.
192    ///
193    /// [`Instance::expose_adapter`]: super::Instance::expose_adapter
194    ray_query: Option<vk::PhysicalDeviceRayQueryFeaturesKHR<'static>>,
195
196    /// Features provided by `VK_KHR_ray_tracing_pipeline`.
197    ray_tracing_pipeline: Option<vk::PhysicalDeviceRayTracingPipelineFeaturesKHR<'static>>,
198
199    /// Features provided by `VK_EXT_ray_tracing_invocation_reorder`.
200    ray_tracing_invocation_reorder: Option<ray_tracing_invocation_reorder::FeaturesEXT>,
201
202    /// Features provided by `VK_KHR_zero_initialize_workgroup_memory`, promoted
203    /// to Vulkan 1.3.
204    zero_initialize_workgroup_memory:
205        Option<vk::PhysicalDeviceZeroInitializeWorkgroupMemoryFeatures<'static>>,
206    position_fetch: Option<vk::PhysicalDeviceRayTracingPositionFetchFeaturesKHR<'static>>,
207
208    /// Features provided by `VK_KHR_shader_atomic_int64`, promoted to Vulkan 1.2.
209    shader_atomic_int64: Option<vk::PhysicalDeviceShaderAtomicInt64Features<'static>>,
210
211    /// Features provided by `VK_EXT_shader_image_atomic_int64`
212    shader_image_atomic_int64: Option<vk::PhysicalDeviceShaderImageAtomicInt64FeaturesEXT<'static>>,
213
214    /// Features provided by `VK_EXT_shader_atomic_float`.
215    shader_atomic_float: Option<vk::PhysicalDeviceShaderAtomicFloatFeaturesEXT<'static>>,
216
217    /// Features provided by `VK_EXT_subgroup_size_control`, promoted to Vulkan 1.3.
218    subgroup_size_control: Option<vk::PhysicalDeviceSubgroupSizeControlFeatures<'static>>,
219
220    /// Features provided by `VK_KHR_maintenance4`, promoted to Vulkan 1.3.
221    maintenance4: Option<vk::PhysicalDeviceMaintenance4FeaturesKHR<'static>>,
222
223    /// Features proved by `VK_EXT_mesh_shader`
224    mesh_shader: Option<vk::PhysicalDeviceMeshShaderFeaturesEXT<'static>>,
225
226    /// Features provided by `VK_KHR_shader_integer_dot_product`, promoted to Vulkan 1.3.
227    shader_integer_dot_product:
228        Option<vk::PhysicalDeviceShaderIntegerDotProductFeaturesKHR<'static>>,
229
230    /// Features provided by `VK_KHR_fragment_shader_barycentric`
231    shader_barycentrics: Option<vk::PhysicalDeviceFragmentShaderBarycentricFeaturesKHR<'static>>,
232
233    /// Features provided by `VK_KHR_portability_subset`.
234    ///
235    /// Strictly speaking this tells us what features we *don't* have compared to core.
236    portability_subset: Option<vk::PhysicalDevicePortabilitySubsetFeaturesKHR<'static>>,
237
238    /// Features provided by `VK_KHR_cooperative_matrix`
239    cooperative_matrix: Option<vk::PhysicalDeviceCooperativeMatrixFeaturesKHR<'static>>,
240
241    /// Features provided by `VK_KHR_vulkan_memory_model`, promoted to Vulkan 1.2
242    vulkan_memory_model: Option<vk::PhysicalDeviceVulkanMemoryModelFeaturesKHR<'static>>,
243
244    shader_draw_parameters: Option<vk::PhysicalDeviceShaderDrawParametersFeatures<'static>>,
245}
246
247impl PhysicalDeviceFeatures {
248    pub fn get_core(&self) -> vk::PhysicalDeviceFeatures {
249        self.core
250    }
251
252    /// Add the members of `self` into `info.enabled_features` and its `p_next` chain.
253    pub fn add_to_device_create<'a>(
254        &'a mut self,
255        mut info: vk::DeviceCreateInfo<'a>,
256    ) -> vk::DeviceCreateInfo<'a> {
257        info = info.enabled_features(&self.core);
258        if let Some(ref mut feature) = self.descriptor_indexing {
259            info = info.push_next(feature);
260        }
261        if let Some(ref mut feature) = self.timeline_semaphore {
262            info = info.push_next(feature);
263        }
264        if let Some(ref mut feature) = self.image_robustness {
265            info = info.push_next(feature);
266        }
267        if let Some(ref mut feature) = self.robustness2 {
268            info = info.push_next(feature);
269        }
270        if let Some(ref mut feature) = self.multiview {
271            info = info.push_next(feature);
272        }
273        if let Some(ref mut feature) = self.astc_hdr {
274            info = info.push_next(feature);
275        }
276        if let Some(ref mut feature) = self.shader_float16_int8 {
277            info = info.push_next(feature);
278        }
279        if let Some(ref mut feature) = self._16bit_storage {
280            info = info.push_next(feature);
281        }
282        if let Some(ref mut feature) = self.zero_initialize_workgroup_memory {
283            info = info.push_next(feature);
284        }
285        if let Some(ref mut feature) = self.acceleration_structure {
286            info = info.push_next(feature);
287        }
288        if let Some(ref mut feature) = self.buffer_device_address {
289            info = info.push_next(feature);
290        }
291        if let Some(ref mut feature) = self.ray_query {
292            info = info.push_next(feature);
293        }
294        if let Some(ref mut feature) = self.ray_tracing_pipeline {
295            info = info.push_next(feature);
296        }
297        if let Some(ref mut feature) = self.ray_tracing_invocation_reorder {
298            info = info.push_next(feature);
299        }
300        if let Some(ref mut feature) = self.shader_atomic_int64 {
301            info = info.push_next(feature);
302        }
303        if let Some(ref mut feature) = self.position_fetch {
304            info = info.push_next(feature);
305        }
306        if let Some(ref mut feature) = self.shader_image_atomic_int64 {
307            info = info.push_next(feature);
308        }
309        if let Some(ref mut feature) = self.shader_atomic_float {
310            info = info.push_next(feature);
311        }
312        if let Some(ref mut feature) = self.subgroup_size_control {
313            info = info.push_next(feature);
314        }
315        if let Some(ref mut feature) = self.maintenance4 {
316            info = info.push_next(feature);
317        }
318        if let Some(ref mut feature) = self.mesh_shader {
319            info = info.push_next(feature);
320        }
321        if let Some(ref mut feature) = self.shader_integer_dot_product {
322            info = info.push_next(feature);
323        }
324        if let Some(ref mut feature) = self.shader_barycentrics {
325            info = info.push_next(feature);
326        }
327        if let Some(ref mut feature) = self.portability_subset {
328            info = info.push_next(feature);
329        }
330        if let Some(ref mut feature) = self.cooperative_matrix {
331            info = info.push_next(feature);
332        }
333        if let Some(ref mut feature) = self.vulkan_memory_model {
334            info = info.push_next(feature);
335        }
336        if let Some(ref mut feature) = self.shader_draw_parameters {
337            info = info.push_next(feature);
338        }
339        info
340    }
341
342    fn supports_storage_input_output_16(&self) -> bool {
343        self._16bit_storage
344            .as_ref()
345            .map(|features| features.storage_input_output16 != 0)
346            .unwrap_or(false)
347    }
348
349    /// Create a `PhysicalDeviceFeatures` that can be used to create a logical
350    /// device.
351    ///
352    /// Return a `PhysicalDeviceFeatures` value capturing all the Vulkan
353    /// features needed for the given [`Features`], [`DownlevelFlags`], and
354    /// [`PrivateCapabilities`]. You can use the returned value's
355    /// [`add_to_device_create`] method to configure a
356    /// [`vk::DeviceCreateInfo`] to build a logical device providing those
357    /// features.
358    ///
359    /// To ensure that the returned value is able to select all the Vulkan
360    /// features needed to express `requested_features`, `downlevel_flags`, and
361    /// `private_caps`:
362    ///
363    /// - The given `enabled_extensions` set must include all the extensions
364    ///   selected by [`Adapter::required_device_extensions`] when passed
365    ///   `features`.
366    ///
367    /// - The given `device_api_version` must be the Vulkan API version of the
368    ///   physical device we will use to create the logical device.
369    ///
370    /// [`Features`]: wgt::Features
371    /// [`DownlevelFlags`]: wgt::DownlevelFlags
372    /// [`PrivateCapabilities`]: super::PrivateCapabilities
373    /// [`add_to_device_create`]: PhysicalDeviceFeatures::add_to_device_create
374    /// [`Adapter::required_device_extensions`]: super::Adapter::required_device_extensions
375    fn from_extensions_and_requested_features(
376        phd_capabilities: &PhysicalDeviceProperties,
377        phd_features: &PhysicalDeviceFeatures,
378        enabled_extensions: &[&'static CStr],
379        requested_features: wgt::Features,
380        downlevel_flags: wgt::DownlevelFlags,
381        private_caps: &super::PrivateCapabilities,
382    ) -> Self {
383        let device_api_version = phd_capabilities.device_api_version;
384        let needs_bindless = requested_features.intersects(
385            wgt::Features::TEXTURE_BINDING_ARRAY
386                | wgt::Features::BUFFER_BINDING_ARRAY
387                | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY
388                | wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING
389                | wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING,
390        );
391        let needs_partially_bound =
392            requested_features.intersects(wgt::Features::PARTIALLY_BOUND_BINDING_ARRAY);
393
394        Self {
395            // vk::PhysicalDeviceFeatures is a struct composed of Bool32's while
396            // Features is a bitfield so we need to map everything manually
397            core: vk::PhysicalDeviceFeatures::default()
398                .robust_buffer_access(private_caps.robust_buffer_access)
399                .independent_blend(downlevel_flags.contains(wgt::DownlevelFlags::INDEPENDENT_BLEND))
400                .sample_rate_shading(
401                    downlevel_flags.contains(wgt::DownlevelFlags::MULTISAMPLED_SHADING),
402                )
403                .image_cube_array(
404                    downlevel_flags.contains(wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES),
405                )
406                .draw_indirect_first_instance(
407                    requested_features.contains(wgt::Features::INDIRECT_FIRST_INSTANCE),
408                )
409                //.dual_src_blend(requested_features.contains(wgt::Features::DUAL_SRC_BLENDING))
410                .multi_draw_indirect(phd_features.core.multi_draw_indirect != 0)
411                .fill_mode_non_solid(requested_features.intersects(
412                    wgt::Features::POLYGON_MODE_LINE | wgt::Features::POLYGON_MODE_POINT,
413                ))
414                //.depth_bounds(requested_features.contains(wgt::Features::DEPTH_BOUNDS))
415                //.alpha_to_one(requested_features.contains(wgt::Features::ALPHA_TO_ONE))
416                //.multi_viewport(requested_features.contains(wgt::Features::MULTI_VIEWPORTS))
417                .sampler_anisotropy(
418                    downlevel_flags.contains(wgt::DownlevelFlags::ANISOTROPIC_FILTERING),
419                )
420                .texture_compression_etc2(
421                    requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_ETC2),
422                )
423                .texture_compression_astc_ldr(
424                    requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_ASTC),
425                )
426                .texture_compression_bc(
427                    requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_BC),
428                    // BC provides formats for Sliced 3D
429                )
430                //.occlusion_query_precise(requested_features.contains(wgt::Features::PRECISE_OCCLUSION_QUERY))
431                .pipeline_statistics_query(
432                    requested_features.contains(wgt::Features::PIPELINE_STATISTICS_QUERY),
433                )
434                .vertex_pipeline_stores_and_atomics(
435                    requested_features.contains(wgt::Features::VERTEX_WRITABLE_STORAGE),
436                )
437                .fragment_stores_and_atomics(
438                    downlevel_flags.contains(wgt::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE),
439                )
440                //.shader_image_gather_extended(
441                //.shader_storage_image_extended_formats(
442                .shader_uniform_buffer_array_dynamic_indexing(
443                    requested_features.contains(wgt::Features::BUFFER_BINDING_ARRAY),
444                )
445                .shader_storage_buffer_array_dynamic_indexing(requested_features.contains(
446                    wgt::Features::BUFFER_BINDING_ARRAY
447                        | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY,
448                ))
449                .shader_sampled_image_array_dynamic_indexing(
450                    requested_features.contains(wgt::Features::TEXTURE_BINDING_ARRAY),
451                )
452                .shader_storage_buffer_array_dynamic_indexing(requested_features.contains(
453                    wgt::Features::TEXTURE_BINDING_ARRAY
454                        | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY,
455                ))
456                //.shader_storage_image_array_dynamic_indexing(
457                .shader_clip_distance(requested_features.contains(wgt::Features::CLIP_DISTANCES))
458                //.shader_cull_distance(requested_features.contains(wgt::Features::SHADER_CULL_DISTANCE))
459                .shader_float64(requested_features.contains(wgt::Features::SHADER_F64))
460                .shader_int64(requested_features.contains(wgt::Features::SHADER_INT64))
461                .shader_int16(requested_features.contains(wgt::Features::SHADER_I16))
462                //.shader_resource_residency(requested_features.contains(wgt::Features::SHADER_RESOURCE_RESIDENCY))
463                .geometry_shader(requested_features.contains(wgt::Features::PRIMITIVE_INDEX))
464                .depth_clamp(requested_features.contains(wgt::Features::DEPTH_CLIP_CONTROL))
465                .depth_bias_clamp(downlevel_flags.contains(wgt::DownlevelFlags::DEPTH_BIAS_CLAMP))
466                .dual_src_blend(requested_features.contains(wgt::Features::DUAL_SOURCE_BLENDING)),
467            descriptor_indexing: if requested_features.intersects(INDEXING_FEATURES) {
468                Some(
469                    vk::PhysicalDeviceDescriptorIndexingFeaturesEXT::default()
470                        .shader_sampled_image_array_non_uniform_indexing(needs_bindless)
471                        .shader_storage_image_array_non_uniform_indexing(needs_bindless)
472                        .shader_storage_buffer_array_non_uniform_indexing(needs_bindless)
473                        .descriptor_binding_sampled_image_update_after_bind(needs_bindless)
474                        .descriptor_binding_storage_image_update_after_bind(needs_bindless)
475                        .descriptor_binding_storage_buffer_update_after_bind(needs_bindless)
476                        .descriptor_binding_partially_bound(needs_partially_bound),
477                )
478            } else {
479                None
480            },
481            timeline_semaphore: if device_api_version >= vk::API_VERSION_1_2
482                || enabled_extensions.contains(&khr::timeline_semaphore::NAME)
483            {
484                Some(
485                    vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR::default()
486                        .timeline_semaphore(private_caps.timeline_semaphores),
487                )
488            } else {
489                None
490            },
491            image_robustness: if device_api_version >= vk::API_VERSION_1_3
492                || enabled_extensions.contains(&ext::image_robustness::NAME)
493            {
494                Some(
495                    vk::PhysicalDeviceImageRobustnessFeaturesEXT::default()
496                        .robust_image_access(private_caps.robust_image_access),
497                )
498            } else {
499                None
500            },
501            robustness2: if enabled_extensions.contains(&ext::robustness2::NAME) {
502                Some(
503                    vk::PhysicalDeviceRobustness2FeaturesEXT::default()
504                        .robust_buffer_access2(private_caps.robust_buffer_access2)
505                        .robust_image_access2(private_caps.robust_image_access2),
506                )
507            } else {
508                None
509            },
510            multiview: if device_api_version >= vk::API_VERSION_1_1
511                || enabled_extensions.contains(&khr::multiview::NAME)
512            {
513                Some(
514                    vk::PhysicalDeviceMultiviewFeatures::default()
515                        .multiview(requested_features.contains(wgt::Features::MULTIVIEW)),
516                )
517            } else {
518                None
519            },
520            sampler_ycbcr_conversion: if device_api_version >= vk::API_VERSION_1_1
521                || enabled_extensions.contains(&khr::sampler_ycbcr_conversion::NAME)
522            {
523                Some(
524                    vk::PhysicalDeviceSamplerYcbcrConversionFeatures::default(), // .sampler_ycbcr_conversion(requested_features.contains(wgt::Features::TEXTURE_FORMAT_NV12))
525                )
526            } else {
527                None
528            },
529            astc_hdr: if enabled_extensions.contains(&ext::texture_compression_astc_hdr::NAME) {
530                Some(
531                    vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT::default()
532                        .texture_compression_astc_hdr(true),
533                )
534            } else {
535                None
536            },
537            shader_float16_int8: match requested_features.contains(wgt::Features::SHADER_F16) {
538                shader_float16 if shader_float16 || private_caps.shader_int8 => Some(
539                    vk::PhysicalDeviceShaderFloat16Int8Features::default()
540                        .shader_float16(shader_float16)
541                        .shader_int8(private_caps.shader_int8),
542                ),
543                _ => None,
544            },
545            _16bit_storage: if requested_features
546                .intersects(wgt::Features::SHADER_F16 | wgt::Features::SHADER_I16)
547            {
548                Some(
549                    vk::PhysicalDevice16BitStorageFeatures::default()
550                        .storage_buffer16_bit_access(true)
551                        .storage_input_output16(phd_features.supports_storage_input_output_16())
552                        .uniform_and_storage_buffer16_bit_access(true),
553                )
554            } else {
555                None
556            },
557            acceleration_structure: if enabled_extensions
558                .contains(&khr::acceleration_structure::NAME)
559            {
560                Some(
561                    vk::PhysicalDeviceAccelerationStructureFeaturesKHR::default()
562                        .acceleration_structure(true)
563                        .descriptor_binding_acceleration_structure_update_after_bind(
564                            requested_features
565                                .contains(wgt::Features::ACCELERATION_STRUCTURE_BINDING_ARRAY),
566                        ),
567                )
568            } else {
569                None
570            },
571            buffer_device_address: if enabled_extensions.contains(&khr::buffer_device_address::NAME)
572            {
573                Some(
574                    vk::PhysicalDeviceBufferDeviceAddressFeaturesKHR::default()
575                        .buffer_device_address(true),
576                )
577            } else {
578                None
579            },
580            ray_query: if enabled_extensions.contains(&khr::ray_query::NAME) {
581                Some(vk::PhysicalDeviceRayQueryFeaturesKHR::default().ray_query(true))
582            } else {
583                None
584            },
585            ray_tracing_pipeline: if enabled_extensions.contains(&khr::ray_tracing_pipeline::NAME) {
586                Some(
587                    vk::PhysicalDeviceRayTracingPipelineFeaturesKHR::default()
588                        .ray_tracing_pipeline(true),
589                )
590            } else {
591                None
592            },
593            ray_tracing_invocation_reorder: if enabled_extensions
594                .contains(&ray_tracing_invocation_reorder::NAME)
595            {
596                Some(ray_tracing_invocation_reorder::FeaturesEXT {
597                    ray_tracing_invocation_reorder: vk::TRUE,
598                    ..Default::default()
599                })
600            } else {
601                None
602            },
603            zero_initialize_workgroup_memory: if device_api_version >= vk::API_VERSION_1_3
604                || enabled_extensions.contains(&khr::zero_initialize_workgroup_memory::NAME)
605            {
606                Some(
607                    vk::PhysicalDeviceZeroInitializeWorkgroupMemoryFeatures::default()
608                        .shader_zero_initialize_workgroup_memory(
609                            private_caps.zero_initialize_workgroup_memory,
610                        ),
611                )
612            } else {
613                None
614            },
615            shader_atomic_int64: if device_api_version >= vk::API_VERSION_1_2
616                || enabled_extensions.contains(&khr::shader_atomic_int64::NAME)
617            {
618                let needed = requested_features.intersects(
619                    wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS
620                        | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX,
621                );
622                Some(
623                    vk::PhysicalDeviceShaderAtomicInt64Features::default()
624                        .shader_buffer_int64_atomics(needed)
625                        .shader_shared_int64_atomics(needed),
626                )
627            } else {
628                None
629            },
630            shader_image_atomic_int64: if enabled_extensions
631                .contains(&ext::shader_image_atomic_int64::NAME)
632            {
633                let needed = requested_features.intersects(wgt::Features::TEXTURE_INT64_ATOMIC);
634                Some(
635                    vk::PhysicalDeviceShaderImageAtomicInt64FeaturesEXT::default()
636                        .shader_image_int64_atomics(needed),
637                )
638            } else {
639                None
640            },
641            shader_atomic_float: if enabled_extensions.contains(&ext::shader_atomic_float::NAME) {
642                let needed = requested_features.contains(wgt::Features::SHADER_FLOAT32_ATOMIC);
643                Some(
644                    vk::PhysicalDeviceShaderAtomicFloatFeaturesEXT::default()
645                        .shader_buffer_float32_atomics(needed)
646                        .shader_buffer_float32_atomic_add(needed),
647                )
648            } else {
649                None
650            },
651            subgroup_size_control: if device_api_version >= vk::API_VERSION_1_3
652                || enabled_extensions.contains(&ext::subgroup_size_control::NAME)
653            {
654                Some(
655                    vk::PhysicalDeviceSubgroupSizeControlFeatures::default()
656                        .subgroup_size_control(true),
657                )
658            } else {
659                None
660            },
661            position_fetch: if enabled_extensions.contains(&khr::ray_tracing_position_fetch::NAME) {
662                Some(
663                    vk::PhysicalDeviceRayTracingPositionFetchFeaturesKHR::default()
664                        .ray_tracing_position_fetch(true),
665                )
666            } else {
667                None
668            },
669            mesh_shader: if enabled_extensions.contains(&ext::mesh_shader::NAME) {
670                let needed = requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER);
671                let multiview_needed =
672                    requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER_MULTIVIEW);
673                Some(
674                    vk::PhysicalDeviceMeshShaderFeaturesEXT::default()
675                        .mesh_shader(needed)
676                        .task_shader(needed)
677                        .multiview_mesh_shader(multiview_needed),
678                )
679            } else {
680                None
681            },
682            maintenance4: if device_api_version >= vk::API_VERSION_1_3
683                || enabled_extensions.contains(&khr::maintenance4::NAME)
684            {
685                let needed = requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER);
686                Some(vk::PhysicalDeviceMaintenance4Features::default().maintenance4(needed))
687            } else {
688                None
689            },
690            shader_integer_dot_product: if device_api_version >= vk::API_VERSION_1_3
691                || enabled_extensions.contains(&khr::shader_integer_dot_product::NAME)
692            {
693                Some(
694                    vk::PhysicalDeviceShaderIntegerDotProductFeaturesKHR::default()
695                        .shader_integer_dot_product(private_caps.shader_integer_dot_product),
696                )
697            } else {
698                None
699            },
700            shader_barycentrics: if enabled_extensions
701                .contains(&khr::fragment_shader_barycentric::NAME)
702            {
703                let needed = requested_features.intersects(
704                    wgt::Features::SHADER_BARYCENTRICS | wgt::Features::SHADER_PER_VERTEX,
705                );
706                Some(
707                    vk::PhysicalDeviceFragmentShaderBarycentricFeaturesKHR::default()
708                        .fragment_shader_barycentric(needed),
709                )
710            } else {
711                None
712            },
713            portability_subset: if enabled_extensions.contains(&khr::portability_subset::NAME) {
714                let image_view_format_swizzle_needed =
715                    requested_features.intersects(wgt::Features::TEXTURE_COMPONENT_SWIZZLE);
716                let multisample_array_needed =
717                    requested_features.intersects(wgt::Features::MULTISAMPLE_ARRAY);
718
719                Some(
720                    vk::PhysicalDevicePortabilitySubsetFeaturesKHR::default()
721                        .image_view_format_swizzle(image_view_format_swizzle_needed)
722                        .multisample_array_image(multisample_array_needed),
723                )
724            } else {
725                None
726            },
727            cooperative_matrix: if enabled_extensions.contains(&khr::cooperative_matrix::NAME) {
728                let needed =
729                    requested_features.contains(wgt::Features::EXPERIMENTAL_COOPERATIVE_MATRIX);
730                Some(
731                    vk::PhysicalDeviceCooperativeMatrixFeaturesKHR::default()
732                        .cooperative_matrix(needed),
733                )
734            } else {
735                None
736            },
737            vulkan_memory_model: if device_api_version >= vk::API_VERSION_1_2
738                || enabled_extensions.contains(&khr::vulkan_memory_model::NAME)
739            {
740                let needed =
741                    requested_features.contains(wgt::Features::EXPERIMENTAL_COOPERATIVE_MATRIX);
742                Some(
743                    vk::PhysicalDeviceVulkanMemoryModelFeaturesKHR::default()
744                        .vulkan_memory_model(needed)
745                        // The SPIR-V backend emits storage atomics with `Device`
746                        // memory scope, so whenever the Vulkan memory model is
747                        // enabled we must also enable device scope, otherwise the
748                        // validation layers report
749                        // `VUID-RuntimeSpirv-vulkanMemoryModel-06265`.
750                        .vulkan_memory_model_device_scope(needed),
751                )
752            } else {
753                None
754            },
755            shader_draw_parameters: if device_api_version >= vk::API_VERSION_1_1 {
756                let needed = requested_features.contains(wgt::Features::SHADER_DRAW_INDEX);
757                Some(
758                    vk::PhysicalDeviceShaderDrawParametersFeatures::default()
759                        .shader_draw_parameters(needed),
760                )
761            } else {
762                None
763            },
764        }
765    }
766
767    /// Compute the wgpu [`Features`] and [`DownlevelFlags`] supported by a physical device.
768    ///
769    /// Given `self`, together with the instance and physical device it was
770    /// built from, and a `caps` also built from those, determine which wgpu
771    /// features and downlevel flags the device can support.
772    ///
773    /// [`Features`]: wgt::Features
774    /// [`DownlevelFlags`]: wgt::DownlevelFlags
775    fn to_wgpu(
776        &self,
777        instance: &ash::Instance,
778        phd: vk::PhysicalDevice,
779        caps: &PhysicalDeviceProperties,
780        queue_props: &vk::QueueFamilyProperties,
781    ) -> (wgt::Features, wgt::DownlevelFlags) {
782        use wgt::{DownlevelFlags as Df, Features as F};
783        let mut features = F::empty()
784            | F::ADDRESS_MODE_CLAMP_TO_BORDER
785            | F::ADDRESS_MODE_CLAMP_TO_ZERO
786            | F::CLEAR_TEXTURE
787            | F::IMMEDIATES
788            | F::MAPPABLE_PRIMARY_BUFFERS
789            | F::MEMORY_DECORATION_COHERENT
790            | F::MEMORY_DECORATION_VOLATILE
791            | F::PASSTHROUGH_SHADERS
792            | F::PIPELINE_CACHE
793            | F::SHADER_EARLY_DEPTH_TEST
794            | F::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES
795            | F::TEXTURE_ATOMIC
796            | F::UNRESTRICTED_BYTES_PER_ROW;
797
798        let mut dl_flags = Df::empty()
799            | Df::ARBITRARY_BINDING_VIEW_DIMENSIONS
800            | Df::BASE_VERTEX
801            | Df::BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED
802            | Df::COMPARISON_SAMPLERS
803            | Df::COMPUTE_SHADERS
804            | Df::DEPTH_TEXTURE_AND_BUFFER_COPIES
805            | Df::FRAGMENT_STORAGE
806            | Df::INDIRECT_EXECUTION
807            | Df::LINEAR_INTERPOLATION
808            | Df::MSL2_1
809            | Df::NONBLOCKING_QUERY_RESOLVE
810            | Df::NON_POWER_OF_TWO_MIPMAPPED_TEXTURES
811            | Df::UNRESTRICTED_EXTERNAL_TEXTURE_COPIES
812            | Df::UNRESTRICTED_INDEX_BUFFER
813            | Df::VERTEX_STORAGE
814            | Df::VIEW_FORMATS;
815
816        // `VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL`
817        // and `VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL`
818        // is required for separate read-only depth stencil.
819        dl_flags.set(
820            Df::READ_ONLY_DEPTH_STENCIL,
821            caps.device_api_version >= vk::API_VERSION_1_1
822                || caps.supports_extension(khr::maintenance2::NAME),
823        );
824
825        dl_flags.set(
826            Df::SURFACE_VIEW_FORMATS,
827            caps.supports_extension(khr::swapchain_mutable_format::NAME)
828                || !caps.supports_extension(khr::swapchain::NAME),
829        );
830        dl_flags.set(Df::CUBE_ARRAY_TEXTURES, self.core.image_cube_array != 0);
831        dl_flags.set(Df::ANISOTROPIC_FILTERING, self.core.sampler_anisotropy != 0);
832        dl_flags.set(
833            Df::FRAGMENT_WRITABLE_STORAGE,
834            self.core.fragment_stores_and_atomics != 0,
835        );
836        dl_flags.set(Df::MULTISAMPLED_SHADING, self.core.sample_rate_shading != 0);
837        dl_flags.set(Df::INDEPENDENT_BLEND, self.core.independent_blend != 0);
838        dl_flags.set(
839            Df::FULL_DRAW_INDEX_UINT32,
840            self.core.full_draw_index_uint32 != 0,
841        );
842        dl_flags.set(Df::DEPTH_BIAS_CLAMP, self.core.depth_bias_clamp != 0);
843
844        features.set(
845            F::TIMESTAMP_QUERY
846                | F::TIMESTAMP_QUERY_INSIDE_ENCODERS
847                | F::TIMESTAMP_QUERY_INSIDE_PASSES,
848            // Vulkan strictly defines this as either 36-64, or zero.
849            queue_props.timestamp_valid_bits >= 36,
850        );
851        features.set(
852            F::INDIRECT_FIRST_INSTANCE,
853            self.core.draw_indirect_first_instance != 0,
854        );
855        //if self.core.dual_src_blend != 0
856        features.set(F::POLYGON_MODE_LINE, self.core.fill_mode_non_solid != 0);
857        features.set(F::POLYGON_MODE_POINT, self.core.fill_mode_non_solid != 0);
858        //if self.core.depth_bounds != 0 {
859        //if self.core.alpha_to_one != 0 {
860        //if self.core.multi_viewport != 0 {
861        features.set(
862            F::TEXTURE_COMPRESSION_ETC2,
863            self.core.texture_compression_etc2 != 0,
864        );
865        features.set(
866            F::TEXTURE_COMPRESSION_ASTC,
867            self.core.texture_compression_astc_ldr != 0,
868        );
869        features.set(
870            F::TEXTURE_COMPRESSION_BC,
871            self.core.texture_compression_bc != 0,
872        );
873        features.set(
874            F::TEXTURE_COMPRESSION_BC_SLICED_3D,
875            self.core.texture_compression_bc != 0, // BC guarantees Sliced 3D
876        );
877        features.set(
878            F::PIPELINE_STATISTICS_QUERY,
879            self.core.pipeline_statistics_query != 0,
880        );
881        features.set(
882            F::VERTEX_WRITABLE_STORAGE,
883            self.core.vertex_pipeline_stores_and_atomics != 0,
884        );
885
886        features.set(F::SHADER_F64, self.core.shader_float64 != 0);
887        features.set(F::SHADER_INT64, self.core.shader_int64 != 0);
888        if let Some(ref bit16) = self._16bit_storage {
889            features.set(
890                F::SHADER_I16,
891                self.core.shader_int16 != 0
892                    && bit16.storage_buffer16_bit_access != 0
893                    && bit16.uniform_and_storage_buffer16_bit_access != 0,
894            );
895        }
896
897        features.set(F::PRIMITIVE_INDEX, self.core.geometry_shader != 0);
898
899        if let Some(ref shader_atomic_int64) = self.shader_atomic_int64 {
900            features.set(
901                F::SHADER_INT64_ATOMIC_ALL_OPS | F::SHADER_INT64_ATOMIC_MIN_MAX,
902                shader_atomic_int64.shader_buffer_int64_atomics != 0
903                    && shader_atomic_int64.shader_shared_int64_atomics != 0,
904            );
905        }
906
907        if let Some(ref shader_image_atomic_int64) = self.shader_image_atomic_int64 {
908            features.set(
909                F::TEXTURE_INT64_ATOMIC,
910                shader_image_atomic_int64
911                    .shader_image_int64_atomics(true)
912                    .shader_image_int64_atomics
913                    != 0,
914            );
915        }
916
917        if let Some(ref shader_atomic_float) = self.shader_atomic_float {
918            features.set(
919                F::SHADER_FLOAT32_ATOMIC,
920                shader_atomic_float.shader_buffer_float32_atomics != 0
921                    && shader_atomic_float.shader_buffer_float32_atomic_add != 0,
922            );
923        }
924
925        if let Some(ref shader_barycentrics) = self.shader_barycentrics {
926            features.set(
927                F::SHADER_BARYCENTRICS | F::SHADER_PER_VERTEX,
928                shader_barycentrics.fragment_shader_barycentric != 0,
929            );
930        }
931
932        //if caps.supports_extension(khr::sampler_mirror_clamp_to_edge::NAME) {
933        //if caps.supports_extension(ext::sampler_filter_minmax::NAME) {
934        features.set(
935            F::MULTI_DRAW_INDIRECT_COUNT,
936            caps.supports_extension(khr::draw_indirect_count::NAME),
937        );
938        features.set(
939            F::CONSERVATIVE_RASTERIZATION,
940            caps.supports_extension(ext::conservative_rasterization::NAME),
941        );
942        features.set(
943            F::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN,
944            caps.supports_extension(khr::ray_tracing_position_fetch::NAME),
945        );
946
947        if let Some(ref descriptor_indexing) = self.descriptor_indexing {
948            // We use update-after-bind descriptors for all bind groups containing binding arrays.
949            //
950            // In those bind groups, we allow all binding types except uniform buffers to be present.
951            //
952            // As we can only switch between update-after-bind and not on a per bind group basis,
953            // all supported binding types need to be able to be marked update after bind.
954            //
955            // As such, we enable all features as a whole, rather individually.
956            let supports_descriptor_indexing =
957                // Sampled Images
958                descriptor_indexing.shader_sampled_image_array_non_uniform_indexing != 0
959                    && descriptor_indexing.descriptor_binding_sampled_image_update_after_bind != 0
960                    // Storage Images
961                    && descriptor_indexing.shader_storage_image_array_non_uniform_indexing != 0
962                    && descriptor_indexing.descriptor_binding_storage_image_update_after_bind != 0
963                    // Storage Buffers
964                    && descriptor_indexing.shader_storage_buffer_array_non_uniform_indexing != 0
965                    && descriptor_indexing.descriptor_binding_storage_buffer_update_after_bind != 0;
966
967            let descriptor_indexing_features = F::BUFFER_BINDING_ARRAY
968                | F::TEXTURE_BINDING_ARRAY
969                | F::STORAGE_RESOURCE_BINDING_ARRAY
970                | F::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING
971                | F::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING;
972
973            features.set(descriptor_indexing_features, supports_descriptor_indexing);
974
975            let supports_partially_bound =
976                descriptor_indexing.descriptor_binding_partially_bound != 0;
977
978            features.set(F::PARTIALLY_BOUND_BINDING_ARRAY, supports_partially_bound);
979        }
980
981        features.set(F::DEPTH_CLIP_CONTROL, self.core.depth_clamp != 0);
982        features.set(F::DUAL_SOURCE_BLENDING, self.core.dual_src_blend != 0);
983        features.set(F::CLIP_DISTANCES, self.core.shader_clip_distance != 0);
984
985        if let Some(ref multiview) = self.multiview {
986            features.set(F::MULTIVIEW, multiview.multiview != 0);
987            features.set(F::SELECTIVE_MULTIVIEW, multiview.multiview != 0);
988        }
989
990        features.set(
991            F::TEXTURE_FORMAT_16BIT_NORM,
992            is_format_16bit_norm_supported(instance, phd),
993        );
994
995        if let Some(ref astc_hdr) = self.astc_hdr {
996            features.set(
997                F::TEXTURE_COMPRESSION_ASTC_HDR,
998                astc_hdr.texture_compression_astc_hdr != 0,
999            );
1000        }
1001
1002        if self.core.texture_compression_astc_ldr != 0 {
1003            features.set(
1004                F::TEXTURE_COMPRESSION_ASTC_SLICED_3D,
1005                supports_astc_3d(instance, phd),
1006            );
1007        }
1008
1009        if let (Some(ref f16_i8), Some(ref bit16)) = (self.shader_float16_int8, self._16bit_storage)
1010        {
1011            // Note `storage_input_output16` is not required, we polyfill `f16` I/O using `f32`
1012            // types when this capability is not available
1013            features.set(
1014                F::SHADER_F16,
1015                f16_i8.shader_float16 != 0
1016                    && bit16.storage_buffer16_bit_access != 0
1017                    && bit16.uniform_and_storage_buffer16_bit_access != 0,
1018            );
1019        }
1020
1021        if let Some(ref subgroup) = caps.subgroup {
1022            if (caps.device_api_version >= vk::API_VERSION_1_3
1023                || caps.supports_extension(ext::subgroup_size_control::NAME))
1024                && subgroup.supported_operations.contains(
1025                    vk::SubgroupFeatureFlags::BASIC
1026                        | vk::SubgroupFeatureFlags::VOTE
1027                        | vk::SubgroupFeatureFlags::ARITHMETIC
1028                        | vk::SubgroupFeatureFlags::BALLOT
1029                        | vk::SubgroupFeatureFlags::SHUFFLE
1030                        | vk::SubgroupFeatureFlags::SHUFFLE_RELATIVE
1031                        | vk::SubgroupFeatureFlags::QUAD,
1032                )
1033            {
1034                features.set(
1035                    F::SUBGROUP,
1036                    subgroup
1037                        .supported_stages
1038                        .contains(vk::ShaderStageFlags::COMPUTE | vk::ShaderStageFlags::FRAGMENT),
1039                );
1040                features.set(
1041                    F::SUBGROUP_VERTEX,
1042                    subgroup
1043                        .supported_stages
1044                        .contains(vk::ShaderStageFlags::VERTEX),
1045                );
1046                features.insert(F::SUBGROUP_BARRIER);
1047            }
1048        }
1049
1050        let supports_depth_format = |format| {
1051            supports_format(
1052                instance,
1053                phd,
1054                format,
1055                vk::ImageTiling::OPTIMAL,
1056                depth_stencil_required_flags(),
1057            )
1058        };
1059
1060        let texture_s8 = supports_depth_format(vk::Format::S8_UINT);
1061        let texture_d32 = supports_depth_format(vk::Format::D32_SFLOAT);
1062        let texture_d24_s8 = supports_depth_format(vk::Format::D24_UNORM_S8_UINT);
1063        let texture_d32_s8 = supports_depth_format(vk::Format::D32_SFLOAT_S8_UINT);
1064
1065        let stencil8 = texture_s8 || texture_d24_s8;
1066        let depth24_plus_stencil8 = texture_d24_s8 || texture_d32_s8;
1067
1068        dl_flags.set(
1069            Df::WEBGPU_TEXTURE_FORMAT_SUPPORT,
1070            stencil8 && depth24_plus_stencil8 && texture_d32,
1071        );
1072
1073        features.set(F::DEPTH32FLOAT_STENCIL8, texture_d32_s8);
1074
1075        let supports_acceleration_structures = caps
1076            .supports_extension(khr::deferred_host_operations::NAME)
1077            && caps.supports_extension(khr::acceleration_structure::NAME)
1078            && caps.supports_extension(khr::buffer_device_address::NAME);
1079
1080        let supports_ray_query =
1081            supports_acceleration_structures && caps.supports_extension(khr::ray_query::NAME);
1082        let supports_acceleration_structure_binding_array = supports_ray_query
1083            && self
1084                .acceleration_structure
1085                .as_ref()
1086                .is_some_and(|features| {
1087                    features.descriptor_binding_acceleration_structure_update_after_bind != 0
1088                });
1089
1090        features.set(
1091            F::EXPERIMENTAL_RAY_QUERY
1092            // Although this doesn't really require ray queries, it does not make sense to be enabled if acceleration structures
1093            // aren't enabled.
1094                | F::EXTENDED_ACCELERATION_STRUCTURE_VERTEX_FORMATS,
1095            supports_ray_query,
1096        );
1097
1098        // Binding arrays of TLAS are supported on Vulkan when ray queries are supported.
1099        //
1100        // Note: this flag is used for shader-side `binding_array<acceleration_structure>` as well as
1101        // allowing `BindGroupLayoutEntry::count = Some(...)` for `BindingType::AccelerationStructure`.
1102        features.set(
1103            F::ACCELERATION_STRUCTURE_BINDING_ARRAY,
1104            supports_acceleration_structure_binding_array,
1105        );
1106
1107        if supports_acceleration_structures
1108            && caps.supports_extension(khr::ray_tracing_pipeline::NAME)
1109        {
1110            features.insert(
1111                F::EXPERIMENTAL_RAY_TRACING_PIPELINES
1112                        // Same reason as for ray queries.
1113                        | F::EXTENDED_ACCELERATION_STRUCTURE_VERTEX_FORMATS,
1114            );
1115
1116            // Hit objects only exist in ray tracing pipeline stages, so this is of no use
1117            // without `EXPERIMENTAL_RAY_TRACING_PIPELINES`.
1118            if let Some(ref reorder) = self.ray_tracing_invocation_reorder {
1119                features.set(
1120                    F::EXPERIMENTAL_RAY_TRACING_INVOCATION_REORDER,
1121                    reorder.ray_tracing_invocation_reorder != 0,
1122                );
1123            }
1124        }
1125
1126        let rg11b10ufloat_renderable = supports_format(
1127            instance,
1128            phd,
1129            vk::Format::B10G11R11_UFLOAT_PACK32,
1130            vk::ImageTiling::OPTIMAL,
1131            vk::FormatFeatureFlags::COLOR_ATTACHMENT
1132                | vk::FormatFeatureFlags::COLOR_ATTACHMENT_BLEND,
1133        );
1134        features.set(F::RG11B10UFLOAT_RENDERABLE, rg11b10ufloat_renderable);
1135
1136        features.set(
1137            F::BGRA8UNORM_STORAGE,
1138            supports_bgra8unorm_storage(instance, phd, caps.device_api_version),
1139        );
1140
1141        features.set(
1142            F::FLOAT32_FILTERABLE,
1143            is_float32_filterable_supported(instance, phd),
1144        );
1145
1146        features.set(
1147            F::FLOAT32_BLENDABLE,
1148            is_float32_blendable_supported(instance, phd),
1149        );
1150
1151        if let Some(ref _sampler_ycbcr_conversion) = self.sampler_ycbcr_conversion {
1152            features.set(
1153                F::TEXTURE_FORMAT_NV12,
1154                supports_format(
1155                    instance,
1156                    phd,
1157                    vk::Format::G8_B8R8_2PLANE_420_UNORM,
1158                    vk::ImageTiling::OPTIMAL,
1159                    vk::FormatFeatureFlags::SAMPLED_IMAGE
1160                        | vk::FormatFeatureFlags::TRANSFER_SRC
1161                        | vk::FormatFeatureFlags::TRANSFER_DST,
1162                ) && !caps.is_driver(vk::DriverId::MOLTENVK),
1163            );
1164        }
1165
1166        if let Some(ref _sampler_ycbcr_conversion) = self.sampler_ycbcr_conversion {
1167            features.set(
1168                F::TEXTURE_FORMAT_P010,
1169                supports_format(
1170                    instance,
1171                    phd,
1172                    vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16,
1173                    vk::ImageTiling::OPTIMAL,
1174                    vk::FormatFeatureFlags::SAMPLED_IMAGE
1175                        | vk::FormatFeatureFlags::TRANSFER_SRC
1176                        | vk::FormatFeatureFlags::TRANSFER_DST,
1177                ) && !caps.is_driver(vk::DriverId::MOLTENVK),
1178            );
1179        }
1180
1181        features.set(
1182            F::EXPERIMENTAL_MESH_SHADER,
1183            caps.supports_extension(ext::mesh_shader::NAME),
1184        );
1185        features.set(
1186            F::EXPERIMENTAL_MESH_SHADER_POINTS,
1187            caps.supports_extension(ext::mesh_shader::NAME),
1188        );
1189        if let Some(ref mesh_shader) = self.mesh_shader {
1190            features.set(
1191                F::EXPERIMENTAL_MESH_SHADER_MULTIVIEW,
1192                mesh_shader.multiview_mesh_shader != 0,
1193            );
1194        }
1195
1196        // Not supported by default by `VK_KHR_portability_subset`, which we use on apple platforms.
1197        features.set(
1198            F::TEXTURE_COMPONENT_SWIZZLE,
1199            self.portability_subset
1200                .map(|p| p.image_view_format_swizzle == vk::TRUE)
1201                .unwrap_or(true),
1202        );
1203        features.set(
1204            F::MULTISAMPLE_ARRAY,
1205            self.portability_subset
1206                .map(|p| p.multisample_array_image == vk::TRUE)
1207                .unwrap_or(true),
1208        );
1209
1210        // Enable cooperative matrix if any configuration is supported. The SPIR-V
1211        // we emit for it uses `Device`-scope atomics under the Vulkan memory model,
1212        // so the device must also support `vulkanMemoryModelDeviceScope`, otherwise
1213        // those shaders trip `VUID-RuntimeSpirv-vulkanMemoryModel-06265`.
1214        features.set(
1215            F::EXPERIMENTAL_COOPERATIVE_MATRIX,
1216            !caps.cooperative_matrix_properties.is_empty()
1217                && self.vulkan_memory_model.is_some_and(|m| {
1218                    m.vulkan_memory_model == vk::TRUE
1219                        && m.vulkan_memory_model_device_scope == vk::TRUE
1220                }),
1221        );
1222
1223        features.set(
1224            F::SHADER_DRAW_INDEX,
1225            self.shader_draw_parameters
1226                .is_some_and(|a| a.shader_draw_parameters != 0)
1227                || caps.supports_extension(c"VK_KHR_shader_draw_parameters"),
1228        );
1229
1230        features.set(
1231            F::DEBUG_PRINTF,
1232            caps.device_api_version >= vk::API_VERSION_1_3
1233                || caps.supports_extension(khr::shader_non_semantic_info::NAME),
1234        );
1235
1236        (features, dl_flags)
1237    }
1238}
1239
1240/// Vulkan "properties" structures gathered about a physical device.
1241///
1242/// This structure holds the properties of a [`vk::PhysicalDevice`]:
1243/// - the standard Vulkan device properties
1244/// - the `VkExtensionProperties` structs for all available extensions, and
1245/// - the per-extension properties structures for the available extensions that
1246///   `wgpu` cares about.
1247///
1248/// Generally, if you get it from any of these functions, it's stored
1249/// here:
1250/// - `vkEnumerateDeviceExtensionProperties`
1251/// - `vkGetPhysicalDeviceProperties`
1252/// - `vkGetPhysicalDeviceProperties2`
1253///
1254/// This also includes a copy of the device API version, since we can
1255/// use that as a shortcut for searching for an extension, if the
1256/// extension has been promoted to core in the current version.
1257///
1258/// This does not include device features; for those, see
1259/// [`PhysicalDeviceFeatures`].
1260#[derive(Default, Debug)]
1261pub struct PhysicalDeviceProperties {
1262    /// Extensions supported by the `vk::PhysicalDevice`,
1263    /// as returned by `vkEnumerateDeviceExtensionProperties`.
1264    supported_extensions: Vec<vk::ExtensionProperties>,
1265
1266    /// Properties of the `vk::PhysicalDevice`, as returned by
1267    /// `vkGetPhysicalDeviceProperties`.
1268    properties: vk::PhysicalDeviceProperties,
1269
1270    /// Additional `vk::PhysicalDevice` properties from the
1271    /// `VK_KHR_maintenance3` extension, promoted to Vulkan 1.1.
1272    maintenance_3: Option<vk::PhysicalDeviceMaintenance3Properties<'static>>,
1273
1274    /// Additional `vk::PhysicalDevice` properties from the
1275    /// `VK_KHR_maintenance4` extension, promoted to Vulkan 1.3.
1276    maintenance_4: Option<vk::PhysicalDeviceMaintenance4Properties<'static>>,
1277
1278    /// Additional `vk::PhysicalDevice` properties from the
1279    /// `VK_KHR_maintenance5` extension, promoted to Vulkan 1.4.
1280    maintenance_5: Option<vk::PhysicalDeviceMaintenance5PropertiesKHR<'static>>,
1281
1282    /// Additional `vk::PhysicalDevice` properties from the
1283    /// `VK_EXT_descriptor_indexing` extension, promoted to Vulkan 1.2.
1284    descriptor_indexing: Option<vk::PhysicalDeviceDescriptorIndexingPropertiesEXT<'static>>,
1285
1286    /// Additional `vk::PhysicalDevice` properties from the
1287    /// `VK_KHR_acceleration_structure` extension.
1288    acceleration_structure: Option<vk::PhysicalDeviceAccelerationStructurePropertiesKHR<'static>>,
1289
1290    /// Additional `vk::PhysicalDevice` properties from the
1291    /// `VK_KHR_ray_tracing_pipeline` extension.
1292    ray_tracing_pipeline: Option<vk::PhysicalDeviceRayTracingPipelinePropertiesKHR<'static>>,
1293
1294    /// Additional `vk::PhysicalDevice` properties from the
1295    /// `VK_EXT_ray_tracing_invocation_reorder` extension.
1296    ray_tracing_invocation_reorder: Option<ray_tracing_invocation_reorder::PropertiesEXT>,
1297
1298    /// Additional `vk::PhysicalDevice` properties from the
1299    /// `VK_KHR_driver_properties` extension, promoted to Vulkan 1.2.
1300    driver: Option<vk::PhysicalDeviceDriverPropertiesKHR<'static>>,
1301
1302    /// Additional `vk::PhysicalDevice` properties from Vulkan 1.1.
1303    subgroup: Option<vk::PhysicalDeviceSubgroupProperties<'static>>,
1304
1305    /// Additional `vk::PhysicalDevice` properties from the
1306    /// `VK_EXT_subgroup_size_control` extension, promoted to Vulkan 1.3.
1307    subgroup_size_control: Option<vk::PhysicalDeviceSubgroupSizeControlProperties<'static>>,
1308
1309    /// Additional `vk::PhysicalDevice` properties from the
1310    /// `VK_EXT_robustness2` extension.
1311    robustness2: Option<vk::PhysicalDeviceRobustness2PropertiesEXT<'static>>,
1312
1313    /// Additional `vk::PhysicalDevice` properties from the
1314    /// `VK_EXT_mesh_shader` extension.
1315    mesh_shader: Option<vk::PhysicalDeviceMeshShaderPropertiesEXT<'static>>,
1316
1317    /// Additional `vk::PhysicalDevice` properties from the
1318    /// `VK_KHR_multiview` extension.
1319    multiview: Option<vk::PhysicalDeviceMultiviewPropertiesKHR<'static>>,
1320
1321    /// `VK_EXT_pci_bus_info` extension.
1322    pci_bus_info: Option<vk::PhysicalDevicePCIBusInfoPropertiesEXT<'static>>,
1323
1324    /// The device API version.
1325    ///
1326    /// Which is the version of Vulkan supported for device-level functionality.
1327    ///
1328    /// It is associated with a `VkPhysicalDevice` and its children.
1329    device_api_version: u32,
1330
1331    /// Supported cooperative matrix configurations.
1332    ///
1333    /// This is determined by querying `vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR`.
1334    cooperative_matrix_properties: Vec<wgt::CooperativeMatrixProperties>,
1335}
1336
1337impl PhysicalDeviceProperties {
1338    pub fn properties(&self) -> vk::PhysicalDeviceProperties {
1339        self.properties
1340    }
1341
1342    pub fn supports_extension(&self, extension: &CStr) -> bool {
1343        self.supported_extensions
1344            .iter()
1345            .any(|ep| ep.extension_name_as_c_str() == Ok(extension))
1346    }
1347
1348    pub fn is_driver(&self, id: vk::DriverId) -> bool {
1349        self.driver.is_some_and(|driver| driver.driver_id == id)
1350    }
1351
1352    /// Map `requested_features` to the list of Vulkan extension strings required to create the logical device.
1353    fn get_required_extensions(&self, requested_features: wgt::Features) -> Vec<&'static CStr> {
1354        let mut extensions = Vec::new();
1355
1356        // Note that quite a few extensions depend on the `VK_KHR_get_physical_device_properties2` instance extension.
1357        // We enable `VK_KHR_get_physical_device_properties2` unconditionally (if available).
1358
1359        // Require `VK_KHR_swapchain`
1360        extensions.push(khr::swapchain::NAME);
1361
1362        if self.device_api_version < vk::API_VERSION_1_1 {
1363            // Require `VK_KHR_maintenance1`
1364            extensions.push(khr::maintenance1::NAME);
1365
1366            // Optional `VK_KHR_maintenance2`
1367            if self.supports_extension(khr::maintenance2::NAME) {
1368                extensions.push(khr::maintenance2::NAME);
1369            }
1370
1371            // Optional `VK_KHR_maintenance3`
1372            if self.supports_extension(khr::maintenance3::NAME) {
1373                extensions.push(khr::maintenance3::NAME);
1374            }
1375
1376            // Require `VK_KHR_storage_buffer_storage_class`
1377            extensions.push(khr::storage_buffer_storage_class::NAME);
1378
1379            // Require `VK_KHR_multiview` if the associated feature was requested
1380            if requested_features.contains(wgt::Features::MULTIVIEW) {
1381                extensions.push(khr::multiview::NAME);
1382            }
1383
1384            // Require `VK_KHR_sampler_ycbcr_conversion` if the associated feature was requested
1385            if requested_features.contains(wgt::Features::TEXTURE_FORMAT_NV12) {
1386                extensions.push(khr::sampler_ycbcr_conversion::NAME);
1387            }
1388
1389            // Require `VK_KHR_16bit_storage` if `SHADER_F16` or `SHADER_I16` was requested
1390            if requested_features.intersects(wgt::Features::SHADER_F16 | wgt::Features::SHADER_I16)
1391            {
1392                // - Feature `SHADER_F16` also requires `VK_KHR_shader_float16_int8`, but we always
1393                //   require that anyway (if it is available) below.
1394                // - `VK_KHR_16bit_storage` requires `VK_KHR_storage_buffer_storage_class`, however
1395                //   we require that one already.
1396                extensions.push(khr::_16bit_storage::NAME);
1397            }
1398
1399            if requested_features.contains(wgt::Features::SHADER_DRAW_INDEX) {
1400                extensions.push(khr::shader_draw_parameters::NAME);
1401            }
1402        }
1403
1404        if self.device_api_version < vk::API_VERSION_1_2 {
1405            // Optional `VK_KHR_image_format_list`
1406            if self.supports_extension(khr::image_format_list::NAME) {
1407                extensions.push(khr::image_format_list::NAME);
1408            }
1409
1410            // Optional `VK_KHR_driver_properties`
1411            if self.supports_extension(khr::driver_properties::NAME) {
1412                extensions.push(khr::driver_properties::NAME);
1413            }
1414
1415            // Optional `VK_KHR_timeline_semaphore`
1416            if self.supports_extension(khr::timeline_semaphore::NAME) {
1417                extensions.push(khr::timeline_semaphore::NAME);
1418            }
1419
1420            // Require `VK_EXT_descriptor_indexing` if one of the associated features was requested
1421            if requested_features.intersects(INDEXING_FEATURES) {
1422                extensions.push(ext::descriptor_indexing::NAME);
1423            }
1424
1425            // Always require `VK_KHR_shader_float16_int8` if available as it enables
1426            // Int8 optimizations. Also require it even if it's not available but
1427            // requested so that we get a corresponding error message.
1428            if requested_features.contains(wgt::Features::SHADER_F16)
1429                || self.supports_extension(khr::shader_float16_int8::NAME)
1430            {
1431                extensions.push(khr::shader_float16_int8::NAME);
1432            }
1433
1434            // `SPV_EXT_mesh_shader`, `SPV_KHR_ray_tracing` and
1435            // `SPV_EXT_shader_invocation_reorder` all require SPIR-V 1.4.
1436            if requested_features
1437                .intersects(wgt::Features::EXPERIMENTAL_MESH_SHADER | RAY_TRACING_PIPELINE_FEATURES)
1438            {
1439                extensions.push(khr::spirv_1_4::NAME);
1440            }
1441
1442            //extensions.push(khr::sampler_mirror_clamp_to_edge::NAME);
1443            //extensions.push(ext::sampler_filter_minmax::NAME);
1444        }
1445
1446        if self.device_api_version < vk::API_VERSION_1_3 {
1447            // Optional `VK_KHR_maintenance4`
1448            if self.supports_extension(khr::maintenance4::NAME) {
1449                extensions.push(khr::maintenance4::NAME);
1450            }
1451
1452            // Optional `VK_EXT_image_robustness`
1453            if self.supports_extension(ext::image_robustness::NAME) {
1454                extensions.push(ext::image_robustness::NAME);
1455            }
1456
1457            // Require `VK_EXT_subgroup_size_control` if the associated feature was requested
1458            if requested_features.contains(wgt::Features::SUBGROUP) {
1459                extensions.push(ext::subgroup_size_control::NAME);
1460            }
1461
1462            // Optional `VK_KHR_shader_integer_dot_product`
1463            if self.supports_extension(khr::shader_integer_dot_product::NAME) {
1464                extensions.push(khr::shader_integer_dot_product::NAME);
1465            }
1466
1467            // Optional `VK_KHR_dynamic_rendering`.
1468            // Depends on:
1469            // - `VK_KHR_get_physical_device_properties2` or Vulkan 1.1, and `VK_KHR_depth_stencil_resolve`
1470            // - or Vulkan 1.2
1471            //
1472            // We only check Vulkan 1.2 for now, as `VK_KHR_depth_stencil_resolve`
1473            // also depends a bunch of extensions.
1474            if self.device_api_version >= vk::API_VERSION_1_2
1475                && self.supports_extension(khr::dynamic_rendering::NAME)
1476            {
1477                extensions.push(khr::dynamic_rendering::NAME);
1478            }
1479
1480            // Optional `VK_KHR_load_store_op_none`
1481            if self.supports_extension(khr::load_store_op_none::NAME) {
1482                extensions.push(khr::load_store_op_none::NAME);
1483            }
1484
1485            // Optional `VK_QCOM_render_pass_store_ops`
1486            if self.supports_extension(ash::qcom::render_pass_store_ops::NAME) {
1487                extensions.push(ash::qcom::render_pass_store_ops::NAME);
1488            }
1489
1490            // Optional `VK_EXT_load_store_op_none`
1491            if self.supports_extension(ext::load_store_op_none::NAME) {
1492                extensions.push(ext::load_store_op_none::NAME);
1493            }
1494
1495            // Require `VK_KHR_shader_non_semantic_info` if the associated feature was requested
1496            if requested_features.contains(wgt::Features::DEBUG_PRINTF) {
1497                extensions.push(khr::shader_non_semantic_info::NAME);
1498            }
1499        }
1500
1501        // Optional `VK_KHR_swapchain_mutable_format`
1502        if self.supports_extension(khr::swapchain_mutable_format::NAME) {
1503            extensions.push(khr::swapchain_mutable_format::NAME);
1504        }
1505
1506        // Optional `VK_KHR_incremental_present`
1507        if self.supports_extension(khr::incremental_present::NAME) {
1508            extensions.push(khr::incremental_present::NAME);
1509        }
1510
1511        // Optional `VK_EXT_robustness2`
1512        if self.supports_extension(ext::robustness2::NAME) {
1513            extensions.push(ext::robustness2::NAME);
1514        }
1515
1516        // Optional `VK_KHR_external_memory_win32`
1517        if self.supports_extension(khr::external_memory_win32::NAME) {
1518            extensions.push(khr::external_memory_win32::NAME);
1519        }
1520
1521        // Optional `VK_KHR_external_memory_fd`
1522        if self.supports_extension(khr::external_memory_fd::NAME) {
1523            extensions.push(khr::external_memory_fd::NAME);
1524        }
1525
1526        // Optional `VK_EXT_external_memory_dma`
1527        if self.supports_extension(ext::external_memory_dma_buf::NAME) {
1528            extensions.push(ext::external_memory_dma_buf::NAME);
1529        }
1530
1531        // Optional `VK_EXT_image_drm_format_modifier`
1532        if self.supports_extension(ext::image_drm_format_modifier::NAME) {
1533            extensions.push(ext::image_drm_format_modifier::NAME);
1534        }
1535
1536        // Optional `VK_GOOGLE_display_timing`
1537        if self.supports_extension(google::display_timing::NAME) {
1538            extensions.push(google::display_timing::NAME);
1539        }
1540
1541        // Optional `VK_EXT_memory_budget`
1542        if self.supports_extension(ext::memory_budget::NAME) {
1543            extensions.push(ext::memory_budget::NAME);
1544        } else {
1545            log::debug!("VK_EXT_memory_budget is not available.")
1546        }
1547
1548        // Require `VK_KHR_draw_indirect_count` if the associated feature was requested
1549        // Even though Vulkan 1.2 has promoted the extension to core, we must require the extension to avoid
1550        // large amounts of spaghetti involved with using PhysicalDeviceVulkan12Features.
1551        if requested_features.contains(wgt::Features::MULTI_DRAW_INDIRECT_COUNT) {
1552            extensions.push(khr::draw_indirect_count::NAME);
1553        }
1554
1555        // Require `VK_KHR_deferred_host_operations`, `VK_KHR_acceleration_structure` `VK_KHR_buffer_device_address` (for acceleration structures) if either `EXPERIMENTAL_RAY_QUERY` or `EXPERIMENTAL_RAY_TRACING_PIPELINES` were requested.
1556        if requested_features
1557            .intersects(wgt::Features::EXPERIMENTAL_RAY_QUERY | RAY_TRACING_PIPELINE_FEATURES)
1558        {
1559            extensions.push(khr::deferred_host_operations::NAME);
1560            extensions.push(khr::acceleration_structure::NAME);
1561            extensions.push(khr::buffer_device_address::NAME);
1562        }
1563
1564        // Require `VK_KHR_ray_query` if `EXPERIMENTAL_RAY_QUERY` was requested
1565        if requested_features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) {
1566            extensions.push(khr::ray_query::NAME);
1567        }
1568
1569        // Require `VK_KHR_ray_tracing_pipeline` if `EXPERIMENTAL_RAY_TRACING_PIPELINES` was
1570        // requested, or `EXPERIMENTAL_RAY_TRACING_INVOCATION_REORDER`, which depends on it.
1571        if requested_features.intersects(RAY_TRACING_PIPELINE_FEATURES) {
1572            extensions.push(khr::ray_tracing_pipeline::NAME);
1573        }
1574
1575        // Require `VK_EXT_ray_tracing_invocation_reorder` if
1576        // `EXPERIMENTAL_RAY_TRACING_INVOCATION_REORDER` was requested.
1577        if requested_features.contains(wgt::Features::EXPERIMENTAL_RAY_TRACING_INVOCATION_REORDER) {
1578            extensions.push(ray_tracing_invocation_reorder::NAME);
1579        }
1580
1581        if requested_features.contains(wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN) {
1582            extensions.push(khr::ray_tracing_position_fetch::NAME)
1583        }
1584
1585        // Require `VK_EXT_conservative_rasterization` if the associated feature was requested
1586        if requested_features.contains(wgt::Features::CONSERVATIVE_RASTERIZATION) {
1587            extensions.push(ext::conservative_rasterization::NAME);
1588        }
1589
1590        // Require `VK_KHR_portability_subset` on macOS/iOS
1591        #[cfg(target_vendor = "apple")]
1592        extensions.push(khr::portability_subset::NAME);
1593
1594        // Require `VK_EXT_texture_compression_astc_hdr` if the associated feature was requested
1595        if requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_ASTC_HDR) {
1596            extensions.push(ext::texture_compression_astc_hdr::NAME);
1597        }
1598
1599        // Require `VK_KHR_shader_atomic_int64` if the associated feature was requested
1600        if requested_features.intersects(
1601            wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX,
1602        ) {
1603            extensions.push(khr::shader_atomic_int64::NAME);
1604        }
1605
1606        // Require `VK_EXT_shader_image_atomic_int64` if the associated feature was requested
1607        if requested_features.intersects(wgt::Features::TEXTURE_INT64_ATOMIC) {
1608            extensions.push(ext::shader_image_atomic_int64::NAME);
1609        }
1610
1611        // Require `VK_EXT_shader_atomic_float` if the associated feature was requested
1612        if requested_features.contains(wgt::Features::SHADER_FLOAT32_ATOMIC) {
1613            extensions.push(ext::shader_atomic_float::NAME);
1614        }
1615
1616        if requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER) {
1617            extensions.push(ext::mesh_shader::NAME);
1618        }
1619
1620        // Require `VK_KHR_fragment_shader_barycentric` if an associated feature was requested
1621        // Vulkan bundles both barycentrics and per-vertex attributes under the same feature.
1622        if requested_features
1623            .intersects(wgt::Features::SHADER_BARYCENTRICS | wgt::Features::SHADER_PER_VERTEX)
1624        {
1625            extensions.push(khr::fragment_shader_barycentric::NAME);
1626        }
1627
1628        // Require `VK_KHR_cooperative_matrix` if the associated feature was requested
1629        if requested_features.contains(wgt::Features::EXPERIMENTAL_COOPERATIVE_MATRIX) {
1630            extensions.push(khr::cooperative_matrix::NAME);
1631        }
1632
1633        extensions
1634    }
1635
1636    fn to_wgpu_limits(&self) -> wgt::Limits {
1637        let limits = &self.properties.limits;
1638
1639        // Default is only implemented for tuples up to a certain size.
1640        let (
1641            mut max_task_workgroup_total_count,
1642            mut max_task_workgroups_per_dimension,
1643            mut max_mesh_workgroup_total_count,
1644            mut max_mesh_workgroups_per_dimension,
1645        ) = Default::default();
1646        let (
1647            mut max_task_invocations_per_workgroup,
1648            mut max_task_invocations_per_dimension,
1649            mut max_mesh_invocations_per_workgroup,
1650            mut max_mesh_invocations_per_dimension,
1651            mut max_task_payload_size,
1652            mut max_mesh_output_vertices,
1653            mut max_mesh_output_primitives,
1654            mut max_mesh_output_layers,
1655            mut max_mesh_multiview_view_count,
1656        ) = Default::default();
1657        if let Some(m) = self.mesh_shader {
1658            max_task_workgroup_total_count = m.max_task_work_group_total_count;
1659            max_task_workgroups_per_dimension =
1660                m.max_task_work_group_count.into_iter().min().unwrap();
1661            max_mesh_workgroup_total_count = m.max_mesh_work_group_total_count;
1662            max_mesh_workgroups_per_dimension =
1663                m.max_mesh_work_group_count.into_iter().min().unwrap();
1664            max_task_invocations_per_workgroup = m.max_task_work_group_invocations;
1665            max_task_invocations_per_dimension =
1666                m.max_task_work_group_size.into_iter().min().unwrap();
1667            max_mesh_invocations_per_workgroup = m.max_mesh_work_group_invocations;
1668            max_mesh_invocations_per_dimension =
1669                m.max_mesh_work_group_size.into_iter().min().unwrap();
1670            max_task_payload_size = m.max_task_payload_size;
1671            max_mesh_output_vertices = m.max_mesh_output_vertices;
1672            max_mesh_output_primitives = m.max_mesh_output_primitives;
1673            max_mesh_output_layers = m.max_mesh_output_layers;
1674            max_mesh_multiview_view_count = m.max_mesh_multiview_view_count;
1675        }
1676
1677        let max_memory_allocation_size = self
1678            .maintenance_3
1679            .map(|maintenance_3| maintenance_3.max_memory_allocation_size)
1680            .unwrap_or(u64::MAX);
1681        let max_buffer_size = self
1682            .maintenance_4
1683            .map(|maintenance_4| maintenance_4.max_buffer_size)
1684            .unwrap_or(u64::MAX);
1685        let max_buffer_size = max_buffer_size.min(max_memory_allocation_size);
1686
1687        // Prevent very large buffers on mesa and most android devices, and in all cases
1688        // don't risk confusing JS by exceeding the range of a double.
1689        let is_nvidia = self.properties.vendor_id == crate::auxil::db::nvidia::VENDOR;
1690        let max_buffer_size_cap =
1691            if (cfg!(target_os = "linux") || cfg!(target_os = "android")) && !is_nvidia {
1692                i32::MAX as u64
1693            } else {
1694                1u64 << 52
1695            };
1696
1697        let max_buffer_size = max_buffer_size.min(max_buffer_size_cap);
1698
1699        let mut max_binding_array_elements = 0;
1700        let mut max_sampler_binding_array_elements = 0;
1701        if let Some(ref descriptor_indexing) = self.descriptor_indexing {
1702            max_binding_array_elements = descriptor_indexing
1703                .max_descriptor_set_update_after_bind_sampled_images
1704                .min(descriptor_indexing.max_descriptor_set_update_after_bind_storage_images)
1705                .min(descriptor_indexing.max_descriptor_set_update_after_bind_storage_buffers)
1706                .min(descriptor_indexing.max_per_stage_descriptor_update_after_bind_sampled_images)
1707                .min(descriptor_indexing.max_per_stage_descriptor_update_after_bind_storage_images)
1708                .min(
1709                    descriptor_indexing.max_per_stage_descriptor_update_after_bind_storage_buffers,
1710                );
1711
1712            max_sampler_binding_array_elements = descriptor_indexing
1713                .max_descriptor_set_update_after_bind_samplers
1714                .min(descriptor_indexing.max_per_stage_descriptor_update_after_bind_samplers);
1715        }
1716
1717        const MAX_SHADER_STAGES_PER_PIPELINE: u32 = 2;
1718
1719        // When summed, the 3 limits below must be under Vulkan's maxFragmentCombinedOutputResources.
1720        // https://gpuweb.github.io/gpuweb/correspondence/#vulkan-maxFragmentCombinedOutputResources
1721        //
1722        // - maxStorageTexturesPerShaderStage, WebGPU default: 4
1723        // - maxStorageBuffersPerShaderStage, WebGPU default: 8
1724        // - maxColorAttachments, WebGPU default: 8
1725        //
1726        // However, maxFragmentCombinedOutputResources should be ignored on
1727        // intel/nvidia/amd/imgtec since it's not reported correctly.
1728        //
1729        // https://github.com/gpuweb/gpuweb/issues/3631#issuecomment-1498747606
1730        // https://github.com/gpuweb/gpuweb/issues/4018
1731        let mut max_storage_textures_per_shader_stage = limits
1732            .max_per_stage_descriptor_storage_images
1733            .min(limits.max_descriptor_set_storage_images / MAX_SHADER_STAGES_PER_PIPELINE);
1734        let mut max_storage_buffers_per_shader_stage = limits
1735            .max_per_stage_descriptor_storage_buffers
1736            .min(limits.max_descriptor_set_storage_buffers / MAX_SHADER_STAGES_PER_PIPELINE);
1737        let mut max_color_attachments = limits
1738            .max_color_attachments
1739            .min(limits.max_fragment_output_attachments);
1740
1741        let ignore_max_fragment_combined_output_resources_by_device = [
1742            crate::auxil::db::intel::VENDOR,
1743            crate::auxil::db::nvidia::VENDOR,
1744            crate::auxil::db::amd::VENDOR,
1745            crate::auxil::db::imgtec::VENDOR,
1746        ]
1747        .contains(&self.properties.vendor_id);
1748        let ignore_max_fragment_combined_output_resources_by_driver =
1749            self.is_driver(vk::DriverId::MESA_AGXV);
1750        let ignore_max_fragment_combined_output_resources =
1751            ignore_max_fragment_combined_output_resources_by_device
1752                || ignore_max_fragment_combined_output_resources_by_driver;
1753
1754        if !ignore_max_fragment_combined_output_resources {
1755            crate::auxil::cap_limits_to_be_under_the_sum_limit(
1756                [
1757                    &mut max_storage_textures_per_shader_stage,
1758                    &mut max_storage_buffers_per_shader_stage,
1759                    &mut max_color_attachments,
1760                ],
1761                limits.max_fragment_combined_output_resources,
1762            );
1763        }
1764
1765        // When summed, the 5 limits below must be under Vulkan's maxPerStageResources.
1766        //
1767        // - maxUniformBuffersPerShaderStage, WebGPU default: 12
1768        // - maxSampledTexturesPerShaderStage, WebGPU default: 16
1769        // - maxStorageTexturesPerShaderStage, WebGPU default: 4
1770        // - maxStorageBuffersPerShaderStage, WebGPU default: 8
1771        // - maxColorAttachments, WebGPU default: 8
1772        //
1773        // Note: Vulkan's texel buffers and input attachments also count towards
1774        // maxPerStageResources but we don't make use of them.
1775        let mut max_sampled_textures_per_shader_stage = limits
1776            .max_per_stage_descriptor_sampled_images
1777            .min(limits.max_descriptor_set_sampled_images / MAX_SHADER_STAGES_PER_PIPELINE);
1778        let mut max_uniform_buffers_per_shader_stage = limits
1779            .max_per_stage_descriptor_uniform_buffers
1780            .min(limits.max_descriptor_set_uniform_buffers / MAX_SHADER_STAGES_PER_PIPELINE);
1781
1782        crate::auxil::cap_limits_to_be_under_the_sum_limit(
1783            [
1784                &mut max_sampled_textures_per_shader_stage,
1785                &mut max_uniform_buffers_per_shader_stage,
1786                &mut max_storage_textures_per_shader_stage,
1787                &mut max_storage_buffers_per_shader_stage,
1788                &mut max_color_attachments,
1789            ],
1790            limits.max_per_stage_resources,
1791        );
1792
1793        // Acceleration structure limits
1794        let mut max_blas_geometry_count = 0;
1795        let mut max_blas_primitive_count = 0;
1796        let mut max_tlas_instance_count = 0;
1797        let mut max_acceleration_structures_per_shader_stage = 0;
1798        if let Some(properties) = self.acceleration_structure {
1799            max_blas_geometry_count = properties.max_geometry_count as u32;
1800            max_blas_primitive_count = properties.max_primitive_count as u32;
1801            max_tlas_instance_count = properties.max_instance_count as u32;
1802            max_acceleration_structures_per_shader_stage = properties
1803                .max_per_stage_descriptor_acceleration_structures
1804                .min(
1805                    properties.max_descriptor_set_acceleration_structures
1806                        / MAX_SHADER_STAGES_PER_PIPELINE,
1807                );
1808        }
1809
1810        // When summed, the 6 limits below must be under Vulkan's
1811        // maxPerSetDescriptors / MAX_SHADER_STAGES_PER_PIPELINE.
1812        //
1813        // - maxUniformBuffersPerShaderStage, WebGPU default: 12
1814        // - maxSampledTexturesPerShaderStage, WebGPU default: 16
1815        // - maxStorageTexturesPerShaderStage, WebGPU default: 4
1816        // - maxStorageBuffersPerShaderStage, WebGPU default: 8
1817        // - maxSamplersPerShaderStage, WebGPU default: 16
1818        // - maxAccelerationStructuresPerShaderStage, Native only
1819        //
1820        // Note: All Vulkan's descriptor types count towards maxPerSetDescriptors but
1821        // we don't use all of them.
1822        // See https://registry.khronos.org/vulkan/specs/latest/html/vkspec.html#interfaces-resources-limits
1823        let max_per_set_descriptors = self
1824            .maintenance_3
1825            .map(|maintenance_3| maintenance_3.max_per_set_descriptors)
1826            // The lowest value seen in reports is 312, use 256 as a safe default.
1827            // https://vulkan.gpuinfo.org/displayextensionproperty.php?extensionname=VK_KHR_maintenance3&extensionproperty=maxPerSetDescriptors&platform=all
1828            // https://vulkan.gpuinfo.org/displaycoreproperty.php?core=1.1&name=maxPerSetDescriptors&platform=all
1829            .unwrap_or(256);
1830
1831        let mut max_samplers_per_shader_stage = limits
1832            .max_per_stage_descriptor_samplers
1833            .min(limits.max_descriptor_set_samplers / MAX_SHADER_STAGES_PER_PIPELINE);
1834
1835        crate::auxil::cap_limits_to_be_under_the_sum_limit(
1836            [
1837                &mut max_sampled_textures_per_shader_stage,
1838                &mut max_uniform_buffers_per_shader_stage,
1839                &mut max_storage_textures_per_shader_stage,
1840                &mut max_storage_buffers_per_shader_stage,
1841                &mut max_samplers_per_shader_stage,
1842                &mut max_acceleration_structures_per_shader_stage,
1843            ],
1844            max_per_set_descriptors / MAX_SHADER_STAGES_PER_PIPELINE,
1845        );
1846
1847        // Use max(default, maxPerSetDescriptors) since the spec requires this
1848        // limit to be at least 1000. This is ok because we already lowered
1849        // all the other relevant per stage limits so their sum is lower
1850        // than maxPerSetDescriptors.
1851        let max_bindings_per_bind_group = 1000.max(max_per_set_descriptors);
1852
1853        // TODO: programmatically determine this, if possible. It's unclear whether we can
1854        // as of https://github.com/gpuweb/gpuweb/issues/2965#issuecomment-1361315447.
1855        //
1856        // In theory some tilers may not support this much. We can't tell however, and
1857        // the driver will throw a DEVICE_REMOVED if it goes too high in usage. This is fine.
1858        let max_color_attachment_bytes_per_sample =
1859            max_color_attachments * wgt::TextureFormat::MAX_TARGET_PIXEL_BYTE_COST;
1860
1861        let mut max_ray_dispatch_count = 0;
1862        let mut max_ray_recursion_depth = 0;
1863
1864        if let Some(properties) = self.ray_tracing_pipeline {
1865            max_ray_dispatch_count = properties.max_ray_dispatch_invocation_count;
1866            max_ray_recursion_depth = properties.max_ray_recursion_depth;
1867        }
1868
1869        let max_multiview_view_count = self
1870            .multiview
1871            .map(|a| a.max_multiview_view_count.min(32))
1872            .unwrap_or(0);
1873
1874        crate::auxil::adjust_raw_limits(wgt::Limits {
1875            //
1876            // WebGPU LIMITS:
1877            // Based on https://gpuweb.github.io/gpuweb/correspondence/#limits
1878            //
1879            max_texture_dimension_1d: limits.max_image_dimension1_d,
1880            max_texture_dimension_2d: limits
1881                .max_image_dimension2_d
1882                .min(limits.max_image_dimension_cube)
1883                .min(limits.max_framebuffer_width)
1884                .min(limits.max_framebuffer_height),
1885            max_texture_dimension_3d: limits.max_image_dimension3_d,
1886            max_texture_array_layers: limits.max_image_array_layers,
1887            max_bind_groups: limits.max_bound_descriptor_sets,
1888            // No limit.
1889            max_bind_groups_plus_vertex_buffers: u32::MAX,
1890            max_bindings_per_bind_group,
1891            max_dynamic_uniform_buffers_per_pipeline_layout: limits
1892                .max_descriptor_set_uniform_buffers_dynamic,
1893            max_dynamic_storage_buffers_per_pipeline_layout: limits
1894                .max_descriptor_set_storage_buffers_dynamic,
1895            max_samplers_per_shader_stage,
1896            max_sampled_textures_per_shader_stage,
1897            max_storage_buffers_per_shader_stage,
1898            max_storage_buffers_in_vertex_stage: 0,
1899            max_storage_buffers_in_fragment_stage: 0,
1900            max_storage_textures_per_shader_stage,
1901            max_storage_textures_in_vertex_stage: 0,
1902            max_storage_textures_in_fragment_stage: 0,
1903            max_uniform_buffers_per_shader_stage,
1904            max_vertex_buffers: limits.max_vertex_input_bindings,
1905            max_buffer_size,
1906            max_uniform_buffer_binding_size: limits
1907                .max_uniform_buffer_range
1908                .min(crate::auxil::MAX_I32_BINDING_SIZE)
1909                .into(),
1910            max_storage_buffer_binding_size: limits
1911                .max_storage_buffer_range
1912                .min(crate::auxil::MAX_I32_BINDING_SIZE)
1913                .into(),
1914            min_uniform_buffer_offset_alignment: limits.min_uniform_buffer_offset_alignment as u32,
1915            min_storage_buffer_offset_alignment: limits.min_storage_buffer_offset_alignment as u32,
1916            max_vertex_attributes: limits.max_vertex_input_attributes,
1917            max_vertex_buffer_array_stride: limits.max_vertex_input_binding_stride,
1918            max_inter_stage_shader_variables: limits
1919                .max_vertex_output_components
1920                .min(limits.max_fragment_input_components)
1921                / 4
1922                - 1, // -1 for position
1923            max_color_attachments,
1924            max_color_attachment_bytes_per_sample,
1925            max_compute_workgroup_storage_size: limits.max_compute_shared_memory_size,
1926            max_compute_invocations_per_workgroup: limits.max_compute_work_group_invocations,
1927            max_compute_workgroup_size_x: limits.max_compute_work_group_size[0],
1928            max_compute_workgroup_size_y: limits.max_compute_work_group_size[1],
1929            max_compute_workgroup_size_z: limits.max_compute_work_group_size[2],
1930            max_compute_workgroups_per_dimension: limits.max_compute_work_group_count[0]
1931                .min(limits.max_compute_work_group_count[1])
1932                .min(limits.max_compute_work_group_count[2]),
1933            max_immediate_size: limits.max_push_constants_size,
1934            //
1935            // NATIVE (Non-WebGPU) LIMITS:
1936            //
1937            max_non_sampler_bindings: u32::MAX,
1938
1939            max_binding_array_elements_per_shader_stage: max_binding_array_elements,
1940            max_binding_array_sampler_elements_per_shader_stage: max_sampler_binding_array_elements,
1941            max_binding_array_acceleration_structure_elements_per_shader_stage: if self
1942                .descriptor_indexing
1943                .is_some()
1944            {
1945                max_acceleration_structures_per_shader_stage
1946            } else {
1947                0
1948            },
1949
1950            max_task_workgroup_total_count,
1951            max_task_workgroups_per_dimension,
1952            max_mesh_workgroup_total_count,
1953            max_mesh_workgroups_per_dimension,
1954
1955            max_task_invocations_per_workgroup,
1956            max_task_invocations_per_dimension,
1957
1958            max_mesh_invocations_per_workgroup,
1959            max_mesh_invocations_per_dimension,
1960
1961            max_task_payload_size,
1962            max_mesh_output_vertices,
1963            max_mesh_output_primitives,
1964            max_mesh_output_layers,
1965            max_mesh_multiview_view_count,
1966
1967            max_blas_primitive_count,
1968            max_blas_geometry_count,
1969            max_tlas_instance_count,
1970            max_acceleration_structures_per_shader_stage,
1971            max_buffers_and_acceleration_structures_per_shader_stage: u32::MAX,
1972
1973            max_multiview_view_count,
1974
1975            max_ray_dispatch_count,
1976            max_ray_recursion_depth,
1977        })
1978    }
1979
1980    /// Return a `wgpu_hal::Alignments` structure describing this adapter.
1981    ///
1982    /// The `using_robustness2` argument says how this adapter will implement
1983    /// `wgpu_hal`'s guarantee that shaders can only read the [accessible
1984    /// region][ar] of bindgroup's buffer bindings:
1985    ///
1986    /// - If this adapter will depend on `VK_EXT_robustness2`'s
1987    ///   `robustBufferAccess2` feature to apply bounds checks to shader buffer
1988    ///   access, `using_robustness2` must be `true`.
1989    ///
1990    /// - Otherwise, this adapter must use Naga to inject bounds checks on
1991    ///   buffer accesses, and `using_robustness2` must be `false`.
1992    ///
1993    /// [ar]: ../../struct.BufferBinding.html#accessible-region
1994    fn to_hal_alignments(&self, using_robustness2: bool) -> crate::Alignments {
1995        let limits = &self.properties.limits;
1996        crate::Alignments {
1997            buffer_copy_offset: wgt::BufferSize::new(limits.optimal_buffer_copy_offset_alignment)
1998                .unwrap(),
1999            buffer_copy_pitch: wgt::BufferSize::new(limits.optimal_buffer_copy_row_pitch_alignment)
2000                .unwrap(),
2001            uniform_bounds_check_alignment: {
2002                let alignment = if using_robustness2 {
2003                    self.robustness2
2004                        .unwrap() // if we're using it, we should have its properties
2005                        .robust_uniform_buffer_access_size_alignment
2006                } else {
2007                    // If the `robustness2` properties are unavailable, then `robustness2` is not available either Naga-injected bounds checks are precise.
2008                    1
2009                };
2010                wgt::BufferSize::new(alignment).unwrap()
2011            },
2012            raw_tlas_instance_size: 64,
2013            ray_tracing_scratch_buffer_alignment: self.acceleration_structure.map_or(
2014                0,
2015                |acceleration_structure| {
2016                    acceleration_structure.min_acceleration_structure_scratch_offset_alignment
2017                },
2018            ),
2019            ray_tracing_pipeline_group_data_size: self
2020                .ray_tracing_pipeline
2021                .map_or(0, |ray_tracing_pipeline| {
2022                    ray_tracing_pipeline.shader_group_handle_size
2023                }),
2024            ray_tracing_pipeline_group_data_alignment: self
2025                .ray_tracing_pipeline
2026                .map_or(0, |ray_tracing_pipeline| {
2027                    ray_tracing_pipeline.shader_group_handle_alignment
2028                }),
2029            ray_tracing_pipeline_data_offset_alignment: self
2030                .ray_tracing_pipeline
2031                .map_or(0, |ray_tracing_pipeline| {
2032                    ray_tracing_pipeline.shader_group_base_alignment
2033                }),
2034        }
2035    }
2036}
2037
2038impl super::InstanceShared {
2039    fn inspect(
2040        &self,
2041        phd: vk::PhysicalDevice,
2042    ) -> (PhysicalDeviceProperties, PhysicalDeviceFeatures) {
2043        let capabilities = {
2044            let mut capabilities = PhysicalDeviceProperties::default();
2045            capabilities.supported_extensions =
2046                unsafe { self.raw.enumerate_device_extension_properties(phd).unwrap() };
2047            capabilities.properties = unsafe { self.raw.get_physical_device_properties(phd) };
2048            capabilities.device_api_version = capabilities.properties.api_version;
2049
2050            let supports_multiview = capabilities.device_api_version >= vk::API_VERSION_1_1
2051                || capabilities.supports_extension(khr::multiview::NAME);
2052
2053            if let Some(ref get_device_properties) = self.get_physical_device_properties {
2054                // Get these now to avoid borrowing conflicts later
2055                let supports_maintenance3 = capabilities.device_api_version >= vk::API_VERSION_1_1
2056                    || capabilities.supports_extension(khr::maintenance3::NAME);
2057                let supports_maintenance4 = capabilities.device_api_version >= vk::API_VERSION_1_3
2058                    || capabilities.supports_extension(khr::maintenance4::NAME);
2059                let supports_maintenance5 = capabilities.device_api_version
2060                    >= vk::make_api_version(0, 1, 4, 0) // TODO: Use `vk::API_VERSION_1_4` after `ash` is updated.
2061                    || capabilities.supports_extension(khr::maintenance5::NAME);
2062                let supports_descriptor_indexing = capabilities.device_api_version
2063                    >= vk::API_VERSION_1_2
2064                    || capabilities.supports_extension(ext::descriptor_indexing::NAME);
2065                let supports_driver_properties = capabilities.device_api_version
2066                    >= vk::API_VERSION_1_2
2067                    || capabilities.supports_extension(khr::driver_properties::NAME);
2068                let supports_subgroup_size_control = capabilities.device_api_version
2069                    >= vk::API_VERSION_1_3
2070                    || capabilities.supports_extension(ext::subgroup_size_control::NAME);
2071                let supports_robustness2 = capabilities.supports_extension(ext::robustness2::NAME);
2072                let supports_pci_bus_info =
2073                    capabilities.supports_extension(ext::pci_bus_info::NAME);
2074
2075                let supports_acceleration_structure =
2076                    capabilities.supports_extension(khr::acceleration_structure::NAME);
2077
2078                let supports_ray_tracing_pipeline =
2079                    capabilities.supports_extension(khr::ray_tracing_pipeline::NAME);
2080
2081                let supports_ray_tracing_invocation_reorder =
2082                    capabilities.supports_extension(ray_tracing_invocation_reorder::NAME);
2083
2084                let supports_mesh_shader = capabilities.supports_extension(ext::mesh_shader::NAME);
2085
2086                let mut properties2 = vk::PhysicalDeviceProperties2KHR::default();
2087                if supports_maintenance3 {
2088                    let next = capabilities
2089                        .maintenance_3
2090                        .insert(vk::PhysicalDeviceMaintenance3Properties::default());
2091                    properties2 = properties2.push_next(next);
2092                }
2093
2094                if supports_maintenance4 {
2095                    let next = capabilities
2096                        .maintenance_4
2097                        .insert(vk::PhysicalDeviceMaintenance4Properties::default());
2098                    properties2 = properties2.push_next(next);
2099                }
2100
2101                if supports_maintenance5 {
2102                    let next = capabilities
2103                        .maintenance_5
2104                        .insert(vk::PhysicalDeviceMaintenance5PropertiesKHR::default());
2105                    properties2 = properties2.push_next(next);
2106                }
2107
2108                if supports_descriptor_indexing {
2109                    let next = capabilities
2110                        .descriptor_indexing
2111                        .insert(vk::PhysicalDeviceDescriptorIndexingPropertiesEXT::default());
2112                    properties2 = properties2.push_next(next);
2113                }
2114
2115                if supports_acceleration_structure {
2116                    let next = capabilities
2117                        .acceleration_structure
2118                        .insert(vk::PhysicalDeviceAccelerationStructurePropertiesKHR::default());
2119                    properties2 = properties2.push_next(next);
2120                }
2121
2122                if supports_ray_tracing_pipeline {
2123                    let next = capabilities
2124                        .ray_tracing_pipeline
2125                        .insert(vk::PhysicalDeviceRayTracingPipelinePropertiesKHR::default());
2126                    properties2 = properties2.push_next(next);
2127                }
2128
2129                if supports_ray_tracing_invocation_reorder {
2130                    let next = capabilities
2131                        .ray_tracing_invocation_reorder
2132                        .insert(ray_tracing_invocation_reorder::PropertiesEXT::default());
2133                    properties2 = properties2.push_next(next);
2134                }
2135
2136                if supports_driver_properties {
2137                    let next = capabilities
2138                        .driver
2139                        .insert(vk::PhysicalDeviceDriverPropertiesKHR::default());
2140                    properties2 = properties2.push_next(next);
2141                }
2142
2143                if capabilities.device_api_version >= vk::API_VERSION_1_1 {
2144                    let next = capabilities
2145                        .subgroup
2146                        .insert(vk::PhysicalDeviceSubgroupProperties::default());
2147                    properties2 = properties2.push_next(next);
2148                }
2149
2150                if supports_subgroup_size_control {
2151                    let next = capabilities
2152                        .subgroup_size_control
2153                        .insert(vk::PhysicalDeviceSubgroupSizeControlProperties::default());
2154                    properties2 = properties2.push_next(next);
2155                }
2156
2157                if supports_robustness2 {
2158                    let next = capabilities
2159                        .robustness2
2160                        .insert(vk::PhysicalDeviceRobustness2PropertiesEXT::default());
2161                    properties2 = properties2.push_next(next);
2162                }
2163
2164                if supports_pci_bus_info {
2165                    let next = capabilities
2166                        .pci_bus_info
2167                        .insert(vk::PhysicalDevicePCIBusInfoPropertiesEXT::default());
2168                    properties2 = properties2.push_next(next);
2169                }
2170
2171                if supports_mesh_shader {
2172                    let next = capabilities
2173                        .mesh_shader
2174                        .insert(vk::PhysicalDeviceMeshShaderPropertiesEXT::default());
2175                    properties2 = properties2.push_next(next);
2176                }
2177
2178                if supports_multiview {
2179                    let next = capabilities
2180                        .multiview
2181                        .insert(vk::PhysicalDeviceMultiviewProperties::default());
2182                    properties2 = properties2.push_next(next);
2183                }
2184
2185                unsafe {
2186                    get_device_properties.get_physical_device_properties2(phd, &mut properties2)
2187                };
2188
2189                // Query cooperative matrix properties
2190                if capabilities.supports_extension(khr::cooperative_matrix::NAME) {
2191                    let coop_matrix =
2192                        khr::cooperative_matrix::Instance::new(&self.entry, &self.raw);
2193                    capabilities.cooperative_matrix_properties =
2194                        query_cooperative_matrix_properties(&coop_matrix, phd);
2195                }
2196
2197                // Suppress some capabilities to avoid known problems
2198                if is_intel_igpu_outdated_for_robustness2(&capabilities) {
2199                    capabilities
2200                        .supported_extensions
2201                        .retain(|&x| x.extension_name_as_c_str() != Ok(ext::robustness2::NAME));
2202                    capabilities.robustness2 = None;
2203                }
2204
2205                // Due to https://gitlab.freedesktop.org/mesa/mesa/-/work_items/15725
2206                // TODO(https://github.com/gfx-rs/wgpu/issues/9742): enable on
2207                // fixed driver versions, when available
2208                if capabilities.is_driver(vk::DriverId::MESA_RADV) {
2209                    capabilities
2210                        .supported_extensions
2211                        .retain(|&x| x.extension_name_as_c_str() != Ok(ext::memory_budget::NAME));
2212                }
2213            };
2214            capabilities
2215        };
2216
2217        let mut features = PhysicalDeviceFeatures::default();
2218        features.core = if let Some(ref get_device_properties) = self.get_physical_device_properties
2219        {
2220            let core = vk::PhysicalDeviceFeatures::default();
2221            let mut features2 = vk::PhysicalDeviceFeatures2KHR::default().features(core);
2222
2223            // `VK_KHR_multiview` is promoted to 1.1
2224            if capabilities.device_api_version >= vk::API_VERSION_1_1
2225                || capabilities.supports_extension(khr::multiview::NAME)
2226            {
2227                let next = features
2228                    .multiview
2229                    .insert(vk::PhysicalDeviceMultiviewFeatures::default());
2230                features2 = features2.push_next(next);
2231            }
2232
2233            // `VK_KHR_sampler_ycbcr_conversion` is promoted to 1.1
2234            if capabilities.device_api_version >= vk::API_VERSION_1_1
2235                || capabilities.supports_extension(khr::sampler_ycbcr_conversion::NAME)
2236            {
2237                let next = features
2238                    .sampler_ycbcr_conversion
2239                    .insert(vk::PhysicalDeviceSamplerYcbcrConversionFeatures::default());
2240                features2 = features2.push_next(next);
2241            }
2242
2243            if capabilities.supports_extension(ext::descriptor_indexing::NAME) {
2244                let next = features
2245                    .descriptor_indexing
2246                    .insert(vk::PhysicalDeviceDescriptorIndexingFeaturesEXT::default());
2247                features2 = features2.push_next(next);
2248            }
2249
2250            // `VK_KHR_timeline_semaphore` is promoted to 1.2, but has no
2251            // changes, so we can keep using the extension unconditionally.
2252            if capabilities.supports_extension(khr::timeline_semaphore::NAME) {
2253                let next = features
2254                    .timeline_semaphore
2255                    .insert(vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR::default());
2256                features2 = features2.push_next(next);
2257            }
2258
2259            // `VK_KHR_shader_atomic_int64` is promoted to 1.2, but has no
2260            // changes, so we can keep using the extension unconditionally.
2261            if capabilities.device_api_version >= vk::API_VERSION_1_2
2262                || capabilities.supports_extension(khr::shader_atomic_int64::NAME)
2263            {
2264                let next = features
2265                    .shader_atomic_int64
2266                    .insert(vk::PhysicalDeviceShaderAtomicInt64Features::default());
2267                features2 = features2.push_next(next);
2268            }
2269
2270            if capabilities.supports_extension(ext::shader_image_atomic_int64::NAME) {
2271                let next = features
2272                    .shader_image_atomic_int64
2273                    .insert(vk::PhysicalDeviceShaderImageAtomicInt64FeaturesEXT::default());
2274                features2 = features2.push_next(next);
2275            }
2276            if capabilities.supports_extension(ext::shader_atomic_float::NAME) {
2277                let next = features
2278                    .shader_atomic_float
2279                    .insert(vk::PhysicalDeviceShaderAtomicFloatFeaturesEXT::default());
2280                features2 = features2.push_next(next);
2281            }
2282            if capabilities.supports_extension(ext::image_robustness::NAME) {
2283                let next = features
2284                    .image_robustness
2285                    .insert(vk::PhysicalDeviceImageRobustnessFeaturesEXT::default());
2286                features2 = features2.push_next(next);
2287            }
2288            if capabilities.supports_extension(ext::robustness2::NAME) {
2289                let next = features
2290                    .robustness2
2291                    .insert(vk::PhysicalDeviceRobustness2FeaturesEXT::default());
2292                features2 = features2.push_next(next);
2293            }
2294            if capabilities.supports_extension(ext::texture_compression_astc_hdr::NAME) {
2295                let next = features
2296                    .astc_hdr
2297                    .insert(vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT::default());
2298                features2 = features2.push_next(next);
2299            }
2300
2301            // `VK_KHR_shader_float16_int8` is promoted to 1.2
2302            if capabilities.device_api_version >= vk::API_VERSION_1_2
2303                || capabilities.supports_extension(khr::shader_float16_int8::NAME)
2304            {
2305                let next = features
2306                    .shader_float16_int8
2307                    .insert(vk::PhysicalDeviceShaderFloat16Int8FeaturesKHR::default());
2308                features2 = features2.push_next(next);
2309            }
2310
2311            if capabilities.supports_extension(khr::_16bit_storage::NAME) {
2312                let next = features
2313                    ._16bit_storage
2314                    .insert(vk::PhysicalDevice16BitStorageFeaturesKHR::default());
2315                features2 = features2.push_next(next);
2316            }
2317            if capabilities.supports_extension(khr::acceleration_structure::NAME) {
2318                let next = features
2319                    .acceleration_structure
2320                    .insert(vk::PhysicalDeviceAccelerationStructureFeaturesKHR::default());
2321                features2 = features2.push_next(next);
2322            }
2323
2324            if capabilities.supports_extension(khr::ray_tracing_position_fetch::NAME) {
2325                let next = features
2326                    .position_fetch
2327                    .insert(vk::PhysicalDeviceRayTracingPositionFetchFeaturesKHR::default());
2328                features2 = features2.push_next(next);
2329            }
2330
2331            if capabilities.supports_extension(ray_tracing_invocation_reorder::NAME) {
2332                let next = features
2333                    .ray_tracing_invocation_reorder
2334                    .insert(ray_tracing_invocation_reorder::FeaturesEXT::default());
2335                features2 = features2.push_next(next);
2336            }
2337
2338            // `VK_KHR_maintenance4` is promoted to 1.3
2339            if capabilities.device_api_version >= vk::API_VERSION_1_3
2340                || capabilities.supports_extension(khr::maintenance4::NAME)
2341            {
2342                let next = features
2343                    .maintenance4
2344                    .insert(vk::PhysicalDeviceMaintenance4Features::default());
2345                features2 = features2.push_next(next);
2346            }
2347
2348            // `VK_KHR_zero_initialize_workgroup_memory` is promoted to 1.3
2349            if capabilities.device_api_version >= vk::API_VERSION_1_3
2350                || capabilities.supports_extension(khr::zero_initialize_workgroup_memory::NAME)
2351            {
2352                let next = features
2353                    .zero_initialize_workgroup_memory
2354                    .insert(vk::PhysicalDeviceZeroInitializeWorkgroupMemoryFeatures::default());
2355                features2 = features2.push_next(next);
2356            }
2357
2358            // `VK_EXT_subgroup_size_control` is promoted to 1.3
2359            if capabilities.device_api_version >= vk::API_VERSION_1_3
2360                || capabilities.supports_extension(ext::subgroup_size_control::NAME)
2361            {
2362                let next = features
2363                    .subgroup_size_control
2364                    .insert(vk::PhysicalDeviceSubgroupSizeControlFeatures::default());
2365                features2 = features2.push_next(next);
2366            }
2367
2368            if capabilities.supports_extension(ext::mesh_shader::NAME) {
2369                let next = features
2370                    .mesh_shader
2371                    .insert(vk::PhysicalDeviceMeshShaderFeaturesEXT::default());
2372                features2 = features2.push_next(next);
2373            }
2374
2375            // `VK_KHR_shader_integer_dot_product` is promoted to 1.3
2376            if capabilities.device_api_version >= vk::API_VERSION_1_3
2377                || capabilities.supports_extension(khr::shader_integer_dot_product::NAME)
2378            {
2379                let next = features
2380                    .shader_integer_dot_product
2381                    .insert(vk::PhysicalDeviceShaderIntegerDotProductFeatures::default());
2382                features2 = features2.push_next(next);
2383            }
2384
2385            if capabilities.supports_extension(khr::fragment_shader_barycentric::NAME) {
2386                let next = features
2387                    .shader_barycentrics
2388                    .insert(vk::PhysicalDeviceFragmentShaderBarycentricFeaturesKHR::default());
2389                features2 = features2.push_next(next);
2390            }
2391
2392            if capabilities.supports_extension(khr::portability_subset::NAME) {
2393                let next = features
2394                    .portability_subset
2395                    .insert(vk::PhysicalDevicePortabilitySubsetFeaturesKHR::default());
2396                features2 = features2.push_next(next);
2397            }
2398
2399            if capabilities.supports_extension(khr::cooperative_matrix::NAME) {
2400                let next = features
2401                    .cooperative_matrix
2402                    .insert(vk::PhysicalDeviceCooperativeMatrixFeaturesKHR::default());
2403                features2 = features2.push_next(next);
2404            }
2405
2406            if capabilities.device_api_version >= vk::API_VERSION_1_2
2407                || capabilities.supports_extension(khr::vulkan_memory_model::NAME)
2408            {
2409                let next = features
2410                    .vulkan_memory_model
2411                    .insert(vk::PhysicalDeviceVulkanMemoryModelFeaturesKHR::default());
2412                features2 = features2.push_next(next);
2413            }
2414
2415            if capabilities.device_api_version >= vk::API_VERSION_1_1 {
2416                let next = features
2417                    .shader_draw_parameters
2418                    .insert(vk::PhysicalDeviceShaderDrawParametersFeatures::default());
2419                features2 = features2.push_next(next);
2420            }
2421
2422            unsafe { get_device_properties.get_physical_device_features2(phd, &mut features2) };
2423            features2.features
2424        } else {
2425            unsafe { self.raw.get_physical_device_features(phd) }
2426        };
2427
2428        (capabilities, features)
2429    }
2430}
2431
2432impl super::Instance {
2433    pub fn expose_adapter(
2434        &self,
2435        phd: vk::PhysicalDevice,
2436    ) -> Option<crate::ExposedAdapter<super::Api>> {
2437        use crate::auxil::db;
2438
2439        let (phd_capabilities, phd_features) = self.shared.inspect(phd);
2440
2441        let mem_properties = {
2442            profiling::scope!("vkGetPhysicalDeviceMemoryProperties");
2443            unsafe { self.shared.raw.get_physical_device_memory_properties(phd) }
2444        };
2445        let memory_types = &mem_properties.memory_types_as_slice();
2446        let supports_lazily_allocated = memory_types.iter().any(|mem| {
2447            mem.property_flags
2448                .contains(vk::MemoryPropertyFlags::LAZILY_ALLOCATED)
2449        });
2450
2451        let device_type = match phd_capabilities.properties.device_type {
2452            vk::PhysicalDeviceType::OTHER => wgt::DeviceType::Other,
2453            vk::PhysicalDeviceType::INTEGRATED_GPU => wgt::DeviceType::IntegratedGpu,
2454            vk::PhysicalDeviceType::DISCRETE_GPU => wgt::DeviceType::DiscreteGpu,
2455            vk::PhysicalDeviceType::VIRTUAL_GPU => wgt::DeviceType::VirtualGpu,
2456            vk::PhysicalDeviceType::CPU => wgt::DeviceType::Cpu,
2457            _ => wgt::DeviceType::Other,
2458        };
2459        let info = wgt::AdapterInfo {
2460            name: {
2461                phd_capabilities
2462                    .properties
2463                    .device_name_as_c_str()
2464                    .ok()
2465                    .and_then(|name| name.to_str().ok())
2466                    .unwrap_or("?")
2467                    .to_owned()
2468            },
2469            vendor: phd_capabilities.properties.vendor_id,
2470            device: phd_capabilities.properties.device_id,
2471            device_pci_bus_id: phd_capabilities
2472                .pci_bus_info
2473                .filter(|info| info.pci_bus != 0 || info.pci_device != 0)
2474                .map(|info| {
2475                    format!(
2476                        "{:04x}:{:02x}:{:02x}.{}",
2477                        info.pci_domain, info.pci_bus, info.pci_device, info.pci_function
2478                    )
2479                })
2480                .unwrap_or_default(),
2481            driver: {
2482                phd_capabilities
2483                    .driver
2484                    .as_ref()
2485                    .and_then(|driver| driver.driver_name_as_c_str().ok())
2486                    .and_then(|name| name.to_str().ok())
2487                    .unwrap_or("?")
2488                    .to_owned()
2489            },
2490            driver_info: {
2491                phd_capabilities
2492                    .driver
2493                    .as_ref()
2494                    .and_then(|driver| driver.driver_info_as_c_str().ok())
2495                    .and_then(|name| name.to_str().ok())
2496                    .unwrap_or("?")
2497                    .to_owned()
2498            },
2499            subgroup_min_size: phd_capabilities
2500                .subgroup_size_control
2501                .map(|subgroup_size| subgroup_size.min_subgroup_size)
2502                .unwrap_or(wgt::MINIMUM_SUBGROUP_MIN_SIZE),
2503            subgroup_max_size: phd_capabilities
2504                .subgroup_size_control
2505                .map(|subgroup_size| subgroup_size.max_subgroup_size)
2506                .unwrap_or(wgt::MAXIMUM_SUBGROUP_MAX_SIZE),
2507            transient_saves_memory: Some(supports_lazily_allocated),
2508            ..wgt::AdapterInfo::new(device_type, wgt::Backend::Vulkan)
2509        };
2510        let mut workarounds = super::Workarounds::empty();
2511        {
2512            // TODO: only enable for particular devices
2513            workarounds |= super::Workarounds::SEPARATE_ENTRY_POINTS;
2514            workarounds.set(
2515                super::Workarounds::EMPTY_RESOLVE_ATTACHMENT_LISTS,
2516                phd_capabilities.properties.vendor_id == db::qualcomm::VENDOR,
2517            );
2518            workarounds.set(
2519                super::Workarounds::FORCE_FILL_BUFFER_WITH_SIZE_GREATER_4096_ALIGNED_OFFSET_16,
2520                phd_capabilities.properties.vendor_id == db::nvidia::VENDOR,
2521            );
2522            workarounds.set(
2523                super::Workarounds::POLYFILL_MESH_TASK_WORKGROUP_ZERO_INIT,
2524                phd_capabilities.is_driver(vk::DriverId::AMD_PROPRIETARY),
2525            );
2526            // Matched by driver ID rather than vendor ID: Mesa's PanVK also reports Arm's
2527            // vendor ID and is not affected.
2528            workarounds.set(
2529                super::Workarounds::DISABLE_TIMELINE_SEMAPHORES,
2530                phd_capabilities.is_driver(vk::DriverId::ARM_PROPRIETARY)
2531                    && arm_driver_leaks_timeline_semaphores(&info.driver_info),
2532            );
2533        };
2534
2535        if let Some(driver) = phd_capabilities.driver {
2536            if driver.conformance_version.major == 0 {
2537                if driver.driver_id == vk::DriverId::MOLTENVK {
2538                    log::debug!("Adapter is not Vulkan compliant, but is MoltenVK, continuing");
2539                } else if self
2540                    .shared
2541                    .flags
2542                    .contains(wgt::InstanceFlags::ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER)
2543                {
2544                    log::debug!("Adapter is not Vulkan compliant: {}", info.name);
2545                } else {
2546                    log::debug!(
2547                        "Adapter is not Vulkan compliant, hiding adapter: {}",
2548                        info.name
2549                    );
2550                    return None;
2551                }
2552            }
2553        }
2554        if phd_capabilities.device_api_version == vk::API_VERSION_1_0
2555            && !phd_capabilities.supports_extension(khr::storage_buffer_storage_class::NAME)
2556        {
2557            log::debug!(
2558                "SPIR-V storage buffer class is not supported, hiding adapter: {}",
2559                info.name
2560            );
2561            return None;
2562        }
2563        if !phd_capabilities.supports_extension(khr::maintenance1::NAME)
2564            && phd_capabilities.device_api_version < vk::API_VERSION_1_1
2565        {
2566            log::debug!(
2567                "VK_KHR_maintenance1 is not supported, hiding adapter: {}",
2568                info.name
2569            );
2570            return None;
2571        }
2572
2573        let queue_families = unsafe {
2574            self.shared
2575                .raw
2576                .get_physical_device_queue_family_properties(phd)
2577        };
2578        let queue_family_properties = queue_families.first()?;
2579        let queue_flags = queue_family_properties.queue_flags;
2580        if !queue_flags.contains(vk::QueueFlags::GRAPHICS) {
2581            log::debug!("The first queue only exposes {queue_flags:?}");
2582            return None;
2583        }
2584
2585        let (available_features, mut downlevel_flags) = phd_features.to_wgpu(
2586            &self.shared.raw,
2587            phd,
2588            &phd_capabilities,
2589            queue_family_properties,
2590        );
2591
2592        downlevel_flags.set(
2593            wgt::DownlevelFlags::TEXTURE_COMPRESSION,
2594            available_features.contains(wgt::Features::TEXTURE_COMPRESSION_BC)
2595                || available_features.contains(
2596                    wgt::Features::TEXTURE_COMPRESSION_ETC2
2597                        | wgt::Features::TEXTURE_COMPRESSION_ASTC,
2598                ),
2599        );
2600
2601        let has_robust_buffer_access2 = phd_features
2602            .robustness2
2603            .as_ref()
2604            .map(|r| r.robust_buffer_access2 == 1)
2605            .unwrap_or_default();
2606
2607        let alignments = phd_capabilities.to_hal_alignments(has_robust_buffer_access2);
2608
2609        let private_caps = super::PrivateCapabilities {
2610            image_view_usage: phd_capabilities.device_api_version >= vk::API_VERSION_1_1
2611                || phd_capabilities.supports_extension(khr::maintenance2::NAME),
2612            // VeriSilicon's proprietary driver, as on NXP's i.MX 8 SoCs, advertises timeline
2613            // semaphores but crashes in `vkQueueSubmit` when wgpu uses them. It reports
2614            // `VK_DRIVER_ID_MESA_RADV` as its driver ID, so only the vendor ID identifies it.
2615            timeline_semaphores: phd_capabilities.properties.vendor_id != db::verisilicon::VENDOR
2616                && !workarounds.contains(super::Workarounds::DISABLE_TIMELINE_SEMAPHORES)
2617                && match phd_features.timeline_semaphore {
2618                    Some(features) => features.timeline_semaphore == vk::TRUE,
2619                    None => phd_features
2620                        .timeline_semaphore
2621                        .is_some_and(|ext| ext.timeline_semaphore != 0),
2622                },
2623            texture_d24: supports_format(
2624                &self.shared.raw,
2625                phd,
2626                vk::Format::X8_D24_UNORM_PACK32,
2627                vk::ImageTiling::OPTIMAL,
2628                depth_stencil_required_flags(),
2629            ),
2630            texture_d24_s8: supports_format(
2631                &self.shared.raw,
2632                phd,
2633                vk::Format::D24_UNORM_S8_UINT,
2634                vk::ImageTiling::OPTIMAL,
2635                depth_stencil_required_flags(),
2636            ),
2637            texture_s8: supports_format(
2638                &self.shared.raw,
2639                phd,
2640                vk::Format::S8_UINT,
2641                vk::ImageTiling::OPTIMAL,
2642                depth_stencil_required_flags(),
2643            ),
2644            multi_draw_indirect: phd_features.core.multi_draw_indirect != 0,
2645            max_draw_indirect_count: phd_capabilities.properties.limits.max_draw_indirect_count,
2646            non_coherent_map_mask: phd_capabilities.properties.limits.non_coherent_atom_size - 1,
2647            can_present: true,
2648            //TODO: make configurable
2649            robust_buffer_access: phd_features.core.robust_buffer_access != 0,
2650            robust_image_access: phd_features
2651                .robustness2
2652                .is_some_and(|f| f.robust_image_access2 != 0)
2653                || phd_features
2654                    .image_robustness
2655                    .is_some_and(|ext| ext.robust_image_access != 0),
2656            robust_buffer_access2: has_robust_buffer_access2,
2657            robust_image_access2: phd_features
2658                .robustness2
2659                .as_ref()
2660                .map(|r| r.robust_image_access2 == 1)
2661                .unwrap_or_default(),
2662            zero_initialize_workgroup_memory: phd_features
2663                .zero_initialize_workgroup_memory
2664                .is_some_and(|ext| ext.shader_zero_initialize_workgroup_memory == vk::TRUE),
2665            image_format_list: phd_capabilities.device_api_version >= vk::API_VERSION_1_2
2666                || phd_capabilities.supports_extension(khr::image_format_list::NAME),
2667            maximum_samplers: phd_capabilities
2668                .properties
2669                .limits
2670                .max_sampler_allocation_count,
2671            shader_integer_dot_product: phd_features
2672                .shader_integer_dot_product
2673                .is_some_and(|ext| ext.shader_integer_dot_product != 0),
2674            shader_int8: phd_features
2675                .shader_float16_int8
2676                .is_some_and(|features| features.shader_int8 != 0),
2677            multiview_instance_index_limit: phd_capabilities
2678                .multiview
2679                .map(|a| a.max_multiview_instance_index)
2680                .unwrap_or(0),
2681            scratch_buffer_alignment: alignments.ray_tracing_scratch_buffer_alignment,
2682            depth_stencil_swizzle_one_support: phd_capabilities
2683                .maintenance_5
2684                .map(|maintenance_5| maintenance_5.depth_stencil_swizzle_one_support == vk::TRUE)
2685                .unwrap_or(false),
2686            ray_tracing_pipeline_group_data_size: alignments.ray_tracing_pipeline_group_data_size,
2687            shader_binding_table_alignment: alignments.ray_tracing_pipeline_data_offset_alignment,
2688            store_op_none: phd_capabilities.device_api_version >= vk::API_VERSION_1_3
2689                || (phd_capabilities.device_api_version >= vk::API_VERSION_1_2
2690                    && phd_capabilities.supports_extension(khr::dynamic_rendering::NAME))
2691                || phd_capabilities.supports_extension(khr::load_store_op_none::NAME)
2692                || phd_capabilities.supports_extension(ash::qcom::render_pass_store_ops::NAME)
2693                || phd_capabilities.supports_extension(ext::load_store_op_none::NAME),
2694            incremental_present: phd_capabilities
2695                .supports_extension(khr::incremental_present::NAME),
2696        };
2697        let capabilities = crate::Capabilities {
2698            limits: phd_capabilities.to_wgpu_limits(),
2699            alignments,
2700            downlevel: wgt::DownlevelCapabilities {
2701                flags: downlevel_flags,
2702                limits: wgt::DownlevelLimits {},
2703                shader_model: wgt::ShaderModel::Sm5, //TODO?
2704            },
2705            cooperative_matrix_properties: phd_capabilities.cooperative_matrix_properties.clone(),
2706            ray_tracing_invocation_reorder_mode: match phd_capabilities
2707                .ray_tracing_invocation_reorder
2708            {
2709                Some(properties)
2710                    if available_features
2711                        .contains(wgt::Features::EXPERIMENTAL_RAY_TRACING_INVOCATION_REORDER) =>
2712                {
2713                    properties.mode()
2714                }
2715                _ => wgt::RayTracingInvocationReorderMode::None,
2716            },
2717        };
2718
2719        let adapter = super::Adapter {
2720            raw: phd,
2721            instance: Arc::clone(&self.shared),
2722            //queue_families,
2723            known_memory_flags: vk::MemoryPropertyFlags::DEVICE_LOCAL
2724                | vk::MemoryPropertyFlags::HOST_VISIBLE
2725                | vk::MemoryPropertyFlags::HOST_COHERENT
2726                | vk::MemoryPropertyFlags::HOST_CACHED
2727                | vk::MemoryPropertyFlags::LAZILY_ALLOCATED,
2728            phd_capabilities,
2729            phd_features,
2730            downlevel_flags,
2731            private_caps,
2732            workarounds,
2733        };
2734
2735        let available_features = if crate::auxil::supports_core_features_and_limits(
2736            &capabilities.limits,
2737            &capabilities.downlevel,
2738        ) {
2739            available_features | wgt::Features::CORE_FEATURES_AND_LIMITS
2740        } else {
2741            available_features
2742        };
2743
2744        Some(crate::ExposedAdapter {
2745            adapter,
2746            info,
2747            features: available_features,
2748            capabilities,
2749        })
2750    }
2751}
2752
2753impl super::Adapter {
2754    pub fn raw_physical_device(&self) -> vk::PhysicalDevice {
2755        self.raw
2756    }
2757
2758    pub fn get_physical_device_features(&self) -> &PhysicalDeviceFeatures {
2759        &self.phd_features
2760    }
2761
2762    pub fn physical_device_capabilities(&self) -> &PhysicalDeviceProperties {
2763        &self.phd_capabilities
2764    }
2765
2766    pub fn shared_instance(&self) -> &super::InstanceShared {
2767        &self.instance
2768    }
2769
2770    pub fn required_device_extensions(&self, features: wgt::Features) -> Vec<&'static CStr> {
2771        let (supported_extensions, unsupported_extensions) = self
2772            .phd_capabilities
2773            .get_required_extensions(features)
2774            .iter()
2775            .partition::<Vec<&CStr>, _>(|&&extension| {
2776                self.phd_capabilities.supports_extension(extension)
2777            });
2778
2779        if !unsupported_extensions.is_empty() {
2780            log::debug!("Missing extensions: {unsupported_extensions:?}");
2781        }
2782
2783        log::debug!("Supported extensions: {supported_extensions:?}");
2784        supported_extensions
2785    }
2786
2787    /// Create a `PhysicalDeviceFeatures` for opening a logical device with
2788    /// `features` from this adapter.
2789    ///
2790    /// The given `enabled_extensions` set must include all the extensions
2791    /// selected by [`required_device_extensions`] when passed `features`.
2792    /// Otherwise, the `PhysicalDeviceFeatures` value may not be able to select
2793    /// all the Vulkan features needed to represent `features` and this
2794    /// adapter's characteristics.
2795    ///
2796    /// Typically, you'd simply call `required_device_extensions`, and then pass
2797    /// its return value and the feature set you gave it directly to this
2798    /// function. But it's fine to add more extensions to the list.
2799    ///
2800    /// [`required_device_extensions`]: Self::required_device_extensions
2801    pub fn physical_device_features(
2802        &self,
2803        enabled_extensions: &[&'static CStr],
2804        features: wgt::Features,
2805    ) -> PhysicalDeviceFeatures {
2806        PhysicalDeviceFeatures::from_extensions_and_requested_features(
2807            &self.phd_capabilities,
2808            &self.phd_features,
2809            enabled_extensions,
2810            features,
2811            self.downlevel_flags,
2812            &self.private_caps,
2813        )
2814    }
2815
2816    /// # Safety
2817    ///
2818    /// - `raw_device` must be created from this adapter.
2819    /// - `raw_device` must be created using `family_index`, `enabled_extensions` and `physical_device_features()`
2820    /// - `enabled_extensions` must be a superset of `required_device_extensions()`.
2821    /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of `raw_device`. If
2822    ///   `drop_callback` is [`Some`], `raw_device` must be valid until the callback is called.
2823    #[allow(clippy::too_many_arguments)]
2824    pub unsafe fn device_from_raw(
2825        &self,
2826        raw_device: ash::Device,
2827        drop_callback: Option<crate::DropCallback>,
2828        enabled_extensions: &[&'static CStr],
2829        features: wgt::Features,
2830        limits: &wgt::Limits,
2831        memory_hints: &wgt::MemoryHints,
2832        family_index: u32,
2833        queue_index: u32,
2834    ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> {
2835        let mem_properties = {
2836            profiling::scope!("vkGetPhysicalDeviceMemoryProperties");
2837            unsafe {
2838                self.instance
2839                    .raw
2840                    .get_physical_device_memory_properties(self.raw)
2841            }
2842        };
2843        let queue_flags = unsafe {
2844            self.instance
2845                .raw
2846                .get_physical_device_queue_family_properties(self.raw)
2847                .get(family_index as usize)
2848                .map(|queue_family_properties| queue_family_properties.queue_flags)
2849                .ok_or(crate::DeviceError::Unexpected)?
2850        };
2851        let memory_types = &mem_properties.memory_types_as_slice();
2852        let valid_ash_memory_types = memory_types.iter().enumerate().fold(0, |u, (i, mem)| {
2853            if self.known_memory_flags.contains(mem.property_flags) {
2854                u | (1 << i)
2855            } else {
2856                u
2857            }
2858        });
2859
2860        // Note that VK_EXT_debug_utils is an instance extension (enabled at the instance
2861        // level) but contains a few functions that can be loaded directly on the Device for a
2862        // dispatch-table-less pointer.
2863        let debug_utils_fn = if self.instance.extensions.contains(&ext::debug_utils::NAME) {
2864            Some(ext::debug_utils::Device::new(
2865                &self.instance.raw,
2866                &raw_device,
2867            ))
2868        } else {
2869            None
2870        };
2871        let indirect_count_fn = if enabled_extensions.contains(&khr::draw_indirect_count::NAME) {
2872            Some(khr::draw_indirect_count::Device::new(
2873                &self.instance.raw,
2874                &raw_device,
2875            ))
2876        } else {
2877            None
2878        };
2879        let timeline_semaphore_fn = if enabled_extensions.contains(&khr::timeline_semaphore::NAME) {
2880            Some(super::ExtensionFn::Extension(
2881                khr::timeline_semaphore::Device::new(&self.instance.raw, &raw_device),
2882            ))
2883        } else if self.phd_capabilities.device_api_version >= vk::API_VERSION_1_2 {
2884            Some(super::ExtensionFn::Promoted)
2885        } else {
2886            None
2887        };
2888        let ray_tracing_fns = if enabled_extensions.contains(&khr::acceleration_structure::NAME)
2889            && enabled_extensions.contains(&khr::buffer_device_address::NAME)
2890        {
2891            Some(super::RayTracingDeviceExtensionFunctions {
2892                acceleration_structure: khr::acceleration_structure::Device::new(
2893                    &self.instance.raw,
2894                    &raw_device,
2895                ),
2896                buffer_device_address: khr::buffer_device_address::Device::new(
2897                    &self.instance.raw,
2898                    &raw_device,
2899                ),
2900            })
2901        } else {
2902            None
2903        };
2904        let ray_tracing_pipeline_fns =
2905            if enabled_extensions.contains(&khr::ray_tracing_pipeline::NAME) {
2906                Some(khr::ray_tracing_pipeline::Device::new(
2907                    &self.instance.raw,
2908                    &raw_device,
2909                ))
2910            } else {
2911                None
2912            };
2913        let mesh_shading_fns = if enabled_extensions.contains(&ext::mesh_shader::NAME) {
2914            Some(ext::mesh_shader::Device::new(
2915                &self.instance.raw,
2916                &raw_device,
2917            ))
2918        } else {
2919            None
2920        };
2921        let external_memory_fd_fn = if enabled_extensions.contains(&khr::external_memory_fd::NAME) {
2922            Some(khr::external_memory_fd::Device::new(
2923                &self.instance.raw,
2924                &raw_device,
2925            ))
2926        } else {
2927            None
2928        };
2929
2930        let naga_options = {
2931            use naga::back::spv;
2932
2933            // The following capabilities are always available
2934            // see https://registry.khronos.org/vulkan/specs/1.3-extensions/html/chap52.html#spirvenv-capabilities
2935            let mut capabilities = vec![
2936                spv::Capability::Shader,
2937                spv::Capability::Matrix,
2938                spv::Capability::Sampled1D,
2939                spv::Capability::Image1D,
2940                spv::Capability::ImageQuery,
2941                spv::Capability::DerivativeControl,
2942                spv::Capability::StorageImageExtendedFormats,
2943            ];
2944
2945            if self
2946                .downlevel_flags
2947                .contains(wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES)
2948            {
2949                capabilities.push(spv::Capability::SampledCubeArray);
2950            }
2951
2952            if self
2953                .downlevel_flags
2954                .contains(wgt::DownlevelFlags::MULTISAMPLED_SHADING)
2955            {
2956                capabilities.push(spv::Capability::SampleRateShading);
2957            }
2958
2959            if features.contains(wgt::Features::MULTIVIEW) {
2960                capabilities.push(spv::Capability::MultiView);
2961            }
2962
2963            if features.contains(wgt::Features::PRIMITIVE_INDEX) {
2964                capabilities.push(spv::Capability::Geometry);
2965            }
2966
2967            if features.intersects(wgt::Features::SUBGROUP | wgt::Features::SUBGROUP_VERTEX) {
2968                capabilities.push(spv::Capability::GroupNonUniform);
2969                capabilities.push(spv::Capability::GroupNonUniformVote);
2970                capabilities.push(spv::Capability::GroupNonUniformArithmetic);
2971                capabilities.push(spv::Capability::GroupNonUniformBallot);
2972                capabilities.push(spv::Capability::GroupNonUniformShuffle);
2973                capabilities.push(spv::Capability::GroupNonUniformShuffleRelative);
2974                capabilities.push(spv::Capability::GroupNonUniformQuad);
2975            }
2976
2977            if features.intersects(
2978                wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING
2979                    | wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING
2980                    | wgt::Features::UNIFORM_BUFFER_BINDING_ARRAYS,
2981            ) {
2982                capabilities.push(spv::Capability::ShaderNonUniform);
2983            }
2984            if features.contains(wgt::Features::BGRA8UNORM_STORAGE) {
2985                capabilities.push(spv::Capability::StorageImageWriteWithoutFormat);
2986            }
2987
2988            if features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) {
2989                capabilities.push(spv::Capability::RayQueryKHR);
2990            }
2991
2992            if features.contains(wgt::Features::SHADER_INT64) {
2993                capabilities.push(spv::Capability::Int64);
2994            }
2995
2996            if features.contains(wgt::Features::SHADER_F16) {
2997                capabilities.push(spv::Capability::Float16);
2998            }
2999
3000            if features.contains(wgt::Features::SHADER_F64) {
3001                capabilities.push(spv::Capability::Float64);
3002            }
3003
3004            if features.contains(wgt::Features::SHADER_I16) {
3005                capabilities.push(spv::Capability::Int16);
3006            }
3007
3008            if features.intersects(
3009                wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS
3010                    | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX
3011                    | wgt::Features::TEXTURE_INT64_ATOMIC,
3012            ) {
3013                capabilities.push(spv::Capability::Int64Atomics);
3014            }
3015
3016            if features.intersects(wgt::Features::TEXTURE_INT64_ATOMIC) {
3017                capabilities.push(spv::Capability::Int64ImageEXT);
3018            }
3019
3020            if features.contains(wgt::Features::SHADER_FLOAT32_ATOMIC) {
3021                capabilities.push(spv::Capability::AtomicFloat32AddEXT);
3022            }
3023
3024            if features.contains(wgt::Features::CLIP_DISTANCES) {
3025                capabilities.push(spv::Capability::ClipDistance);
3026            }
3027
3028            // Vulkan bundles both barycentrics and per-vertex attributes under the same feature.
3029            if features
3030                .intersects(wgt::Features::SHADER_BARYCENTRICS | wgt::Features::SHADER_PER_VERTEX)
3031            {
3032                capabilities.push(spv::Capability::FragmentBarycentricKHR);
3033            }
3034
3035            if features.contains(wgt::Features::SHADER_DRAW_INDEX) {
3036                capabilities.push(spv::Capability::DrawParameters);
3037            }
3038
3039            let mut flags = spv::WriterFlags::empty();
3040            flags.set(
3041                spv::WriterFlags::DEBUG,
3042                self.instance.flags.contains(wgt::InstanceFlags::DEBUG),
3043            );
3044            flags.set(
3045                spv::WriterFlags::LABEL_VARYINGS,
3046                self.phd_capabilities.properties.vendor_id != crate::auxil::db::qualcomm::VENDOR,
3047            );
3048            flags.set(
3049                spv::WriterFlags::FORCE_POINT_SIZE,
3050                //Note: we could technically disable this when we are compiling separate entry points,
3051                // and we know exactly that the primitive topology is not `PointList`.
3052                // But this requires cloning the `spv::Options` struct, which has heap allocations.
3053                true, // could check `super::Workarounds::SEPARATE_ENTRY_POINTS`
3054            );
3055            flags.set(
3056                spv::WriterFlags::PRINT_ON_RAY_QUERY_INITIALIZATION_FAIL
3057                    | spv::WriterFlags::PRINT_ON_TRACE_RAYS_FAIL,
3058                self.instance.flags.contains(wgt::InstanceFlags::DEBUG)
3059                    && (self.instance.instance_api_version >= vk::API_VERSION_1_3
3060                        || enabled_extensions.contains(&khr::shader_non_semantic_info::NAME)),
3061            );
3062            if features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) {
3063                capabilities.push(spv::Capability::RayQueryKHR);
3064            }
3065            if features.contains(wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES) {
3066                capabilities.push(spv::Capability::RayTracingKHR);
3067            }
3068            if features.contains(wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN) {
3069                capabilities.push(spv::Capability::RayQueryPositionFetchKHR)
3070            }
3071            if features.contains(wgt::Features::EXPERIMENTAL_RAY_TRACING_INVOCATION_REORDER) {
3072                capabilities.push(spv::Capability::ShaderInvocationReorderEXT);
3073            }
3074            if features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER) {
3075                capabilities.push(spv::Capability::MeshShadingEXT);
3076            }
3077            if features.contains(wgt::Features::EXPERIMENTAL_COOPERATIVE_MATRIX) {
3078                capabilities.push(spv::Capability::CooperativeMatrixKHR);
3079                // TODO: expose this more generally
3080                capabilities.push(spv::Capability::VulkanMemoryModel);
3081            }
3082            if self.private_caps.shader_integer_dot_product {
3083                // See <https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_shader_integer_dot_product.html#_new_spir_v_capabilities>.
3084                capabilities.extend(&[
3085                    spv::Capability::DotProductInputAllKHR,
3086                    spv::Capability::DotProductInput4x8BitKHR,
3087                    spv::Capability::DotProductInput4x8BitPackedKHR,
3088                    spv::Capability::DotProductKHR,
3089                ]);
3090            }
3091            if self.private_caps.shader_int8 {
3092                // See <https://registry.khronos.org/vulkan/specs/latest/man/html/VkPhysicalDeviceShaderFloat16Int8Features.html#extension-features-shaderInt8>.
3093                capabilities.extend(&[spv::Capability::Int8]);
3094            }
3095            spv::Options {
3096                lang_version: {
3097                    // Use maximum supported SPIR-V version according to
3098                    // <https://github.com/KhronosGroup/Vulkan-Docs/blob/19b7651/appendices/spirvenv.adoc?plain=1#L21-L40>.
3099                    let version = match self.phd_capabilities.device_api_version {
3100                        vk::API_VERSION_1_0..vk::API_VERSION_1_1 => (1, 0),
3101                        vk::API_VERSION_1_1..vk::API_VERSION_1_2 => (1, 3),
3102                        vk::API_VERSION_1_2..vk::API_VERSION_1_3 => (1, 5),
3103                        vk::API_VERSION_1_3.. => (1, 6),
3104                        _ => unreachable!(),
3105                    };
3106                    // `VK_KHR_spirv_1_4` raises that ceiling on pre-1.2 devices, which
3107                    // both mesh shaders and ray tracing pipelines need it to do.
3108                    if enabled_extensions.contains(&khr::spirv_1_4::NAME) {
3109                        version.max((1, 4))
3110                    } else {
3111                        version
3112                    }
3113                },
3114                flags,
3115                capabilities: Some(capabilities.iter().cloned().collect()),
3116                bounds_check_policies: naga::proc::BoundsCheckPolicies {
3117                    index: naga::proc::BoundsCheckPolicy::Restrict,
3118                    buffer: if self.private_caps.robust_buffer_access2 {
3119                        naga::proc::BoundsCheckPolicy::Unchecked
3120                    } else {
3121                        naga::proc::BoundsCheckPolicy::Restrict
3122                    },
3123                    image_load: if self.private_caps.robust_image_access {
3124                        naga::proc::BoundsCheckPolicy::Unchecked
3125                    } else {
3126                        naga::proc::BoundsCheckPolicy::Restrict
3127                    },
3128                    // TODO: support bounds checks on binding arrays
3129                    binding_array: naga::proc::BoundsCheckPolicy::Unchecked,
3130                },
3131                zero_initialize_workgroup_memory: if self
3132                    .private_caps
3133                    .zero_initialize_workgroup_memory
3134                {
3135                    spv::ZeroInitializeWorkgroupMemoryMode::Native
3136                } else {
3137                    spv::ZeroInitializeWorkgroupMemoryMode::Polyfill
3138                },
3139                force_loop_bounding: true,
3140                ray_query_initialization_tracking: true,
3141                use_storage_input_output_16: features.contains(wgt::Features::SHADER_F16)
3142                    && self.phd_features.supports_storage_input_output_16(),
3143                fake_missing_bindings: false,
3144                // We need to build this separately for each invocation, so just default it out here
3145                binding_map: BTreeMap::default(),
3146                debug_info: None,
3147                task_dispatch_limits: Some(naga::back::TaskDispatchLimits {
3148                    max_mesh_workgroups_per_dim: limits.max_mesh_workgroups_per_dimension,
3149                    max_mesh_workgroups_total: limits.max_mesh_workgroup_total_count,
3150                }),
3151                mesh_shader_primitive_indices_clamp: true,
3152                trace_ray_argument_validation: true,
3153                emit_int_div_checks: true,
3154            }
3155        };
3156
3157        let raw_queue = {
3158            profiling::scope!("vkGetDeviceQueue");
3159            unsafe { raw_device.get_device_queue(family_index, queue_index) }
3160        };
3161
3162        let driver_version = self
3163            .phd_capabilities
3164            .properties
3165            .driver_version
3166            .to_be_bytes();
3167        #[rustfmt::skip]
3168        let pipeline_cache_validation_key = [
3169            driver_version[0], driver_version[1], driver_version[2], driver_version[3],
3170            0, 0, 0, 0,
3171            0, 0, 0, 0,
3172            0, 0, 0, 0,
3173        ];
3174
3175        let drop_guard = crate::DropGuard::from_option(drop_callback);
3176
3177        let empty_descriptor_set_layout = unsafe {
3178            raw_device
3179                .create_descriptor_set_layout(&vk::DescriptorSetLayoutCreateInfo::default(), None)
3180                .map_err(super::map_host_device_oom_err)?
3181        };
3182
3183        let shared = Arc::new(super::DeviceShared {
3184            raw: raw_device,
3185            family_index,
3186            queue_flags,
3187            queue_index,
3188            raw_queue,
3189            drop_guard,
3190            instance: Arc::clone(&self.instance),
3191            physical_device: self.raw,
3192            enabled_extensions: enabled_extensions.into(),
3193            extension_fns: super::DeviceExtensionFunctions {
3194                debug_utils: debug_utils_fn,
3195                draw_indirect_count: indirect_count_fn,
3196                timeline_semaphore: timeline_semaphore_fn,
3197                ray_tracing: ray_tracing_fns,
3198                ray_tracing_pipelines: ray_tracing_pipeline_fns,
3199                mesh_shading: mesh_shading_fns,
3200                external_memory_fd: external_memory_fd_fn,
3201            },
3202            pipeline_cache_validation_key,
3203            vendor_id: self.phd_capabilities.properties.vendor_id,
3204            timestamp_period: self.phd_capabilities.properties.limits.timestamp_period,
3205            private_caps: self.private_caps.clone(),
3206            features,
3207            workarounds: self.workarounds,
3208            render_passes: Mutex::new(Default::default()),
3209            sampler_cache: Mutex::new(super::sampler::SamplerCache::new(
3210                self.private_caps.maximum_samplers,
3211            )),
3212            memory_allocations_counter: Default::default(),
3213
3214            texture_identity_factory: super::ResourceIdentityFactory::new(),
3215            texture_view_identity_factory: super::ResourceIdentityFactory::new(),
3216            empty_descriptor_set_layout,
3217        });
3218
3219        let relay_semaphores = super::RelaySemaphores::new(&shared)?;
3220
3221        let queue = super::Queue {
3222            raw: raw_queue,
3223            device: Arc::clone(&shared),
3224            family_index,
3225            relay_semaphores: Mutex::new(relay_semaphores),
3226            signal_semaphores: Mutex::new(SemaphoreList::new(SemaphoreListMode::Signal)),
3227            wait_semaphores: Mutex::new(SemaphoreList::new(SemaphoreListMode::Wait)),
3228            next_submit_chain: Mutex::new(None),
3229        };
3230
3231        let allocation_sizes = AllocationSizes::from_memory_hints(memory_hints);
3232
3233        let buffer_device_address = enabled_extensions.contains(&khr::buffer_device_address::NAME);
3234
3235        let mem_allocator = super::MemoryAllocators::new(
3236            self.instance.raw.clone(),
3237            shared.raw.clone(),
3238            self.raw,
3239            buffer_device_address,
3240            allocation_sizes,
3241        )?;
3242
3243        let desc_allocator = super::descriptor::DescriptorAllocator::new(
3244            if let Some(di) = self.phd_capabilities.descriptor_indexing {
3245                di.max_update_after_bind_descriptors_in_all_pools
3246            } else {
3247                0
3248            },
3249        );
3250
3251        let device = super::Device {
3252            shared,
3253            mem_allocator,
3254            desc_allocator: Mutex::new(desc_allocator),
3255            valid_ash_memory_types,
3256            naga_options,
3257            #[cfg(feature = "renderdoc")]
3258            render_doc: Default::default(),
3259            counters: Default::default(),
3260        };
3261
3262        Ok(crate::OpenDevice { device, queue })
3263    }
3264
3265    pub fn texture_format_as_raw(&self, texture_format: wgt::TextureFormat) -> vk::Format {
3266        self.private_caps.map_texture_format(texture_format)
3267    }
3268
3269    /// # Safety:
3270    /// - Same as `open` plus
3271    /// - The callback may not change anything that the device does not support.
3272    /// - The callback may not remove features.
3273    pub unsafe fn open_with_callback<'a>(
3274        &self,
3275        features: wgt::Features,
3276        limits: &wgt::Limits,
3277        memory_hints: &wgt::MemoryHints,
3278        callback: Option<Box<super::CreateDeviceCallback<'a>>>,
3279    ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> {
3280        let mut enabled_extensions = self.required_device_extensions(features);
3281        let mut enabled_phd_features = self.physical_device_features(&enabled_extensions, features);
3282
3283        let default_family_index = 0;
3284        let mut family_infos = vec![vk::DeviceQueueCreateInfo::default()
3285            .queue_family_index(default_family_index)
3286            .queue_priorities(&[1.0])];
3287
3288        let mut pre_info = vk::DeviceCreateInfo::default();
3289
3290        if let Some(callback) = callback {
3291            callback(super::CreateDeviceCallbackArgs {
3292                extensions: &mut enabled_extensions,
3293                device_features: &mut enabled_phd_features,
3294                queue_create_infos: &mut family_infos,
3295                create_info: &mut pre_info,
3296                _phantom: PhantomData,
3297            })
3298        }
3299
3300        let str_pointers = enabled_extensions
3301            .iter()
3302            .map(|&s| {
3303                // Safe because `enabled_extensions` entries have static lifetime.
3304                s.as_ptr()
3305            })
3306            .collect::<Vec<_>>();
3307
3308        let pre_info = pre_info
3309            .queue_create_infos(&family_infos)
3310            .enabled_extension_names(&str_pointers);
3311        let info = enabled_phd_features.add_to_device_create(pre_info);
3312        let raw_device = {
3313            profiling::scope!("vkCreateDevice");
3314            unsafe {
3315                self.instance
3316                    .raw
3317                    .create_device(self.raw, &info, None)
3318                    .map_err(map_err)?
3319            }
3320        };
3321        fn map_err(err: vk::Result) -> crate::DeviceError {
3322            match err {
3323                vk::Result::ERROR_TOO_MANY_OBJECTS => crate::DeviceError::OutOfMemory,
3324                vk::Result::ERROR_INITIALIZATION_FAILED => crate::DeviceError::Lost,
3325                vk::Result::ERROR_EXTENSION_NOT_PRESENT | vk::Result::ERROR_FEATURE_NOT_PRESENT => {
3326                    crate::hal_usage_error(err)
3327                }
3328                other => super::map_host_device_oom_and_lost_err(other),
3329            }
3330        }
3331
3332        unsafe {
3333            self.device_from_raw(
3334                raw_device,
3335                None,
3336                &enabled_extensions,
3337                features,
3338                limits,
3339                memory_hints,
3340                family_infos[0].queue_family_index,
3341                0,
3342            )
3343        }
3344    }
3345}
3346
3347impl crate::Adapter for super::Adapter {
3348    type A = super::Api;
3349
3350    unsafe fn open(
3351        &self,
3352        features: wgt::Features,
3353        limits: &wgt::Limits,
3354        memory_hints: &wgt::MemoryHints,
3355    ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> {
3356        unsafe { self.open_with_callback(features, limits, memory_hints, None) }
3357    }
3358
3359    unsafe fn texture_format_capabilities(
3360        &self,
3361        format: wgt::TextureFormat,
3362    ) -> crate::TextureFormatCapabilities {
3363        use crate::TextureFormatCapabilities as Tfc;
3364
3365        let vk_format = self.private_caps.map_texture_format(format);
3366        let properties = unsafe {
3367            self.instance
3368                .raw
3369                .get_physical_device_format_properties(self.raw, vk_format)
3370        };
3371        let features = properties.optimal_tiling_features;
3372
3373        let mut flags = Tfc::empty();
3374        flags.set(
3375            Tfc::SAMPLED,
3376            features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE),
3377        );
3378        flags.set(
3379            Tfc::SAMPLED_LINEAR,
3380            features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_LINEAR),
3381        );
3382        // flags.set(
3383        //     Tfc::SAMPLED_MINMAX,
3384        //     features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_MINMAX),
3385        // );
3386        flags.set(
3387            Tfc::STORAGE_READ_WRITE
3388                | Tfc::STORAGE_WRITE_ONLY
3389                | Tfc::STORAGE_READ_ONLY
3390                | Tfc::STORAGE_ATOMIC,
3391            features.contains(vk::FormatFeatureFlags::STORAGE_IMAGE),
3392        );
3393        flags.set(
3394            Tfc::STORAGE_ATOMIC,
3395            features.contains(vk::FormatFeatureFlags::STORAGE_IMAGE_ATOMIC),
3396        );
3397        flags.set(
3398            Tfc::COLOR_ATTACHMENT,
3399            features.contains(vk::FormatFeatureFlags::COLOR_ATTACHMENT),
3400        );
3401        flags.set(
3402            Tfc::COLOR_ATTACHMENT_BLEND,
3403            features.contains(vk::FormatFeatureFlags::COLOR_ATTACHMENT_BLEND),
3404        );
3405        flags.set(
3406            Tfc::DEPTH_STENCIL_ATTACHMENT,
3407            features.contains(vk::FormatFeatureFlags::DEPTH_STENCIL_ATTACHMENT),
3408        );
3409        flags.set(
3410            Tfc::COPY_SRC,
3411            features.intersects(vk::FormatFeatureFlags::TRANSFER_SRC),
3412        );
3413        flags.set(
3414            Tfc::COPY_DST,
3415            features.intersects(vk::FormatFeatureFlags::TRANSFER_DST),
3416        );
3417        flags.set(
3418            Tfc::STORAGE_ATOMIC,
3419            features.intersects(vk::FormatFeatureFlags::STORAGE_IMAGE_ATOMIC),
3420        );
3421        // Multi-planar images are created with `EXTENDED_USAGE`, so views of
3422        // the planes are limited by the plane view formats, not by this format.
3423        if format.is_multi_planar_format() && !flags.is_empty() {
3424            let plane_caps = |aspect| unsafe {
3425                self.texture_format_capabilities(format.aspect_specific_format(aspect).unwrap())
3426            };
3427            return (flags & (Tfc::COPY_SRC | Tfc::COPY_DST))
3428                | (plane_caps(wgt::TextureAspect::Plane0)
3429                    & plane_caps(wgt::TextureAspect::Plane1)
3430                    & Tfc::VALID_FOR_MULTI_PLANAR);
3431        }
3432
3433        // Vulkan is very permissive about MSAA
3434        flags.set(Tfc::MULTISAMPLE_RESOLVE, !format.is_compressed());
3435
3436        // get the supported sample counts
3437        let format_aspect = crate::FormatAspects::from(format);
3438        let limits = self.phd_capabilities.properties.limits;
3439
3440        let sample_flags = if format_aspect.contains(crate::FormatAspects::DEPTH) {
3441            limits
3442                .framebuffer_depth_sample_counts
3443                .min(limits.sampled_image_depth_sample_counts)
3444        } else if format_aspect.contains(crate::FormatAspects::STENCIL) {
3445            limits
3446                .framebuffer_stencil_sample_counts
3447                .min(limits.sampled_image_stencil_sample_counts)
3448        } else {
3449            let first_aspect = format_aspect
3450                .iter()
3451                .next()
3452                .expect("All texture should at least one aspect")
3453                .map();
3454
3455            // We should never get depth or stencil out of this, due to the above.
3456            assert_ne!(first_aspect, wgt::TextureAspect::DepthOnly);
3457            assert_ne!(first_aspect, wgt::TextureAspect::StencilOnly);
3458
3459            match format.sample_type(Some(first_aspect), None).unwrap() {
3460                wgt::TextureSampleType::Float { .. } => limits
3461                    .framebuffer_color_sample_counts
3462                    .min(limits.sampled_image_color_sample_counts),
3463                wgt::TextureSampleType::Sint | wgt::TextureSampleType::Uint => {
3464                    limits.sampled_image_integer_sample_counts
3465                }
3466                _ => unreachable!(),
3467            }
3468        };
3469
3470        flags.set(
3471            Tfc::MULTISAMPLE_X2,
3472            sample_flags.contains(vk::SampleCountFlags::TYPE_2),
3473        );
3474        flags.set(
3475            Tfc::MULTISAMPLE_X4,
3476            sample_flags.contains(vk::SampleCountFlags::TYPE_4),
3477        );
3478        flags.set(
3479            Tfc::MULTISAMPLE_X8,
3480            sample_flags.contains(vk::SampleCountFlags::TYPE_8),
3481        );
3482        flags.set(
3483            Tfc::MULTISAMPLE_X16,
3484            sample_flags.contains(vk::SampleCountFlags::TYPE_16),
3485        );
3486
3487        flags
3488    }
3489
3490    unsafe fn surface_capabilities(
3491        &self,
3492        surface: &super::Surface,
3493    ) -> Option<crate::SurfaceCapabilities> {
3494        surface.inner.surface_capabilities(self)
3495    }
3496
3497    unsafe fn surface_display_hdr_info(
3498        &self,
3499        surface: &super::Surface,
3500    ) -> Option<wgt::DisplayHdrInfo> {
3501        // Vulkan has no portable luminance query; the Win32 surface reads it
3502        // through DXGI (see `dxgi::hdr`). Every other surface reports `None`.
3503        surface.inner.display_hdr_info()
3504    }
3505
3506    unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp {
3507        // VK_GOOGLE_display_timing is the only way to get presentation
3508        // timestamps on vulkan right now and it is only ever available
3509        // on android and linux. This includes mac, but there's no alternative
3510        // on mac, so this is fine.
3511        #[cfg(unix)]
3512        {
3513            let mut timespec = libc::timespec::default();
3514            unsafe {
3515                libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut timespec);
3516            }
3517
3518            wgt::PresentationTimestamp(
3519                timespec.tv_sec as u128 * 1_000_000_000 + timespec.tv_nsec as u128,
3520            )
3521        }
3522        #[cfg(not(unix))]
3523        {
3524            wgt::PresentationTimestamp::INVALID_TIMESTAMP
3525        }
3526    }
3527
3528    fn get_ordered_buffer_usages(&self) -> wgt::BufferUses {
3529        wgt::BufferUses::INCLUSIVE | wgt::BufferUses::MAP_WRITE
3530    }
3531
3532    // Vulkan makes very few execution ordering guarantees
3533    // see https://registry.khronos.org/vulkan/specs/latest/html/vkspec.html#synchronization-implicit
3534    // We just don't want to insert barriers between inclusive uses
3535    // See https://github.com/gfx-rs/wgpu/issues/8853
3536    fn get_ordered_texture_usages(&self) -> wgt::TextureUses {
3537        wgt::TextureUses::INCLUSIVE
3538    }
3539}
3540
3541fn is_format_16bit_norm_supported(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool {
3542    [
3543        vk::Format::R16_UNORM,
3544        vk::Format::R16_SNORM,
3545        vk::Format::R16G16_UNORM,
3546        vk::Format::R16G16_SNORM,
3547        vk::Format::R16G16B16A16_UNORM,
3548        vk::Format::R16G16B16A16_SNORM,
3549    ]
3550    .into_iter()
3551    .all(|format| {
3552        supports_format(
3553            instance,
3554            phd,
3555            format,
3556            vk::ImageTiling::OPTIMAL,
3557            vk::FormatFeatureFlags::SAMPLED_IMAGE
3558                | vk::FormatFeatureFlags::STORAGE_IMAGE
3559                | vk::FormatFeatureFlags::TRANSFER_SRC
3560                | vk::FormatFeatureFlags::TRANSFER_DST,
3561        )
3562    })
3563}
3564
3565fn is_float32_filterable_supported(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool {
3566    [
3567        vk::Format::R32_SFLOAT,
3568        vk::Format::R32G32_SFLOAT,
3569        vk::Format::R32G32B32A32_SFLOAT,
3570    ]
3571    .into_iter()
3572    .all(|format| {
3573        supports_format(
3574            instance,
3575            phd,
3576            format,
3577            vk::ImageTiling::OPTIMAL,
3578            vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_LINEAR,
3579        )
3580    })
3581}
3582
3583fn is_float32_blendable_supported(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool {
3584    [
3585        vk::Format::R32_SFLOAT,
3586        vk::Format::R32G32_SFLOAT,
3587        vk::Format::R32G32B32A32_SFLOAT,
3588    ]
3589    .into_iter()
3590    .all(|format| {
3591        supports_format(
3592            instance,
3593            phd,
3594            format,
3595            vk::ImageTiling::OPTIMAL,
3596            vk::FormatFeatureFlags::COLOR_ATTACHMENT_BLEND,
3597        )
3598    })
3599}
3600
3601pub(super) fn supports_format(
3602    instance: &ash::Instance,
3603    phd: vk::PhysicalDevice,
3604    format: vk::Format,
3605    tiling: vk::ImageTiling,
3606    features: vk::FormatFeatureFlags,
3607) -> bool {
3608    let properties = unsafe { instance.get_physical_device_format_properties(phd, format) };
3609    match tiling {
3610        vk::ImageTiling::LINEAR => properties.linear_tiling_features.contains(features),
3611        vk::ImageTiling::OPTIMAL => properties.optimal_tiling_features.contains(features),
3612        _ => false,
3613    }
3614}
3615
3616fn supports_astc_3d(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool {
3617    [
3618        vk::Format::ASTC_4X4_UNORM_BLOCK,
3619        vk::Format::ASTC_4X4_SRGB_BLOCK,
3620        vk::Format::ASTC_5X4_UNORM_BLOCK,
3621        vk::Format::ASTC_5X4_SRGB_BLOCK,
3622        vk::Format::ASTC_5X5_UNORM_BLOCK,
3623        vk::Format::ASTC_5X5_SRGB_BLOCK,
3624        vk::Format::ASTC_6X5_UNORM_BLOCK,
3625        vk::Format::ASTC_6X5_SRGB_BLOCK,
3626        vk::Format::ASTC_6X6_UNORM_BLOCK,
3627        vk::Format::ASTC_6X6_SRGB_BLOCK,
3628        vk::Format::ASTC_8X5_UNORM_BLOCK,
3629        vk::Format::ASTC_8X5_SRGB_BLOCK,
3630        vk::Format::ASTC_8X6_UNORM_BLOCK,
3631        vk::Format::ASTC_8X6_SRGB_BLOCK,
3632        vk::Format::ASTC_8X8_UNORM_BLOCK,
3633        vk::Format::ASTC_8X8_SRGB_BLOCK,
3634        vk::Format::ASTC_10X5_UNORM_BLOCK,
3635        vk::Format::ASTC_10X5_SRGB_BLOCK,
3636        vk::Format::ASTC_10X6_UNORM_BLOCK,
3637        vk::Format::ASTC_10X6_SRGB_BLOCK,
3638        vk::Format::ASTC_10X8_UNORM_BLOCK,
3639        vk::Format::ASTC_10X8_SRGB_BLOCK,
3640        vk::Format::ASTC_10X10_UNORM_BLOCK,
3641        vk::Format::ASTC_10X10_SRGB_BLOCK,
3642        vk::Format::ASTC_12X10_UNORM_BLOCK,
3643        vk::Format::ASTC_12X10_SRGB_BLOCK,
3644        vk::Format::ASTC_12X12_UNORM_BLOCK,
3645        vk::Format::ASTC_12X12_SRGB_BLOCK,
3646    ]
3647    .into_iter()
3648    .all(|format| {
3649        unsafe {
3650            instance.get_physical_device_image_format_properties(
3651                phd,
3652                format,
3653                vk::ImageType::TYPE_3D,
3654                vk::ImageTiling::OPTIMAL,
3655                vk::ImageUsageFlags::SAMPLED,
3656                vk::ImageCreateFlags::empty(),
3657            )
3658        }
3659        .is_ok()
3660    })
3661}
3662
3663fn supports_bgra8unorm_storage(
3664    instance: &ash::Instance,
3665    phd: vk::PhysicalDevice,
3666    device_api_version: u32,
3667) -> bool {
3668    // See https://github.com/KhronosGroup/Vulkan-Docs/issues/2027#issuecomment-1380608011
3669
3670    // This check gates the function call and structures used below.
3671    // TODO: check for (`VK_KHR_get_physical_device_properties2` or VK1.1) and (`VK_KHR_format_feature_flags2` or VK1.3).
3672    // Right now we only check for VK1.3.
3673    if device_api_version < vk::API_VERSION_1_3 {
3674        return false;
3675    }
3676
3677    unsafe {
3678        let mut properties3 = vk::FormatProperties3::default();
3679        let mut properties2 = vk::FormatProperties2::default().push_next(&mut properties3);
3680
3681        instance.get_physical_device_format_properties2(
3682            phd,
3683            vk::Format::B8G8R8A8_UNORM,
3684            &mut properties2,
3685        );
3686
3687        let features2 = properties2.format_properties.optimal_tiling_features;
3688        let features3 = properties3.optimal_tiling_features;
3689
3690        features2.contains(vk::FormatFeatureFlags::STORAGE_IMAGE)
3691            && features3.contains(vk::FormatFeatureFlags2::STORAGE_WRITE_WITHOUT_FORMAT)
3692    }
3693}
3694
3695// For https://github.com/gfx-rs/wgpu/issues/4599
3696// Intel iGPUs with outdated drivers can break rendering if `VK_EXT_robustness2` is used.
3697// Driver version 31.0.101.2115 works, but there's probably an earlier functional version.
3698fn is_intel_igpu_outdated_for_robustness2(capabilities: &PhysicalDeviceProperties) -> bool {
3699    const DRIVER_VERSION_WORKING: u32 = (101 << 14) | 2115; // X.X.101.2115
3700
3701    let props = &capabilities.properties;
3702
3703    let is_outdated = props.vendor_id == crate::auxil::db::intel::VENDOR
3704        && props.device_type == vk::PhysicalDeviceType::INTEGRATED_GPU
3705        && props.driver_version < DRIVER_VERSION_WORKING
3706        && capabilities.is_driver(vk::DriverId::INTEL_PROPRIETARY_WINDOWS);
3707
3708    if is_outdated {
3709        log::debug!(
3710            "Disabling robustBufferAccess2 and robustImageAccess2: IntegratedGpu Intel Driver is outdated. Found with version 0x{:X}, less than the known good version 0x{:X} (31.0.101.2115)",
3711            props.driver_version,
3712            DRIVER_VERSION_WORKING
3713        );
3714    }
3715    is_outdated
3716}
3717
3718/// Returns `true` if Arm's proprietary driver can leak memory on timeline semaphore signals.
3719///
3720/// Arm fixed this in `r46`. Rockchip's `g`-numbered drivers have the fix from `g24` at the latest.
3721/// If `driver_info` does not start with `v1.r<N>p` or `v1.g<N>p`, this returns `true`.
3722fn arm_driver_leaks_timeline_semaphores(driver_info: &str) -> bool {
3723    let Some(release) = driver_info.strip_prefix("v1.") else {
3724        return true;
3725    };
3726    let (fixed_in, rest) = if let Some(rest) = release.strip_prefix('r') {
3727        (46, rest)
3728    } else if let Some(rest) = release.strip_prefix('g') {
3729        (24, rest)
3730    } else {
3731        return true;
3732    };
3733    match rest.split_once('p') {
3734        Some((number, _)) => number.parse::<u32>().map_or(true, |n| n < fixed_in),
3735        None => true,
3736    }
3737}
3738
3739/// Convert Vulkan component type to wgt::CooperativeScalarType.
3740fn map_vk_component_type(ty: vk::ComponentTypeKHR) -> Option<wgt::CooperativeScalarType> {
3741    match ty {
3742        vk::ComponentTypeKHR::FLOAT16 => Some(wgt::CooperativeScalarType::F16),
3743        vk::ComponentTypeKHR::FLOAT32 => Some(wgt::CooperativeScalarType::F32),
3744        vk::ComponentTypeKHR::SINT32 => Some(wgt::CooperativeScalarType::I32),
3745        vk::ComponentTypeKHR::UINT32 => Some(wgt::CooperativeScalarType::U32),
3746        _ => None,
3747    }
3748}
3749
3750/// Convert Vulkan matrix size.
3751fn map_vk_cooperative_size(size: u32) -> Option<u32> {
3752    match size {
3753        8 | 16 => Some(size),
3754        _ => None,
3755    }
3756}
3757
3758/// Query all supported cooperative matrix configurations from Vulkan.
3759fn query_cooperative_matrix_properties(
3760    coop_matrix: &khr::cooperative_matrix::Instance,
3761    phd: vk::PhysicalDevice,
3762) -> Vec<wgt::CooperativeMatrixProperties> {
3763    let vk_properties =
3764        match unsafe { coop_matrix.get_physical_device_cooperative_matrix_properties(phd) } {
3765            Ok(props) => props,
3766            Err(e) => {
3767                log::warn!("Failed to query cooperative matrix properties: {e:?}");
3768                return Vec::new();
3769            }
3770        };
3771
3772    log::debug!(
3773        "Vulkan reports {} cooperative matrix configurations",
3774        vk_properties.len()
3775    );
3776
3777    let mut result = Vec::new();
3778    for prop in &vk_properties {
3779        log::debug!(
3780            "  Vulkan coop matrix: M={} N={} K={} A={:?} B={:?} C={:?} Result={:?} scope={:?} saturating={}",
3781            prop.m_size,
3782            prop.n_size,
3783            prop.k_size,
3784            prop.a_type,
3785            prop.b_type,
3786            prop.c_type,
3787            prop.result_type,
3788            prop.scope,
3789            prop.saturating_accumulation
3790        );
3791
3792        // Only include subgroup-scoped operations (the only scope we support)
3793        if prop.scope != vk::ScopeKHR::SUBGROUP {
3794            log::debug!("    Skipped: scope is not SUBGROUP");
3795            continue;
3796        }
3797
3798        // Map sizes - skip configurations with sizes we don't support
3799        let m_size = match map_vk_cooperative_size(prop.m_size) {
3800            Some(s) => s,
3801            None => {
3802                log::debug!("    Skipped: M size {} not supported", prop.m_size);
3803                continue;
3804            }
3805        };
3806        let n_size = match map_vk_cooperative_size(prop.n_size) {
3807            Some(s) => s,
3808            None => {
3809                log::debug!("    Skipped: N size {} not supported", prop.n_size);
3810                continue;
3811            }
3812        };
3813        let k_size = match map_vk_cooperative_size(prop.k_size) {
3814            Some(s) => s,
3815            None => {
3816                log::debug!("    Skipped: K size {} not supported", prop.k_size);
3817                continue;
3818            }
3819        };
3820
3821        // Map the component types - A and B must match, C and Result must match
3822        let ab_type = match map_vk_component_type(prop.a_type) {
3823            Some(t) if Some(t) == map_vk_component_type(prop.b_type) => t,
3824            _ => {
3825                log::debug!(
3826                    "    Skipped: A/B types {:?}/{:?} not supported or don't match",
3827                    prop.a_type,
3828                    prop.b_type
3829                );
3830                continue;
3831            }
3832        };
3833        let cr_type = match map_vk_component_type(prop.c_type) {
3834            Some(t) if Some(t) == map_vk_component_type(prop.result_type) => t,
3835            _ => {
3836                log::debug!(
3837                    "    Skipped: C/Result types {:?}/{:?} not supported or don't match",
3838                    prop.c_type,
3839                    prop.result_type
3840                );
3841                continue;
3842            }
3843        };
3844
3845        log::debug!("    Accepted!");
3846        result.push(wgt::CooperativeMatrixProperties {
3847            m_size,
3848            n_size,
3849            k_size,
3850            ab_type,
3851            cr_type,
3852            saturating_accumulation: prop.saturating_accumulation != 0,
3853        });
3854    }
3855
3856    log::debug!(
3857        "Found {} cooperative matrix configurations supported by wgpu",
3858        result.len()
3859    );
3860    result
3861}
3862
3863#[cfg(test)]
3864mod tests {
3865    use super::arm_driver_leaks_timeline_semaphores as leaks;
3866
3867    #[test]
3868    fn arm_timeline_semaphore_driver_versions() {
3869        assert!(leaks("v1.g18p0-01eac0.9e534f339477793d151cc7ab4c27f2c0"));
3870        assert!(!leaks("v1.g24p0-00eac0.3c7aec95bbe4cb46ae6709632084ff89"));
3871        assert!(leaks(
3872            "v1.r44p0-wayland-drm-g310-dmaheap-aarch64-d877e132c-18"
3873        ));
3874        assert!(!leaks("v1.r46p0-01eac0"));
3875        assert!(leaks("?"));
3876        assert!(leaks("v1.x50p0"));
3877        assert!(leaks("v1.r50"));
3878    }
3879}