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