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