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