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 parking_lot::Mutex;
6
7use super::conv;
8
9fn depth_stencil_required_flags() -> vk::FormatFeatureFlags {
10    vk::FormatFeatureFlags::SAMPLED_IMAGE | vk::FormatFeatureFlags::DEPTH_STENCIL_ATTACHMENT
11}
12
13const INDEXING_FEATURES: wgt::Features = wgt::Features::TEXTURE_BINDING_ARRAY
14    .union(wgt::Features::BUFFER_BINDING_ARRAY)
15    .union(wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY)
16    .union(wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING)
17    .union(wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING)
18    .union(wgt::Features::UNIFORM_BUFFER_BINDING_ARRAYS)
19    .union(wgt::Features::PARTIALLY_BOUND_BINDING_ARRAY);
20
21#[expect(rustdoc::private_intra_doc_links)]
22/// Features supported by a [`vk::PhysicalDevice`] and its extensions.
23///
24/// This is used in two phases:
25///
26/// - When enumerating adapters, this represents the features offered by the
27///   adapter. [`Instance::expose_adapter`] calls `vkGetPhysicalDeviceFeatures2`
28///   (or `vkGetPhysicalDeviceFeatures` if that is not available) to collect
29///   this information about the `VkPhysicalDevice` represented by the
30///   `wgpu_hal::ExposedAdapter`.
31///
32/// - When opening a device, this represents the features we would like to
33///   enable. At `wgpu_hal::Device` construction time,
34///   [`PhysicalDeviceFeatures::from_extensions_and_requested_features`]
35///   constructs an value of this type indicating which Vulkan features to
36///   enable, based on the `wgpu_types::Features` requested.
37///
38/// [`Instance::expose_adapter`]: super::Instance::expose_adapter
39#[derive(Debug, Default)]
40pub struct PhysicalDeviceFeatures {
41    /// Basic Vulkan 1.0 features.
42    core: vk::PhysicalDeviceFeatures,
43
44    /// Features provided by `VK_EXT_descriptor_indexing`, promoted to Vulkan 1.2.
45    pub(super) descriptor_indexing:
46        Option<vk::PhysicalDeviceDescriptorIndexingFeaturesEXT<'static>>,
47
48    /// Features provided by `VK_KHR_timeline_semaphore`, promoted to Vulkan 1.2
49    timeline_semaphore: Option<vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR<'static>>,
50
51    /// Features provided by `VK_EXT_image_robustness`, promoted to Vulkan 1.3
52    image_robustness: Option<vk::PhysicalDeviceImageRobustnessFeaturesEXT<'static>>,
53
54    /// Features provided by `VK_EXT_robustness2`.
55    robustness2: Option<vk::PhysicalDeviceRobustness2FeaturesEXT<'static>>,
56
57    /// Features provided by `VK_KHR_multiview`, promoted to Vulkan 1.1.
58    multiview: Option<vk::PhysicalDeviceMultiviewFeaturesKHR<'static>>,
59
60    /// Features provided by `VK_KHR_sampler_ycbcr_conversion`, promoted to Vulkan 1.1.
61    sampler_ycbcr_conversion: Option<vk::PhysicalDeviceSamplerYcbcrConversionFeatures<'static>>,
62
63    /// Features provided by `VK_EXT_texture_compression_astc_hdr`, promoted to Vulkan 1.3.
64    astc_hdr: Option<vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT<'static>>,
65
66    /// Features provided by `VK_KHR_shader_float16_int8`, promoted to Vulkan 1.2
67    shader_float16_int8: Option<vk::PhysicalDeviceShaderFloat16Int8Features<'static>>,
68
69    /// Features provided by `VK_KHR_16bit_storage`, promoted to Vulkan 1.1
70    _16bit_storage: Option<vk::PhysicalDevice16BitStorageFeatures<'static>>,
71
72    /// Features provided by `VK_KHR_acceleration_structure`.
73    acceleration_structure: Option<vk::PhysicalDeviceAccelerationStructureFeaturesKHR<'static>>,
74
75    /// Features provided by `VK_KHR_buffer_device_address`, promoted to Vulkan 1.2.
76    ///
77    /// We only use this feature for
78    /// [`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE`], which requires
79    /// `VK_KHR_acceleration_structure`, which depends on
80    /// `VK_KHR_buffer_device_address`, so [`Instance::expose_adapter`] only
81    /// bothers to check if `VK_KHR_acceleration_structure` is available,
82    /// leaving this `None`.
83    ///
84    /// However, we do populate this when creating a device if
85    /// [`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE`] is requested.
86    ///
87    /// [`Instance::expose_adapter`]: super::Instance::expose_adapter
88    /// [`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE`]: wgt::Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE
89    buffer_device_address: Option<vk::PhysicalDeviceBufferDeviceAddressFeaturesKHR<'static>>,
90
91    /// Features provided by `VK_KHR_ray_query`,
92    ///
93    /// Vulkan requires that the feature be present if the `VK_KHR_ray_query`
94    /// extension is present, so [`Instance::expose_adapter`] doesn't bother retrieving
95    /// this from `vkGetPhysicalDeviceFeatures2`.
96    ///
97    /// However, we do populate this when creating a device if ray tracing is requested.
98    ///
99    /// [`Instance::expose_adapter`]: super::Instance::expose_adapter
100    ray_query: Option<vk::PhysicalDeviceRayQueryFeaturesKHR<'static>>,
101
102    /// Features provided by `VK_KHR_zero_initialize_workgroup_memory`, promoted
103    /// to Vulkan 1.3.
104    zero_initialize_workgroup_memory:
105        Option<vk::PhysicalDeviceZeroInitializeWorkgroupMemoryFeatures<'static>>,
106    position_fetch: Option<vk::PhysicalDeviceRayTracingPositionFetchFeaturesKHR<'static>>,
107
108    /// Features provided by `VK_KHR_shader_atomic_int64`, promoted to Vulkan 1.2.
109    shader_atomic_int64: Option<vk::PhysicalDeviceShaderAtomicInt64Features<'static>>,
110
111    /// Features provided by `VK_EXT_shader_image_atomic_int64`
112    shader_image_atomic_int64: Option<vk::PhysicalDeviceShaderImageAtomicInt64FeaturesEXT<'static>>,
113
114    /// Features provided by `VK_EXT_shader_atomic_float`.
115    shader_atomic_float: Option<vk::PhysicalDeviceShaderAtomicFloatFeaturesEXT<'static>>,
116
117    /// Features provided by `VK_EXT_subgroup_size_control`, promoted to Vulkan 1.3.
118    subgroup_size_control: Option<vk::PhysicalDeviceSubgroupSizeControlFeatures<'static>>,
119
120    /// Features proved by `VK_KHR_maintenance4`, needed for mesh shaders
121    maintenance4: Option<vk::PhysicalDeviceMaintenance4FeaturesKHR<'static>>,
122
123    /// Features proved by `VK_EXT_mesh_shader`
124    mesh_shader: Option<vk::PhysicalDeviceMeshShaderFeaturesEXT<'static>>,
125
126    /// Features provided by `VK_KHR_shader_integer_dot_product`, promoted to Vulkan 1.3.
127    shader_integer_dot_product:
128        Option<vk::PhysicalDeviceShaderIntegerDotProductFeaturesKHR<'static>>,
129}
130
131impl PhysicalDeviceFeatures {
132    /// Add the members of `self` into `info.enabled_features` and its `p_next` chain.
133    pub fn add_to_device_create<'a>(
134        &'a mut self,
135        mut info: vk::DeviceCreateInfo<'a>,
136    ) -> vk::DeviceCreateInfo<'a> {
137        info = info.enabled_features(&self.core);
138        if let Some(ref mut feature) = self.descriptor_indexing {
139            info = info.push_next(feature);
140        }
141        if let Some(ref mut feature) = self.timeline_semaphore {
142            info = info.push_next(feature);
143        }
144        if let Some(ref mut feature) = self.image_robustness {
145            info = info.push_next(feature);
146        }
147        if let Some(ref mut feature) = self.robustness2 {
148            info = info.push_next(feature);
149        }
150        if let Some(ref mut feature) = self.multiview {
151            info = info.push_next(feature);
152        }
153        if let Some(ref mut feature) = self.astc_hdr {
154            info = info.push_next(feature);
155        }
156        if let Some(ref mut feature) = self.shader_float16_int8 {
157            info = info.push_next(feature);
158        }
159        if let Some(ref mut feature) = self._16bit_storage {
160            info = info.push_next(feature);
161        }
162        if let Some(ref mut feature) = self.zero_initialize_workgroup_memory {
163            info = info.push_next(feature);
164        }
165        if let Some(ref mut feature) = self.acceleration_structure {
166            info = info.push_next(feature);
167        }
168        if let Some(ref mut feature) = self.buffer_device_address {
169            info = info.push_next(feature);
170        }
171        if let Some(ref mut feature) = self.ray_query {
172            info = info.push_next(feature);
173        }
174        if let Some(ref mut feature) = self.shader_atomic_int64 {
175            info = info.push_next(feature);
176        }
177        if let Some(ref mut feature) = self.position_fetch {
178            info = info.push_next(feature);
179        }
180        if let Some(ref mut feature) = self.shader_image_atomic_int64 {
181            info = info.push_next(feature);
182        }
183        if let Some(ref mut feature) = self.shader_atomic_float {
184            info = info.push_next(feature);
185        }
186        if let Some(ref mut feature) = self.subgroup_size_control {
187            info = info.push_next(feature);
188        }
189        if let Some(ref mut feature) = self.maintenance4 {
190            info = info.push_next(feature);
191        }
192        if let Some(ref mut feature) = self.mesh_shader {
193            info = info.push_next(feature);
194        }
195        if let Some(ref mut feature) = self.shader_integer_dot_product {
196            info = info.push_next(feature);
197        }
198        info
199    }
200
201    /// Create a `PhysicalDeviceFeatures` that can be used to create a logical
202    /// device.
203    ///
204    /// Return a `PhysicalDeviceFeatures` value capturing all the Vulkan
205    /// features needed for the given [`Features`], [`DownlevelFlags`], and
206    /// [`PrivateCapabilities`]. You can use the returned value's
207    /// [`add_to_device_create`] method to configure a
208    /// [`vk::DeviceCreateInfo`] to build a logical device providing those
209    /// features.
210    ///
211    /// To ensure that the returned value is able to select all the Vulkan
212    /// features needed to express `requested_features`, `downlevel_flags`, and
213    /// `private_caps`:
214    ///
215    /// - The given `enabled_extensions` set must include all the extensions
216    ///   selected by [`Adapter::required_device_extensions`] when passed
217    ///   `features`.
218    ///
219    /// - The given `device_api_version` must be the Vulkan API version of the
220    ///   physical device we will use to create the logical device.
221    ///
222    /// [`Features`]: wgt::Features
223    /// [`DownlevelFlags`]: wgt::DownlevelFlags
224    /// [`PrivateCapabilities`]: super::PrivateCapabilities
225    /// [`add_to_device_create`]: PhysicalDeviceFeatures::add_to_device_create
226    /// [`Adapter::required_device_extensions`]: super::Adapter::required_device_extensions
227    fn from_extensions_and_requested_features(
228        phd_capabilities: &PhysicalDeviceProperties,
229        _phd_features: &PhysicalDeviceFeatures,
230        enabled_extensions: &[&'static CStr],
231        requested_features: wgt::Features,
232        downlevel_flags: wgt::DownlevelFlags,
233        private_caps: &super::PrivateCapabilities,
234    ) -> Self {
235        let device_api_version = phd_capabilities.device_api_version;
236        let needs_bindless = requested_features.intersects(
237            wgt::Features::TEXTURE_BINDING_ARRAY
238                | wgt::Features::BUFFER_BINDING_ARRAY
239                | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY
240                | wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING
241                | wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING,
242        );
243        let needs_partially_bound =
244            requested_features.intersects(wgt::Features::PARTIALLY_BOUND_BINDING_ARRAY);
245
246        Self {
247            // vk::PhysicalDeviceFeatures is a struct composed of Bool32's while
248            // Features is a bitfield so we need to map everything manually
249            core: vk::PhysicalDeviceFeatures::default()
250                .robust_buffer_access(private_caps.robust_buffer_access)
251                .independent_blend(downlevel_flags.contains(wgt::DownlevelFlags::INDEPENDENT_BLEND))
252                .sample_rate_shading(
253                    downlevel_flags.contains(wgt::DownlevelFlags::MULTISAMPLED_SHADING),
254                )
255                .image_cube_array(
256                    downlevel_flags.contains(wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES),
257                )
258                .draw_indirect_first_instance(
259                    requested_features.contains(wgt::Features::INDIRECT_FIRST_INSTANCE),
260                )
261                //.dual_src_blend(requested_features.contains(wgt::Features::DUAL_SRC_BLENDING))
262                .multi_draw_indirect(
263                    requested_features.contains(wgt::Features::MULTI_DRAW_INDIRECT),
264                )
265                .fill_mode_non_solid(requested_features.intersects(
266                    wgt::Features::POLYGON_MODE_LINE | wgt::Features::POLYGON_MODE_POINT,
267                ))
268                //.depth_bounds(requested_features.contains(wgt::Features::DEPTH_BOUNDS))
269                //.alpha_to_one(requested_features.contains(wgt::Features::ALPHA_TO_ONE))
270                //.multi_viewport(requested_features.contains(wgt::Features::MULTI_VIEWPORTS))
271                .sampler_anisotropy(
272                    downlevel_flags.contains(wgt::DownlevelFlags::ANISOTROPIC_FILTERING),
273                )
274                .texture_compression_etc2(
275                    requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_ETC2),
276                )
277                .texture_compression_astc_ldr(
278                    requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_ASTC),
279                )
280                .texture_compression_bc(
281                    requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_BC),
282                    // BC provides formats for Sliced 3D
283                )
284                //.occlusion_query_precise(requested_features.contains(wgt::Features::PRECISE_OCCLUSION_QUERY))
285                .pipeline_statistics_query(
286                    requested_features.contains(wgt::Features::PIPELINE_STATISTICS_QUERY),
287                )
288                .vertex_pipeline_stores_and_atomics(
289                    requested_features.contains(wgt::Features::VERTEX_WRITABLE_STORAGE),
290                )
291                .fragment_stores_and_atomics(
292                    downlevel_flags.contains(wgt::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE),
293                )
294                //.shader_image_gather_extended(
295                //.shader_storage_image_extended_formats(
296                .shader_uniform_buffer_array_dynamic_indexing(
297                    requested_features.contains(wgt::Features::BUFFER_BINDING_ARRAY),
298                )
299                .shader_storage_buffer_array_dynamic_indexing(requested_features.contains(
300                    wgt::Features::BUFFER_BINDING_ARRAY
301                        | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY,
302                ))
303                .shader_sampled_image_array_dynamic_indexing(
304                    requested_features.contains(wgt::Features::TEXTURE_BINDING_ARRAY),
305                )
306                .shader_storage_buffer_array_dynamic_indexing(requested_features.contains(
307                    wgt::Features::TEXTURE_BINDING_ARRAY
308                        | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY,
309                ))
310                //.shader_storage_image_array_dynamic_indexing(
311                .shader_clip_distance(requested_features.contains(wgt::Features::CLIP_DISTANCES))
312                //.shader_cull_distance(requested_features.contains(wgt::Features::SHADER_CULL_DISTANCE))
313                .shader_float64(requested_features.contains(wgt::Features::SHADER_F64))
314                .shader_int64(requested_features.contains(wgt::Features::SHADER_INT64))
315                .shader_int16(requested_features.contains(wgt::Features::SHADER_I16))
316                //.shader_resource_residency(requested_features.contains(wgt::Features::SHADER_RESOURCE_RESIDENCY))
317                .geometry_shader(requested_features.contains(wgt::Features::SHADER_PRIMITIVE_INDEX))
318                .depth_clamp(requested_features.contains(wgt::Features::DEPTH_CLIP_CONTROL))
319                .dual_src_blend(requested_features.contains(wgt::Features::DUAL_SOURCE_BLENDING)),
320            descriptor_indexing: if requested_features.intersects(INDEXING_FEATURES) {
321                Some(
322                    vk::PhysicalDeviceDescriptorIndexingFeaturesEXT::default()
323                        .shader_sampled_image_array_non_uniform_indexing(needs_bindless)
324                        .shader_storage_image_array_non_uniform_indexing(needs_bindless)
325                        .shader_storage_buffer_array_non_uniform_indexing(needs_bindless)
326                        .descriptor_binding_sampled_image_update_after_bind(needs_bindless)
327                        .descriptor_binding_storage_image_update_after_bind(needs_bindless)
328                        .descriptor_binding_storage_buffer_update_after_bind(needs_bindless)
329                        .descriptor_binding_partially_bound(needs_partially_bound),
330                )
331            } else {
332                None
333            },
334            timeline_semaphore: if device_api_version >= vk::API_VERSION_1_2
335                || enabled_extensions.contains(&khr::timeline_semaphore::NAME)
336            {
337                Some(
338                    vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR::default()
339                        .timeline_semaphore(private_caps.timeline_semaphores),
340                )
341            } else {
342                None
343            },
344            image_robustness: if device_api_version >= vk::API_VERSION_1_3
345                || enabled_extensions.contains(&ext::image_robustness::NAME)
346            {
347                Some(
348                    vk::PhysicalDeviceImageRobustnessFeaturesEXT::default()
349                        .robust_image_access(private_caps.robust_image_access),
350                )
351            } else {
352                None
353            },
354            robustness2: if enabled_extensions.contains(&ext::robustness2::NAME) {
355                Some(
356                    vk::PhysicalDeviceRobustness2FeaturesEXT::default()
357                        .robust_buffer_access2(private_caps.robust_buffer_access2)
358                        .robust_image_access2(private_caps.robust_image_access2),
359                )
360            } else {
361                None
362            },
363            multiview: if device_api_version >= vk::API_VERSION_1_1
364                || enabled_extensions.contains(&khr::multiview::NAME)
365            {
366                Some(
367                    vk::PhysicalDeviceMultiviewFeatures::default()
368                        .multiview(requested_features.contains(wgt::Features::MULTIVIEW)),
369                )
370            } else {
371                None
372            },
373            sampler_ycbcr_conversion: if device_api_version >= vk::API_VERSION_1_1
374                || enabled_extensions.contains(&khr::sampler_ycbcr_conversion::NAME)
375            {
376                Some(
377                    vk::PhysicalDeviceSamplerYcbcrConversionFeatures::default(), // .sampler_ycbcr_conversion(requested_features.contains(wgt::Features::TEXTURE_FORMAT_NV12))
378                )
379            } else {
380                None
381            },
382            astc_hdr: if enabled_extensions.contains(&ext::texture_compression_astc_hdr::NAME) {
383                Some(
384                    vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT::default()
385                        .texture_compression_astc_hdr(true),
386                )
387            } else {
388                None
389            },
390            shader_float16_int8: match requested_features.contains(wgt::Features::SHADER_F16) {
391                shader_float16 if shader_float16 || private_caps.shader_int8 => Some(
392                    vk::PhysicalDeviceShaderFloat16Int8Features::default()
393                        .shader_float16(shader_float16)
394                        .shader_int8(private_caps.shader_int8),
395                ),
396                _ => None,
397            },
398            _16bit_storage: if requested_features.contains(wgt::Features::SHADER_F16) {
399                Some(
400                    vk::PhysicalDevice16BitStorageFeatures::default()
401                        .storage_buffer16_bit_access(true)
402                        .storage_input_output16(true)
403                        .uniform_and_storage_buffer16_bit_access(true),
404                )
405            } else {
406                None
407            },
408            acceleration_structure: if enabled_extensions
409                .contains(&khr::acceleration_structure::NAME)
410            {
411                Some(
412                    vk::PhysicalDeviceAccelerationStructureFeaturesKHR::default()
413                        .acceleration_structure(true),
414                )
415            } else {
416                None
417            },
418            buffer_device_address: if enabled_extensions.contains(&khr::buffer_device_address::NAME)
419            {
420                Some(
421                    vk::PhysicalDeviceBufferDeviceAddressFeaturesKHR::default()
422                        .buffer_device_address(true),
423                )
424            } else {
425                None
426            },
427            ray_query: if enabled_extensions.contains(&khr::ray_query::NAME) {
428                Some(vk::PhysicalDeviceRayQueryFeaturesKHR::default().ray_query(true))
429            } else {
430                None
431            },
432            zero_initialize_workgroup_memory: if device_api_version >= vk::API_VERSION_1_3
433                || enabled_extensions.contains(&khr::zero_initialize_workgroup_memory::NAME)
434            {
435                Some(
436                    vk::PhysicalDeviceZeroInitializeWorkgroupMemoryFeatures::default()
437                        .shader_zero_initialize_workgroup_memory(
438                            private_caps.zero_initialize_workgroup_memory,
439                        ),
440                )
441            } else {
442                None
443            },
444            shader_atomic_int64: if device_api_version >= vk::API_VERSION_1_2
445                || enabled_extensions.contains(&khr::shader_atomic_int64::NAME)
446            {
447                let needed = requested_features.intersects(
448                    wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS
449                        | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX,
450                );
451                Some(
452                    vk::PhysicalDeviceShaderAtomicInt64Features::default()
453                        .shader_buffer_int64_atomics(needed)
454                        .shader_shared_int64_atomics(needed),
455                )
456            } else {
457                None
458            },
459            shader_image_atomic_int64: if enabled_extensions
460                .contains(&ext::shader_image_atomic_int64::NAME)
461            {
462                let needed = requested_features.intersects(wgt::Features::TEXTURE_INT64_ATOMIC);
463                Some(
464                    vk::PhysicalDeviceShaderImageAtomicInt64FeaturesEXT::default()
465                        .shader_image_int64_atomics(needed),
466                )
467            } else {
468                None
469            },
470            shader_atomic_float: if enabled_extensions.contains(&ext::shader_atomic_float::NAME) {
471                let needed = requested_features.contains(wgt::Features::SHADER_FLOAT32_ATOMIC);
472                Some(
473                    vk::PhysicalDeviceShaderAtomicFloatFeaturesEXT::default()
474                        .shader_buffer_float32_atomics(needed)
475                        .shader_buffer_float32_atomic_add(needed),
476                )
477            } else {
478                None
479            },
480            subgroup_size_control: if device_api_version >= vk::API_VERSION_1_3
481                || enabled_extensions.contains(&ext::subgroup_size_control::NAME)
482            {
483                Some(
484                    vk::PhysicalDeviceSubgroupSizeControlFeatures::default()
485                        .subgroup_size_control(true),
486                )
487            } else {
488                None
489            },
490            position_fetch: if enabled_extensions.contains(&khr::ray_tracing_position_fetch::NAME) {
491                Some(
492                    vk::PhysicalDeviceRayTracingPositionFetchFeaturesKHR::default()
493                        .ray_tracing_position_fetch(true),
494                )
495            } else {
496                None
497            },
498            mesh_shader: if enabled_extensions.contains(&ext::mesh_shader::NAME) {
499                let needed = requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER);
500                let multiview_needed =
501                    requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER_MULTIVIEW);
502                Some(
503                    vk::PhysicalDeviceMeshShaderFeaturesEXT::default()
504                        .mesh_shader(needed)
505                        .task_shader(needed)
506                        .multiview_mesh_shader(multiview_needed),
507                )
508            } else {
509                None
510            },
511            maintenance4: if enabled_extensions.contains(&khr::maintenance4::NAME) {
512                let needed = requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER);
513                Some(vk::PhysicalDeviceMaintenance4FeaturesKHR::default().maintenance4(needed))
514            } else {
515                None
516            },
517            shader_integer_dot_product: if device_api_version >= vk::API_VERSION_1_3
518                || enabled_extensions.contains(&khr::shader_integer_dot_product::NAME)
519            {
520                Some(
521                    vk::PhysicalDeviceShaderIntegerDotProductFeaturesKHR::default()
522                        .shader_integer_dot_product(private_caps.shader_integer_dot_product),
523                )
524            } else {
525                None
526            },
527        }
528    }
529
530    /// Compute the wgpu [`Features`] and [`DownlevelFlags`] supported by a physical device.
531    ///
532    /// Given `self`, together with the instance and physical device it was
533    /// built from, and a `caps` also built from those, determine which wgpu
534    /// features and downlevel flags the device can support.
535    ///
536    /// [`Features`]: wgt::Features
537    /// [`DownlevelFlags`]: wgt::DownlevelFlags
538    fn to_wgpu(
539        &self,
540        instance: &ash::Instance,
541        phd: vk::PhysicalDevice,
542        caps: &PhysicalDeviceProperties,
543    ) -> (wgt::Features, wgt::DownlevelFlags) {
544        use wgt::{DownlevelFlags as Df, Features as F};
545        let mut features = F::empty()
546            | F::SPIRV_SHADER_PASSTHROUGH
547            | F::MAPPABLE_PRIMARY_BUFFERS
548            | F::PUSH_CONSTANTS
549            | F::ADDRESS_MODE_CLAMP_TO_BORDER
550            | F::ADDRESS_MODE_CLAMP_TO_ZERO
551            | F::TIMESTAMP_QUERY
552            | F::TIMESTAMP_QUERY_INSIDE_ENCODERS
553            | F::TIMESTAMP_QUERY_INSIDE_PASSES
554            | F::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES
555            | F::CLEAR_TEXTURE
556            | F::PIPELINE_CACHE
557            | F::SHADER_EARLY_DEPTH_TEST
558            | F::TEXTURE_ATOMIC;
559
560        let mut dl_flags = Df::COMPUTE_SHADERS
561            | Df::BASE_VERTEX
562            | Df::READ_ONLY_DEPTH_STENCIL
563            | Df::NON_POWER_OF_TWO_MIPMAPPED_TEXTURES
564            | Df::COMPARISON_SAMPLERS
565            | Df::VERTEX_STORAGE
566            | Df::FRAGMENT_STORAGE
567            | Df::DEPTH_TEXTURE_AND_BUFFER_COPIES
568            | Df::BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED
569            | Df::UNRESTRICTED_INDEX_BUFFER
570            | Df::INDIRECT_EXECUTION
571            | Df::VIEW_FORMATS
572            | Df::UNRESTRICTED_EXTERNAL_TEXTURE_COPIES
573            | Df::NONBLOCKING_QUERY_RESOLVE;
574
575        dl_flags.set(
576            Df::SURFACE_VIEW_FORMATS,
577            caps.supports_extension(khr::swapchain_mutable_format::NAME),
578        );
579        dl_flags.set(Df::CUBE_ARRAY_TEXTURES, self.core.image_cube_array != 0);
580        dl_flags.set(Df::ANISOTROPIC_FILTERING, self.core.sampler_anisotropy != 0);
581        dl_flags.set(
582            Df::FRAGMENT_WRITABLE_STORAGE,
583            self.core.fragment_stores_and_atomics != 0,
584        );
585        dl_flags.set(Df::MULTISAMPLED_SHADING, self.core.sample_rate_shading != 0);
586        dl_flags.set(Df::INDEPENDENT_BLEND, self.core.independent_blend != 0);
587        dl_flags.set(
588            Df::FULL_DRAW_INDEX_UINT32,
589            self.core.full_draw_index_uint32 != 0,
590        );
591        dl_flags.set(Df::DEPTH_BIAS_CLAMP, self.core.depth_bias_clamp != 0);
592
593        features.set(
594            F::INDIRECT_FIRST_INSTANCE,
595            self.core.draw_indirect_first_instance != 0,
596        );
597        //if self.core.dual_src_blend != 0
598        features.set(F::MULTI_DRAW_INDIRECT, self.core.multi_draw_indirect != 0);
599        features.set(F::POLYGON_MODE_LINE, self.core.fill_mode_non_solid != 0);
600        features.set(F::POLYGON_MODE_POINT, self.core.fill_mode_non_solid != 0);
601        //if self.core.depth_bounds != 0 {
602        //if self.core.alpha_to_one != 0 {
603        //if self.core.multi_viewport != 0 {
604        features.set(
605            F::TEXTURE_COMPRESSION_ETC2,
606            self.core.texture_compression_etc2 != 0,
607        );
608        features.set(
609            F::TEXTURE_COMPRESSION_ASTC,
610            self.core.texture_compression_astc_ldr != 0,
611        );
612        features.set(
613            F::TEXTURE_COMPRESSION_BC,
614            self.core.texture_compression_bc != 0,
615        );
616        features.set(
617            F::TEXTURE_COMPRESSION_BC_SLICED_3D,
618            self.core.texture_compression_bc != 0, // BC guarantees Sliced 3D
619        );
620        features.set(
621            F::PIPELINE_STATISTICS_QUERY,
622            self.core.pipeline_statistics_query != 0,
623        );
624        features.set(
625            F::VERTEX_WRITABLE_STORAGE,
626            self.core.vertex_pipeline_stores_and_atomics != 0,
627        );
628
629        features.set(F::SHADER_F64, self.core.shader_float64 != 0);
630        features.set(F::SHADER_INT64, self.core.shader_int64 != 0);
631        features.set(F::SHADER_I16, self.core.shader_int16 != 0);
632
633        features.set(F::SHADER_PRIMITIVE_INDEX, self.core.geometry_shader != 0);
634
635        if let Some(ref shader_atomic_int64) = self.shader_atomic_int64 {
636            features.set(
637                F::SHADER_INT64_ATOMIC_ALL_OPS | F::SHADER_INT64_ATOMIC_MIN_MAX,
638                shader_atomic_int64.shader_buffer_int64_atomics != 0
639                    && shader_atomic_int64.shader_shared_int64_atomics != 0,
640            );
641        }
642
643        if let Some(ref shader_image_atomic_int64) = self.shader_image_atomic_int64 {
644            features.set(
645                F::TEXTURE_INT64_ATOMIC,
646                shader_image_atomic_int64
647                    .shader_image_int64_atomics(true)
648                    .shader_image_int64_atomics
649                    != 0,
650            );
651        }
652
653        if let Some(ref shader_atomic_float) = self.shader_atomic_float {
654            features.set(
655                F::SHADER_FLOAT32_ATOMIC,
656                shader_atomic_float.shader_buffer_float32_atomics != 0
657                    && shader_atomic_float.shader_buffer_float32_atomic_add != 0,
658            );
659        }
660
661        //if caps.supports_extension(khr::sampler_mirror_clamp_to_edge::NAME) {
662        //if caps.supports_extension(ext::sampler_filter_minmax::NAME) {
663        features.set(
664            F::MULTI_DRAW_INDIRECT_COUNT,
665            caps.supports_extension(khr::draw_indirect_count::NAME),
666        );
667        features.set(
668            F::CONSERVATIVE_RASTERIZATION,
669            caps.supports_extension(ext::conservative_rasterization::NAME),
670        );
671        features.set(
672            F::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN,
673            caps.supports_extension(khr::ray_tracing_position_fetch::NAME),
674        );
675
676        if let Some(ref descriptor_indexing) = self.descriptor_indexing {
677            // We use update-after-bind descriptors for all bind groups containing binding arrays.
678            //
679            // In those bind groups, we allow all binding types except uniform buffers to be present.
680            //
681            // As we can only switch between update-after-bind and not on a per bind group basis,
682            // all supported binding types need to be able to be marked update after bind.
683            //
684            // As such, we enable all features as a whole, rather individually.
685            let supports_descriptor_indexing =
686                // Sampled Images
687                descriptor_indexing.shader_sampled_image_array_non_uniform_indexing != 0
688                    && descriptor_indexing.descriptor_binding_sampled_image_update_after_bind != 0
689                    // Storage Images
690                    && descriptor_indexing.shader_storage_image_array_non_uniform_indexing != 0
691                    && descriptor_indexing.descriptor_binding_storage_image_update_after_bind != 0
692                    // Storage Buffers
693                    && descriptor_indexing.shader_storage_buffer_array_non_uniform_indexing != 0
694                    && descriptor_indexing.descriptor_binding_storage_buffer_update_after_bind != 0;
695
696            let descriptor_indexing_features = F::BUFFER_BINDING_ARRAY
697                | F::TEXTURE_BINDING_ARRAY
698                | F::STORAGE_RESOURCE_BINDING_ARRAY
699                | F::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING
700                | F::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING;
701
702            features.set(descriptor_indexing_features, supports_descriptor_indexing);
703
704            let supports_partially_bound =
705                descriptor_indexing.descriptor_binding_partially_bound != 0;
706
707            features.set(F::PARTIALLY_BOUND_BINDING_ARRAY, supports_partially_bound);
708        }
709
710        features.set(F::DEPTH_CLIP_CONTROL, self.core.depth_clamp != 0);
711        features.set(F::DUAL_SOURCE_BLENDING, self.core.dual_src_blend != 0);
712        features.set(F::CLIP_DISTANCES, self.core.shader_clip_distance != 0);
713
714        if let Some(ref multiview) = self.multiview {
715            features.set(F::MULTIVIEW, multiview.multiview != 0);
716        }
717
718        features.set(
719            F::TEXTURE_FORMAT_16BIT_NORM,
720            is_format_16bit_norm_supported(instance, phd),
721        );
722
723        if let Some(ref astc_hdr) = self.astc_hdr {
724            features.set(
725                F::TEXTURE_COMPRESSION_ASTC_HDR,
726                astc_hdr.texture_compression_astc_hdr != 0,
727            );
728        }
729
730        if self.core.texture_compression_astc_ldr != 0 {
731            features.set(
732                F::TEXTURE_COMPRESSION_ASTC_SLICED_3D,
733                supports_astc_3d(instance, phd),
734            );
735        }
736
737        if let (Some(ref f16_i8), Some(ref bit16)) = (self.shader_float16_int8, self._16bit_storage)
738        {
739            features.set(
740                F::SHADER_F16,
741                f16_i8.shader_float16 != 0
742                    && bit16.storage_buffer16_bit_access != 0
743                    && bit16.uniform_and_storage_buffer16_bit_access != 0
744                    && bit16.storage_input_output16 != 0,
745            );
746        }
747
748        if let Some(ref subgroup) = caps.subgroup {
749            if (caps.device_api_version >= vk::API_VERSION_1_3
750                || caps.supports_extension(ext::subgroup_size_control::NAME))
751                && subgroup.supported_operations.contains(
752                    vk::SubgroupFeatureFlags::BASIC
753                        | vk::SubgroupFeatureFlags::VOTE
754                        | vk::SubgroupFeatureFlags::ARITHMETIC
755                        | vk::SubgroupFeatureFlags::BALLOT
756                        | vk::SubgroupFeatureFlags::SHUFFLE
757                        | vk::SubgroupFeatureFlags::SHUFFLE_RELATIVE
758                        | vk::SubgroupFeatureFlags::QUAD,
759                )
760            {
761                features.set(
762                    F::SUBGROUP,
763                    subgroup
764                        .supported_stages
765                        .contains(vk::ShaderStageFlags::COMPUTE | vk::ShaderStageFlags::FRAGMENT),
766                );
767                features.set(
768                    F::SUBGROUP_VERTEX,
769                    subgroup
770                        .supported_stages
771                        .contains(vk::ShaderStageFlags::VERTEX),
772                );
773                features.insert(F::SUBGROUP_BARRIER);
774            }
775        }
776
777        let supports_depth_format = |format| {
778            supports_format(
779                instance,
780                phd,
781                format,
782                vk::ImageTiling::OPTIMAL,
783                depth_stencil_required_flags(),
784            )
785        };
786
787        let texture_s8 = supports_depth_format(vk::Format::S8_UINT);
788        let texture_d32 = supports_depth_format(vk::Format::D32_SFLOAT);
789        let texture_d24_s8 = supports_depth_format(vk::Format::D24_UNORM_S8_UINT);
790        let texture_d32_s8 = supports_depth_format(vk::Format::D32_SFLOAT_S8_UINT);
791
792        let stencil8 = texture_s8 || texture_d24_s8;
793        let depth24_plus_stencil8 = texture_d24_s8 || texture_d32_s8;
794
795        dl_flags.set(
796            Df::WEBGPU_TEXTURE_FORMAT_SUPPORT,
797            stencil8 && depth24_plus_stencil8 && texture_d32,
798        );
799
800        features.set(F::DEPTH32FLOAT_STENCIL8, texture_d32_s8);
801
802        features.set(
803            F::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE
804                | F::EXTENDED_ACCELERATION_STRUCTURE_VERTEX_FORMATS,
805            caps.supports_extension(khr::deferred_host_operations::NAME)
806                && caps.supports_extension(khr::acceleration_structure::NAME)
807                && caps.supports_extension(khr::buffer_device_address::NAME),
808        );
809
810        features.set(
811            F::EXPERIMENTAL_RAY_QUERY,
812            caps.supports_extension(khr::ray_query::NAME),
813        );
814
815        let rg11b10ufloat_renderable = supports_format(
816            instance,
817            phd,
818            vk::Format::B10G11R11_UFLOAT_PACK32,
819            vk::ImageTiling::OPTIMAL,
820            vk::FormatFeatureFlags::COLOR_ATTACHMENT
821                | vk::FormatFeatureFlags::COLOR_ATTACHMENT_BLEND,
822        );
823        features.set(F::RG11B10UFLOAT_RENDERABLE, rg11b10ufloat_renderable);
824
825        features.set(
826            F::BGRA8UNORM_STORAGE,
827            supports_bgra8unorm_storage(instance, phd, caps.device_api_version),
828        );
829
830        features.set(
831            F::FLOAT32_FILTERABLE,
832            is_float32_filterable_supported(instance, phd),
833        );
834
835        if let Some(ref _sampler_ycbcr_conversion) = self.sampler_ycbcr_conversion {
836            features.set(
837                F::TEXTURE_FORMAT_NV12,
838                supports_format(
839                    instance,
840                    phd,
841                    vk::Format::G8_B8R8_2PLANE_420_UNORM,
842                    vk::ImageTiling::OPTIMAL,
843                    vk::FormatFeatureFlags::SAMPLED_IMAGE
844                        | vk::FormatFeatureFlags::TRANSFER_SRC
845                        | vk::FormatFeatureFlags::TRANSFER_DST,
846                ) && !caps
847                    .driver
848                    .map(|driver| driver.driver_id == vk::DriverId::MOLTENVK)
849                    .unwrap_or_default(),
850            );
851        }
852
853        features.set(
854            F::VULKAN_GOOGLE_DISPLAY_TIMING,
855            caps.supports_extension(google::display_timing::NAME),
856        );
857
858        features.set(
859            F::VULKAN_EXTERNAL_MEMORY_WIN32,
860            caps.supports_extension(khr::external_memory_win32::NAME),
861        );
862        features.set(
863            F::EXPERIMENTAL_MESH_SHADER,
864            caps.supports_extension(ext::mesh_shader::NAME),
865        );
866        if let Some(ref mesh_shader) = self.mesh_shader {
867            features.set(
868                F::EXPERIMENTAL_MESH_SHADER_MULTIVIEW,
869                mesh_shader.multiview_mesh_shader != 0,
870            );
871        }
872        (features, dl_flags)
873    }
874}
875
876/// Vulkan "properties" structures gathered about a physical device.
877///
878/// This structure holds the properties of a [`vk::PhysicalDevice`]:
879/// - the standard Vulkan device properties
880/// - the `VkExtensionProperties` structs for all available extensions, and
881/// - the per-extension properties structures for the available extensions that
882///   `wgpu` cares about.
883///
884/// Generally, if you get it from any of these functions, it's stored
885/// here:
886/// - `vkEnumerateDeviceExtensionProperties`
887/// - `vkGetPhysicalDeviceProperties`
888/// - `vkGetPhysicalDeviceProperties2`
889///
890/// This also includes a copy of the device API version, since we can
891/// use that as a shortcut for searching for an extension, if the
892/// extension has been promoted to core in the current version.
893///
894/// This does not include device features; for those, see
895/// [`PhysicalDeviceFeatures`].
896#[derive(Default, Debug)]
897pub struct PhysicalDeviceProperties {
898    /// Extensions supported by the `vk::PhysicalDevice`,
899    /// as returned by `vkEnumerateDeviceExtensionProperties`.
900    supported_extensions: Vec<vk::ExtensionProperties>,
901
902    /// Properties of the `vk::PhysicalDevice`, as returned by
903    /// `vkGetPhysicalDeviceProperties`.
904    properties: vk::PhysicalDeviceProperties,
905
906    /// Additional `vk::PhysicalDevice` properties from the
907    /// `VK_KHR_maintenance3` extension, promoted to Vulkan 1.1.
908    maintenance_3: Option<vk::PhysicalDeviceMaintenance3Properties<'static>>,
909
910    /// Additional `vk::PhysicalDevice` properties from the
911    /// `VK_EXT_descriptor_indexing` extension, promoted to Vulkan 1.2.
912    descriptor_indexing: Option<vk::PhysicalDeviceDescriptorIndexingPropertiesEXT<'static>>,
913
914    /// Additional `vk::PhysicalDevice` properties from the
915    /// `VK_KHR_acceleration_structure` extension.
916    acceleration_structure: Option<vk::PhysicalDeviceAccelerationStructurePropertiesKHR<'static>>,
917
918    /// Additional `vk::PhysicalDevice` properties from the
919    /// `VK_KHR_driver_properties` extension, promoted to Vulkan 1.2.
920    driver: Option<vk::PhysicalDeviceDriverPropertiesKHR<'static>>,
921
922    /// Additional `vk::PhysicalDevice` properties from Vulkan 1.1.
923    subgroup: Option<vk::PhysicalDeviceSubgroupProperties<'static>>,
924
925    /// Additional `vk::PhysicalDevice` properties from the
926    /// `VK_EXT_subgroup_size_control` extension, promoted to Vulkan 1.3.
927    subgroup_size_control: Option<vk::PhysicalDeviceSubgroupSizeControlProperties<'static>>,
928
929    /// Additional `vk::PhysicalDevice` properties from the
930    /// `VK_EXT_robustness2` extension.
931    robustness2: Option<vk::PhysicalDeviceRobustness2PropertiesEXT<'static>>,
932
933    /// Additional `vk::PhysicalDevice` properties from the
934    /// `VK_EXT_mesh_shader` extension.
935    _mesh_shader: Option<vk::PhysicalDeviceMeshShaderPropertiesEXT<'static>>,
936
937    /// The device API version.
938    ///
939    /// Which is the version of Vulkan supported for device-level functionality.
940    ///
941    /// It is associated with a `VkPhysicalDevice` and its children.
942    device_api_version: u32,
943}
944
945impl PhysicalDeviceProperties {
946    pub fn properties(&self) -> vk::PhysicalDeviceProperties {
947        self.properties
948    }
949
950    pub fn supports_extension(&self, extension: &CStr) -> bool {
951        self.supported_extensions
952            .iter()
953            .any(|ep| ep.extension_name_as_c_str() == Ok(extension))
954    }
955
956    /// Map `requested_features` to the list of Vulkan extension strings required to create the logical device.
957    fn get_required_extensions(&self, requested_features: wgt::Features) -> Vec<&'static CStr> {
958        let mut extensions = Vec::new();
959
960        // Note that quite a few extensions depend on the `VK_KHR_get_physical_device_properties2` instance extension.
961        // We enable `VK_KHR_get_physical_device_properties2` unconditionally (if available).
962
963        // Require `VK_KHR_swapchain`
964        extensions.push(khr::swapchain::NAME);
965
966        if self.device_api_version < vk::API_VERSION_1_1 {
967            // Require `VK_KHR_maintenance1`
968            extensions.push(khr::maintenance1::NAME);
969
970            // Optional `VK_KHR_maintenance2`
971            if self.supports_extension(khr::maintenance2::NAME) {
972                extensions.push(khr::maintenance2::NAME);
973            }
974
975            // Optional `VK_KHR_maintenance3`
976            if self.supports_extension(khr::maintenance3::NAME) {
977                extensions.push(khr::maintenance3::NAME);
978            }
979
980            // Require `VK_KHR_storage_buffer_storage_class`
981            extensions.push(khr::storage_buffer_storage_class::NAME);
982
983            // Require `VK_KHR_multiview` if the associated feature was requested
984            if requested_features.contains(wgt::Features::MULTIVIEW) {
985                extensions.push(khr::multiview::NAME);
986            }
987
988            // Require `VK_KHR_sampler_ycbcr_conversion` if the associated feature was requested
989            if requested_features.contains(wgt::Features::TEXTURE_FORMAT_NV12) {
990                extensions.push(khr::sampler_ycbcr_conversion::NAME);
991            }
992
993            // Require `VK_KHR_16bit_storage` if the feature `SHADER_F16` was requested
994            if requested_features.contains(wgt::Features::SHADER_F16) {
995                // - Feature `SHADER_F16` also requires `VK_KHR_shader_float16_int8`, but we always
996                //   require that anyway (if it is available) below.
997                // - `VK_KHR_16bit_storage` requires `VK_KHR_storage_buffer_storage_class`, however
998                //   we require that one already.
999                extensions.push(khr::_16bit_storage::NAME);
1000            }
1001        }
1002
1003        if self.device_api_version < vk::API_VERSION_1_2 {
1004            // Optional `VK_KHR_image_format_list`
1005            if self.supports_extension(khr::image_format_list::NAME) {
1006                extensions.push(khr::image_format_list::NAME);
1007            }
1008
1009            // Optional `VK_KHR_driver_properties`
1010            if self.supports_extension(khr::driver_properties::NAME) {
1011                extensions.push(khr::driver_properties::NAME);
1012            }
1013
1014            // Optional `VK_KHR_timeline_semaphore`
1015            if self.supports_extension(khr::timeline_semaphore::NAME) {
1016                extensions.push(khr::timeline_semaphore::NAME);
1017            }
1018
1019            // Require `VK_EXT_descriptor_indexing` if one of the associated features was requested
1020            if requested_features.intersects(INDEXING_FEATURES) {
1021                extensions.push(ext::descriptor_indexing::NAME);
1022            }
1023
1024            // Always require `VK_KHR_shader_float16_int8` if available as it enables
1025            // Int8 optimizations. Also require it even if it's not available but
1026            // requested so that we get a corresponding error message.
1027            if requested_features.contains(wgt::Features::SHADER_F16)
1028                || self.supports_extension(khr::shader_float16_int8::NAME)
1029            {
1030                extensions.push(khr::shader_float16_int8::NAME);
1031            }
1032
1033            if requested_features.intersects(wgt::Features::EXPERIMENTAL_MESH_SHADER) {
1034                extensions.push(khr::spirv_1_4::NAME);
1035            }
1036
1037            //extensions.push(khr::sampler_mirror_clamp_to_edge::NAME);
1038            //extensions.push(ext::sampler_filter_minmax::NAME);
1039        }
1040
1041        if self.device_api_version < vk::API_VERSION_1_3 {
1042            // Optional `VK_EXT_image_robustness`
1043            if self.supports_extension(ext::image_robustness::NAME) {
1044                extensions.push(ext::image_robustness::NAME);
1045            }
1046
1047            // Require `VK_EXT_subgroup_size_control` if the associated feature was requested
1048            if requested_features.contains(wgt::Features::SUBGROUP) {
1049                extensions.push(ext::subgroup_size_control::NAME);
1050            }
1051
1052            if requested_features.intersects(wgt::Features::EXPERIMENTAL_MESH_SHADER) {
1053                extensions.push(khr::maintenance4::NAME);
1054            }
1055
1056            // Optional `VK_KHR_shader_integer_dot_product`
1057            if self.supports_extension(khr::shader_integer_dot_product::NAME) {
1058                extensions.push(khr::shader_integer_dot_product::NAME);
1059            }
1060        }
1061
1062        // Optional `VK_KHR_swapchain_mutable_format`
1063        if self.supports_extension(khr::swapchain_mutable_format::NAME) {
1064            extensions.push(khr::swapchain_mutable_format::NAME);
1065        }
1066
1067        // Optional `VK_EXT_robustness2`
1068        if self.supports_extension(ext::robustness2::NAME) {
1069            extensions.push(ext::robustness2::NAME);
1070        }
1071
1072        // Optional `VK_KHR_external_memory_win32`
1073        if self.supports_extension(khr::external_memory_win32::NAME) {
1074            extensions.push(khr::external_memory_win32::NAME);
1075        }
1076
1077        // Optional `VK_KHR_external_memory_fd`
1078        if self.supports_extension(khr::external_memory_fd::NAME) {
1079            extensions.push(khr::external_memory_fd::NAME);
1080        }
1081
1082        // Optional `VK_EXT_external_memory_dma`
1083        if self.supports_extension(ext::external_memory_dma_buf::NAME) {
1084            extensions.push(ext::external_memory_dma_buf::NAME);
1085        }
1086
1087        // Optional `VK_EXT_memory_budget`
1088        if self.supports_extension(ext::memory_budget::NAME) {
1089            extensions.push(ext::memory_budget::NAME);
1090        } else {
1091            log::warn!("VK_EXT_memory_budget is not available.")
1092        }
1093
1094        // Require `VK_KHR_draw_indirect_count` if the associated feature was requested
1095        // Even though Vulkan 1.2 has promoted the extension to core, we must require the extension to avoid
1096        // large amounts of spaghetti involved with using PhysicalDeviceVulkan12Features.
1097        if requested_features.contains(wgt::Features::MULTI_DRAW_INDIRECT_COUNT) {
1098            extensions.push(khr::draw_indirect_count::NAME);
1099        }
1100
1101        // Require `VK_KHR_deferred_host_operations`, `VK_KHR_acceleration_structure` and `VK_KHR_buffer_device_address` if the feature `RAY_TRACING` was requested
1102        if requested_features
1103            .contains(wgt::Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE)
1104        {
1105            extensions.push(khr::deferred_host_operations::NAME);
1106            extensions.push(khr::acceleration_structure::NAME);
1107            extensions.push(khr::buffer_device_address::NAME);
1108        }
1109
1110        // Require `VK_KHR_ray_query` if the associated feature was requested
1111        if requested_features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) {
1112            extensions.push(khr::ray_query::NAME);
1113        }
1114
1115        if requested_features.contains(wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN) {
1116            extensions.push(khr::ray_tracing_position_fetch::NAME)
1117        }
1118
1119        // Require `VK_EXT_conservative_rasterization` if the associated feature was requested
1120        if requested_features.contains(wgt::Features::CONSERVATIVE_RASTERIZATION) {
1121            extensions.push(ext::conservative_rasterization::NAME);
1122        }
1123
1124        // Require `VK_KHR_portability_subset` on macOS/iOS
1125        #[cfg(target_vendor = "apple")]
1126        extensions.push(khr::portability_subset::NAME);
1127
1128        // Require `VK_EXT_texture_compression_astc_hdr` if the associated feature was requested
1129        if requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_ASTC_HDR) {
1130            extensions.push(ext::texture_compression_astc_hdr::NAME);
1131        }
1132
1133        // Require `VK_KHR_shader_atomic_int64` if the associated feature was requested
1134        if requested_features.intersects(
1135            wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX,
1136        ) {
1137            extensions.push(khr::shader_atomic_int64::NAME);
1138        }
1139
1140        // Require `VK_EXT_shader_image_atomic_int64` if the associated feature was requested
1141        if requested_features.intersects(wgt::Features::TEXTURE_INT64_ATOMIC) {
1142            extensions.push(ext::shader_image_atomic_int64::NAME);
1143        }
1144
1145        // Require `VK_EXT_shader_atomic_float` if the associated feature was requested
1146        if requested_features.contains(wgt::Features::SHADER_FLOAT32_ATOMIC) {
1147            extensions.push(ext::shader_atomic_float::NAME);
1148        }
1149
1150        // Require VK_GOOGLE_display_timing if the associated feature was requested
1151        if requested_features.contains(wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING) {
1152            extensions.push(google::display_timing::NAME);
1153        }
1154
1155        if requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER) {
1156            extensions.push(ext::mesh_shader::NAME);
1157        }
1158
1159        extensions
1160    }
1161
1162    fn to_wgpu_limits(&self) -> wgt::Limits {
1163        let limits = &self.properties.limits;
1164
1165        let max_compute_workgroup_sizes = limits.max_compute_work_group_size;
1166        let max_compute_workgroups_per_dimension = limits.max_compute_work_group_count[0]
1167            .min(limits.max_compute_work_group_count[1])
1168            .min(limits.max_compute_work_group_count[2]);
1169
1170        // Prevent very large buffers on mesa and most android devices.
1171        let is_nvidia = self.properties.vendor_id == crate::auxil::db::nvidia::VENDOR;
1172        let max_buffer_size =
1173            if (cfg!(target_os = "linux") || cfg!(target_os = "android")) && !is_nvidia {
1174                i32::MAX as u64
1175            } else {
1176                u64::MAX
1177            };
1178
1179        let mut max_binding_array_elements = 0;
1180        let mut max_sampler_binding_array_elements = 0;
1181        if let Some(ref descriptor_indexing) = self.descriptor_indexing {
1182            max_binding_array_elements = descriptor_indexing
1183                .max_descriptor_set_update_after_bind_sampled_images
1184                .min(descriptor_indexing.max_descriptor_set_update_after_bind_storage_images)
1185                .min(descriptor_indexing.max_descriptor_set_update_after_bind_storage_buffers)
1186                .min(descriptor_indexing.max_per_stage_descriptor_update_after_bind_sampled_images)
1187                .min(descriptor_indexing.max_per_stage_descriptor_update_after_bind_storage_images)
1188                .min(
1189                    descriptor_indexing.max_per_stage_descriptor_update_after_bind_storage_buffers,
1190                );
1191
1192            max_sampler_binding_array_elements = descriptor_indexing
1193                .max_descriptor_set_update_after_bind_samplers
1194                .min(descriptor_indexing.max_per_stage_descriptor_update_after_bind_samplers);
1195        }
1196
1197        // TODO: programmatically determine this, if possible. It's unclear whether we can
1198        // as of https://github.com/gpuweb/gpuweb/issues/2965#issuecomment-1361315447.
1199        //
1200        // In theory some tilers may not support this much. We can't tell however, and
1201        // the driver will throw a DEVICE_REMOVED if it goes too high in usage. This is fine.
1202        //
1203        // 16 bytes per sample is the maximum size for a color attachment.
1204        let max_color_attachment_bytes_per_sample =
1205            limits.max_color_attachments * wgt::TextureFormat::MAX_TARGET_PIXEL_BYTE_COST;
1206
1207        let mut max_blas_geometry_count = 0;
1208        let mut max_blas_primitive_count = 0;
1209        let mut max_tlas_instance_count = 0;
1210        let mut max_acceleration_structures_per_shader_stage = 0;
1211        if let Some(properties) = self.acceleration_structure {
1212            max_blas_geometry_count = properties.max_geometry_count as u32;
1213            max_blas_primitive_count = properties.max_primitive_count as u32;
1214            max_tlas_instance_count = properties.max_instance_count as u32;
1215            max_acceleration_structures_per_shader_stage =
1216                properties.max_per_stage_descriptor_acceleration_structures;
1217        }
1218
1219        wgt::Limits {
1220            max_texture_dimension_1d: limits.max_image_dimension1_d,
1221            max_texture_dimension_2d: limits.max_image_dimension2_d,
1222            max_texture_dimension_3d: limits.max_image_dimension3_d,
1223            max_texture_array_layers: limits.max_image_array_layers,
1224            max_bind_groups: limits
1225                .max_bound_descriptor_sets
1226                .min(crate::MAX_BIND_GROUPS as u32),
1227            max_bindings_per_bind_group: wgt::Limits::default().max_bindings_per_bind_group,
1228            max_dynamic_uniform_buffers_per_pipeline_layout: limits
1229                .max_descriptor_set_uniform_buffers_dynamic,
1230            max_dynamic_storage_buffers_per_pipeline_layout: limits
1231                .max_descriptor_set_storage_buffers_dynamic,
1232            max_sampled_textures_per_shader_stage: limits.max_per_stage_descriptor_sampled_images,
1233            max_samplers_per_shader_stage: limits.max_per_stage_descriptor_samplers,
1234            max_storage_buffers_per_shader_stage: limits.max_per_stage_descriptor_storage_buffers,
1235            max_storage_textures_per_shader_stage: limits.max_per_stage_descriptor_storage_images,
1236            max_uniform_buffers_per_shader_stage: limits.max_per_stage_descriptor_uniform_buffers,
1237            max_binding_array_elements_per_shader_stage: max_binding_array_elements,
1238            max_binding_array_sampler_elements_per_shader_stage: max_sampler_binding_array_elements,
1239            max_uniform_buffer_binding_size: limits
1240                .max_uniform_buffer_range
1241                .min(crate::auxil::MAX_I32_BINDING_SIZE),
1242            max_storage_buffer_binding_size: limits
1243                .max_storage_buffer_range
1244                .min(crate::auxil::MAX_I32_BINDING_SIZE),
1245            max_vertex_buffers: limits
1246                .max_vertex_input_bindings
1247                .min(crate::MAX_VERTEX_BUFFERS as u32),
1248            max_vertex_attributes: limits.max_vertex_input_attributes,
1249            max_vertex_buffer_array_stride: limits.max_vertex_input_binding_stride,
1250            min_subgroup_size: self
1251                .subgroup_size_control
1252                .map(|subgroup_size| subgroup_size.min_subgroup_size)
1253                .unwrap_or(0),
1254            max_subgroup_size: self
1255                .subgroup_size_control
1256                .map(|subgroup_size| subgroup_size.max_subgroup_size)
1257                .unwrap_or(0),
1258            max_push_constant_size: limits.max_push_constants_size,
1259            min_uniform_buffer_offset_alignment: limits.min_uniform_buffer_offset_alignment as u32,
1260            min_storage_buffer_offset_alignment: limits.min_storage_buffer_offset_alignment as u32,
1261            max_inter_stage_shader_components: limits
1262                .max_vertex_output_components
1263                .min(limits.max_fragment_input_components),
1264            max_color_attachments: limits
1265                .max_color_attachments
1266                .min(crate::MAX_COLOR_ATTACHMENTS as u32),
1267            max_color_attachment_bytes_per_sample,
1268            max_compute_workgroup_storage_size: limits.max_compute_shared_memory_size,
1269            max_compute_invocations_per_workgroup: limits.max_compute_work_group_invocations,
1270            max_compute_workgroup_size_x: max_compute_workgroup_sizes[0],
1271            max_compute_workgroup_size_y: max_compute_workgroup_sizes[1],
1272            max_compute_workgroup_size_z: max_compute_workgroup_sizes[2],
1273            max_compute_workgroups_per_dimension,
1274            max_buffer_size,
1275            max_non_sampler_bindings: u32::MAX,
1276            max_blas_primitive_count,
1277            max_blas_geometry_count,
1278            max_tlas_instance_count,
1279            max_acceleration_structures_per_shader_stage,
1280        }
1281    }
1282
1283    /// Return a `wgpu_hal::Alignments` structure describing this adapter.
1284    ///
1285    /// The `using_robustness2` argument says how this adapter will implement
1286    /// `wgpu_hal`'s guarantee that shaders can only read the [accessible
1287    /// region][ar] of bindgroup's buffer bindings:
1288    ///
1289    /// - If this adapter will depend on `VK_EXT_robustness2`'s
1290    ///   `robustBufferAccess2` feature to apply bounds checks to shader buffer
1291    ///   access, `using_robustness2` must be `true`.
1292    ///
1293    /// - Otherwise, this adapter must use Naga to inject bounds checks on
1294    ///   buffer accesses, and `using_robustness2` must be `false`.
1295    ///
1296    /// [ar]: ../../struct.BufferBinding.html#accessible-region
1297    fn to_hal_alignments(&self, using_robustness2: bool) -> crate::Alignments {
1298        let limits = &self.properties.limits;
1299        crate::Alignments {
1300            buffer_copy_offset: wgt::BufferSize::new(limits.optimal_buffer_copy_offset_alignment)
1301                .unwrap(),
1302            buffer_copy_pitch: wgt::BufferSize::new(limits.optimal_buffer_copy_row_pitch_alignment)
1303                .unwrap(),
1304            uniform_bounds_check_alignment: {
1305                let alignment = if using_robustness2 {
1306                    self.robustness2
1307                        .unwrap() // if we're using it, we should have its properties
1308                        .robust_uniform_buffer_access_size_alignment
1309                } else {
1310                    // If the `robustness2` properties are unavailable, then `robustness2` is not available either Naga-injected bounds checks are precise.
1311                    1
1312                };
1313                wgt::BufferSize::new(alignment).unwrap()
1314            },
1315            raw_tlas_instance_size: 64,
1316            ray_tracing_scratch_buffer_alignment: self.acceleration_structure.map_or(
1317                0,
1318                |acceleration_structure| {
1319                    acceleration_structure.min_acceleration_structure_scratch_offset_alignment
1320                },
1321            ),
1322        }
1323    }
1324}
1325
1326impl super::InstanceShared {
1327    fn inspect(
1328        &self,
1329        phd: vk::PhysicalDevice,
1330    ) -> (PhysicalDeviceProperties, PhysicalDeviceFeatures) {
1331        let capabilities = {
1332            let mut capabilities = PhysicalDeviceProperties::default();
1333            capabilities.supported_extensions =
1334                unsafe { self.raw.enumerate_device_extension_properties(phd).unwrap() };
1335            capabilities.properties = unsafe { self.raw.get_physical_device_properties(phd) };
1336            capabilities.device_api_version = capabilities.properties.api_version;
1337
1338            if let Some(ref get_device_properties) = self.get_physical_device_properties {
1339                // Get these now to avoid borrowing conflicts later
1340                let supports_maintenance3 = capabilities.device_api_version >= vk::API_VERSION_1_1
1341                    || capabilities.supports_extension(khr::maintenance3::NAME);
1342                let supports_descriptor_indexing = capabilities.device_api_version
1343                    >= vk::API_VERSION_1_2
1344                    || capabilities.supports_extension(ext::descriptor_indexing::NAME);
1345                let supports_driver_properties = capabilities.device_api_version
1346                    >= vk::API_VERSION_1_2
1347                    || capabilities.supports_extension(khr::driver_properties::NAME);
1348                let supports_subgroup_size_control = capabilities.device_api_version
1349                    >= vk::API_VERSION_1_3
1350                    || capabilities.supports_extension(ext::subgroup_size_control::NAME);
1351                let supports_robustness2 = capabilities.supports_extension(ext::robustness2::NAME);
1352
1353                let supports_acceleration_structure =
1354                    capabilities.supports_extension(khr::acceleration_structure::NAME);
1355
1356                let supports_mesh_shader = capabilities.supports_extension(ext::mesh_shader::NAME);
1357
1358                let mut properties2 = vk::PhysicalDeviceProperties2KHR::default();
1359                if supports_maintenance3 {
1360                    let next = capabilities
1361                        .maintenance_3
1362                        .insert(vk::PhysicalDeviceMaintenance3Properties::default());
1363                    properties2 = properties2.push_next(next);
1364                }
1365
1366                if supports_descriptor_indexing {
1367                    let next = capabilities
1368                        .descriptor_indexing
1369                        .insert(vk::PhysicalDeviceDescriptorIndexingPropertiesEXT::default());
1370                    properties2 = properties2.push_next(next);
1371                }
1372
1373                if supports_acceleration_structure {
1374                    let next = capabilities
1375                        .acceleration_structure
1376                        .insert(vk::PhysicalDeviceAccelerationStructurePropertiesKHR::default());
1377                    properties2 = properties2.push_next(next);
1378                }
1379
1380                if supports_driver_properties {
1381                    let next = capabilities
1382                        .driver
1383                        .insert(vk::PhysicalDeviceDriverPropertiesKHR::default());
1384                    properties2 = properties2.push_next(next);
1385                }
1386
1387                if capabilities.device_api_version >= vk::API_VERSION_1_1 {
1388                    let next = capabilities
1389                        .subgroup
1390                        .insert(vk::PhysicalDeviceSubgroupProperties::default());
1391                    properties2 = properties2.push_next(next);
1392                }
1393
1394                if supports_subgroup_size_control {
1395                    let next = capabilities
1396                        .subgroup_size_control
1397                        .insert(vk::PhysicalDeviceSubgroupSizeControlProperties::default());
1398                    properties2 = properties2.push_next(next);
1399                }
1400
1401                if supports_robustness2 {
1402                    let next = capabilities
1403                        .robustness2
1404                        .insert(vk::PhysicalDeviceRobustness2PropertiesEXT::default());
1405                    properties2 = properties2.push_next(next);
1406                }
1407
1408                if supports_mesh_shader {
1409                    let next = capabilities
1410                        ._mesh_shader
1411                        .insert(vk::PhysicalDeviceMeshShaderPropertiesEXT::default());
1412                    properties2 = properties2.push_next(next);
1413                }
1414
1415                unsafe {
1416                    get_device_properties.get_physical_device_properties2(phd, &mut properties2)
1417                };
1418
1419                if is_intel_igpu_outdated_for_robustness2(
1420                    capabilities.properties,
1421                    capabilities.driver,
1422                ) {
1423                    capabilities
1424                        .supported_extensions
1425                        .retain(|&x| x.extension_name_as_c_str() != Ok(ext::robustness2::NAME));
1426                    capabilities.robustness2 = None;
1427                }
1428            };
1429            capabilities
1430        };
1431
1432        let mut features = PhysicalDeviceFeatures::default();
1433        features.core = if let Some(ref get_device_properties) = self.get_physical_device_properties
1434        {
1435            let core = vk::PhysicalDeviceFeatures::default();
1436            let mut features2 = vk::PhysicalDeviceFeatures2KHR::default().features(core);
1437
1438            // `VK_KHR_multiview` is promoted to 1.1
1439            if capabilities.device_api_version >= vk::API_VERSION_1_1
1440                || capabilities.supports_extension(khr::multiview::NAME)
1441            {
1442                let next = features
1443                    .multiview
1444                    .insert(vk::PhysicalDeviceMultiviewFeatures::default());
1445                features2 = features2.push_next(next);
1446            }
1447
1448            // `VK_KHR_sampler_ycbcr_conversion` is promoted to 1.1
1449            if capabilities.device_api_version >= vk::API_VERSION_1_1
1450                || capabilities.supports_extension(khr::sampler_ycbcr_conversion::NAME)
1451            {
1452                let next = features
1453                    .sampler_ycbcr_conversion
1454                    .insert(vk::PhysicalDeviceSamplerYcbcrConversionFeatures::default());
1455                features2 = features2.push_next(next);
1456            }
1457
1458            if capabilities.supports_extension(ext::descriptor_indexing::NAME) {
1459                let next = features
1460                    .descriptor_indexing
1461                    .insert(vk::PhysicalDeviceDescriptorIndexingFeaturesEXT::default());
1462                features2 = features2.push_next(next);
1463            }
1464
1465            // `VK_KHR_timeline_semaphore` is promoted to 1.2, but has no
1466            // changes, so we can keep using the extension unconditionally.
1467            if capabilities.supports_extension(khr::timeline_semaphore::NAME) {
1468                let next = features
1469                    .timeline_semaphore
1470                    .insert(vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR::default());
1471                features2 = features2.push_next(next);
1472            }
1473
1474            // `VK_KHR_shader_atomic_int64` is promoted to 1.2, but has no
1475            // changes, so we can keep using the extension unconditionally.
1476            if capabilities.device_api_version >= vk::API_VERSION_1_2
1477                || capabilities.supports_extension(khr::shader_atomic_int64::NAME)
1478            {
1479                let next = features
1480                    .shader_atomic_int64
1481                    .insert(vk::PhysicalDeviceShaderAtomicInt64Features::default());
1482                features2 = features2.push_next(next);
1483            }
1484
1485            if capabilities.supports_extension(ext::shader_image_atomic_int64::NAME) {
1486                let next = features
1487                    .shader_image_atomic_int64
1488                    .insert(vk::PhysicalDeviceShaderImageAtomicInt64FeaturesEXT::default());
1489                features2 = features2.push_next(next);
1490            }
1491            if capabilities.supports_extension(ext::shader_atomic_float::NAME) {
1492                let next = features
1493                    .shader_atomic_float
1494                    .insert(vk::PhysicalDeviceShaderAtomicFloatFeaturesEXT::default());
1495                features2 = features2.push_next(next);
1496            }
1497            if capabilities.supports_extension(ext::image_robustness::NAME) {
1498                let next = features
1499                    .image_robustness
1500                    .insert(vk::PhysicalDeviceImageRobustnessFeaturesEXT::default());
1501                features2 = features2.push_next(next);
1502            }
1503            if capabilities.supports_extension(ext::robustness2::NAME) {
1504                let next = features
1505                    .robustness2
1506                    .insert(vk::PhysicalDeviceRobustness2FeaturesEXT::default());
1507                features2 = features2.push_next(next);
1508            }
1509            if capabilities.supports_extension(ext::texture_compression_astc_hdr::NAME) {
1510                let next = features
1511                    .astc_hdr
1512                    .insert(vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT::default());
1513                features2 = features2.push_next(next);
1514            }
1515
1516            // `VK_KHR_shader_float16_int8` is promoted to 1.2
1517            if capabilities.device_api_version >= vk::API_VERSION_1_2
1518                || capabilities.supports_extension(khr::shader_float16_int8::NAME)
1519            {
1520                let next = features
1521                    .shader_float16_int8
1522                    .insert(vk::PhysicalDeviceShaderFloat16Int8FeaturesKHR::default());
1523                features2 = features2.push_next(next);
1524            }
1525
1526            if capabilities.supports_extension(khr::_16bit_storage::NAME) {
1527                let next = features
1528                    ._16bit_storage
1529                    .insert(vk::PhysicalDevice16BitStorageFeaturesKHR::default());
1530                features2 = features2.push_next(next);
1531            }
1532            if capabilities.supports_extension(khr::acceleration_structure::NAME) {
1533                let next = features
1534                    .acceleration_structure
1535                    .insert(vk::PhysicalDeviceAccelerationStructureFeaturesKHR::default());
1536                features2 = features2.push_next(next);
1537            }
1538
1539            if capabilities.supports_extension(khr::ray_tracing_position_fetch::NAME) {
1540                let next = features
1541                    .position_fetch
1542                    .insert(vk::PhysicalDeviceRayTracingPositionFetchFeaturesKHR::default());
1543                features2 = features2.push_next(next);
1544            }
1545
1546            // `VK_KHR_zero_initialize_workgroup_memory` is promoted to 1.3
1547            if capabilities.device_api_version >= vk::API_VERSION_1_3
1548                || capabilities.supports_extension(khr::zero_initialize_workgroup_memory::NAME)
1549            {
1550                let next = features
1551                    .zero_initialize_workgroup_memory
1552                    .insert(vk::PhysicalDeviceZeroInitializeWorkgroupMemoryFeatures::default());
1553                features2 = features2.push_next(next);
1554            }
1555
1556            // `VK_EXT_subgroup_size_control` is promoted to 1.3
1557            if capabilities.device_api_version >= vk::API_VERSION_1_3
1558                || capabilities.supports_extension(ext::subgroup_size_control::NAME)
1559            {
1560                let next = features
1561                    .subgroup_size_control
1562                    .insert(vk::PhysicalDeviceSubgroupSizeControlFeatures::default());
1563                features2 = features2.push_next(next);
1564            }
1565
1566            if capabilities.supports_extension(ext::mesh_shader::NAME) {
1567                let next = features
1568                    .mesh_shader
1569                    .insert(vk::PhysicalDeviceMeshShaderFeaturesEXT::default());
1570                features2 = features2.push_next(next);
1571            }
1572
1573            // `VK_KHR_shader_integer_dot_product` is promoted to 1.3
1574            if capabilities.device_api_version >= vk::API_VERSION_1_3
1575                || capabilities.supports_extension(khr::shader_integer_dot_product::NAME)
1576            {
1577                let next = features
1578                    .shader_integer_dot_product
1579                    .insert(vk::PhysicalDeviceShaderIntegerDotProductFeatures::default());
1580                features2 = features2.push_next(next);
1581            }
1582
1583            unsafe { get_device_properties.get_physical_device_features2(phd, &mut features2) };
1584            features2.features
1585        } else {
1586            unsafe { self.raw.get_physical_device_features(phd) }
1587        };
1588
1589        (capabilities, features)
1590    }
1591}
1592
1593impl super::Instance {
1594    pub fn expose_adapter(
1595        &self,
1596        phd: vk::PhysicalDevice,
1597    ) -> Option<crate::ExposedAdapter<super::Api>> {
1598        use crate::auxil::db;
1599
1600        let (phd_capabilities, phd_features) = self.shared.inspect(phd);
1601
1602        let info = wgt::AdapterInfo {
1603            name: {
1604                phd_capabilities
1605                    .properties
1606                    .device_name_as_c_str()
1607                    .ok()
1608                    .and_then(|name| name.to_str().ok())
1609                    .unwrap_or("?")
1610                    .to_owned()
1611            },
1612            vendor: phd_capabilities.properties.vendor_id,
1613            device: phd_capabilities.properties.device_id,
1614            device_type: match phd_capabilities.properties.device_type {
1615                vk::PhysicalDeviceType::OTHER => wgt::DeviceType::Other,
1616                vk::PhysicalDeviceType::INTEGRATED_GPU => wgt::DeviceType::IntegratedGpu,
1617                vk::PhysicalDeviceType::DISCRETE_GPU => wgt::DeviceType::DiscreteGpu,
1618                vk::PhysicalDeviceType::VIRTUAL_GPU => wgt::DeviceType::VirtualGpu,
1619                vk::PhysicalDeviceType::CPU => wgt::DeviceType::Cpu,
1620                _ => wgt::DeviceType::Other,
1621            },
1622            driver: {
1623                phd_capabilities
1624                    .driver
1625                    .as_ref()
1626                    .and_then(|driver| driver.driver_name_as_c_str().ok())
1627                    .and_then(|name| name.to_str().ok())
1628                    .unwrap_or("?")
1629                    .to_owned()
1630            },
1631            driver_info: {
1632                phd_capabilities
1633                    .driver
1634                    .as_ref()
1635                    .and_then(|driver| driver.driver_info_as_c_str().ok())
1636                    .and_then(|name| name.to_str().ok())
1637                    .unwrap_or("?")
1638                    .to_owned()
1639            },
1640            backend: wgt::Backend::Vulkan,
1641        };
1642        let (available_features, downlevel_flags) =
1643            phd_features.to_wgpu(&self.shared.raw, phd, &phd_capabilities);
1644        let mut workarounds = super::Workarounds::empty();
1645        {
1646            // TODO: only enable for particular devices
1647            workarounds |= super::Workarounds::SEPARATE_ENTRY_POINTS;
1648            workarounds.set(
1649                super::Workarounds::EMPTY_RESOLVE_ATTACHMENT_LISTS,
1650                phd_capabilities.properties.vendor_id == db::qualcomm::VENDOR,
1651            );
1652            workarounds.set(
1653                super::Workarounds::FORCE_FILL_BUFFER_WITH_SIZE_GREATER_4096_ALIGNED_OFFSET_16,
1654                phd_capabilities.properties.vendor_id == db::nvidia::VENDOR,
1655            );
1656        };
1657
1658        if let Some(driver) = phd_capabilities.driver {
1659            if driver.conformance_version.major == 0 {
1660                if driver.driver_id == vk::DriverId::MOLTENVK {
1661                    log::debug!("Adapter is not Vulkan compliant, but is MoltenVK, continuing");
1662                } else if self
1663                    .shared
1664                    .flags
1665                    .contains(wgt::InstanceFlags::ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER)
1666                {
1667                    log::warn!("Adapter is not Vulkan compliant: {}", info.name);
1668                } else {
1669                    log::warn!(
1670                        "Adapter is not Vulkan compliant, hiding adapter: {}",
1671                        info.name
1672                    );
1673                    return None;
1674                }
1675            }
1676        }
1677        if phd_capabilities.device_api_version == vk::API_VERSION_1_0
1678            && !phd_capabilities.supports_extension(khr::storage_buffer_storage_class::NAME)
1679        {
1680            log::warn!(
1681                "SPIR-V storage buffer class is not supported, hiding adapter: {}",
1682                info.name
1683            );
1684            return None;
1685        }
1686        if !phd_capabilities.supports_extension(khr::maintenance1::NAME)
1687            && phd_capabilities.device_api_version < vk::API_VERSION_1_1
1688        {
1689            log::warn!(
1690                "VK_KHR_maintenance1 is not supported, hiding adapter: {}",
1691                info.name
1692            );
1693            return None;
1694        }
1695
1696        let queue_families = unsafe {
1697            self.shared
1698                .raw
1699                .get_physical_device_queue_family_properties(phd)
1700        };
1701        let queue_flags = queue_families.first()?.queue_flags;
1702        if !queue_flags.contains(vk::QueueFlags::GRAPHICS) {
1703            log::warn!("The first queue only exposes {:?}", queue_flags);
1704            return None;
1705        }
1706
1707        let private_caps = super::PrivateCapabilities {
1708            image_view_usage: phd_capabilities.device_api_version >= vk::API_VERSION_1_1
1709                || phd_capabilities.supports_extension(khr::maintenance2::NAME),
1710            timeline_semaphores: match phd_features.timeline_semaphore {
1711                Some(features) => features.timeline_semaphore == vk::TRUE,
1712                None => phd_features
1713                    .timeline_semaphore
1714                    .is_some_and(|ext| ext.timeline_semaphore != 0),
1715            },
1716            texture_d24: supports_format(
1717                &self.shared.raw,
1718                phd,
1719                vk::Format::X8_D24_UNORM_PACK32,
1720                vk::ImageTiling::OPTIMAL,
1721                depth_stencil_required_flags(),
1722            ),
1723            texture_d24_s8: supports_format(
1724                &self.shared.raw,
1725                phd,
1726                vk::Format::D24_UNORM_S8_UINT,
1727                vk::ImageTiling::OPTIMAL,
1728                depth_stencil_required_flags(),
1729            ),
1730            texture_s8: supports_format(
1731                &self.shared.raw,
1732                phd,
1733                vk::Format::S8_UINT,
1734                vk::ImageTiling::OPTIMAL,
1735                depth_stencil_required_flags(),
1736            ),
1737            non_coherent_map_mask: phd_capabilities.properties.limits.non_coherent_atom_size - 1,
1738            can_present: true,
1739            //TODO: make configurable
1740            robust_buffer_access: phd_features.core.robust_buffer_access != 0,
1741            robust_image_access: match phd_features.robustness2 {
1742                Some(ref f) => f.robust_image_access2 != 0,
1743                None => phd_features
1744                    .image_robustness
1745                    .is_some_and(|ext| ext.robust_image_access != 0),
1746            },
1747            robust_buffer_access2: phd_features
1748                .robustness2
1749                .as_ref()
1750                .map(|r| r.robust_buffer_access2 == 1)
1751                .unwrap_or_default(),
1752            robust_image_access2: phd_features
1753                .robustness2
1754                .as_ref()
1755                .map(|r| r.robust_image_access2 == 1)
1756                .unwrap_or_default(),
1757            zero_initialize_workgroup_memory: phd_features
1758                .zero_initialize_workgroup_memory
1759                .is_some_and(|ext| ext.shader_zero_initialize_workgroup_memory == vk::TRUE),
1760            image_format_list: phd_capabilities.device_api_version >= vk::API_VERSION_1_2
1761                || phd_capabilities.supports_extension(khr::image_format_list::NAME),
1762            maximum_samplers: phd_capabilities
1763                .properties
1764                .limits
1765                .max_sampler_allocation_count,
1766            shader_integer_dot_product: phd_features
1767                .shader_integer_dot_product
1768                .is_some_and(|ext| ext.shader_integer_dot_product != 0),
1769            shader_int8: phd_features
1770                .shader_float16_int8
1771                .is_some_and(|features| features.shader_int8 != 0),
1772        };
1773        let capabilities = crate::Capabilities {
1774            limits: phd_capabilities.to_wgpu_limits(),
1775            alignments: phd_capabilities.to_hal_alignments(private_caps.robust_buffer_access2),
1776            downlevel: wgt::DownlevelCapabilities {
1777                flags: downlevel_flags,
1778                limits: wgt::DownlevelLimits {},
1779                shader_model: wgt::ShaderModel::Sm5, //TODO?
1780            },
1781        };
1782
1783        let adapter = super::Adapter {
1784            raw: phd,
1785            instance: Arc::clone(&self.shared),
1786            //queue_families,
1787            known_memory_flags: vk::MemoryPropertyFlags::DEVICE_LOCAL
1788                | vk::MemoryPropertyFlags::HOST_VISIBLE
1789                | vk::MemoryPropertyFlags::HOST_COHERENT
1790                | vk::MemoryPropertyFlags::HOST_CACHED
1791                | vk::MemoryPropertyFlags::LAZILY_ALLOCATED,
1792            phd_capabilities,
1793            phd_features,
1794            downlevel_flags,
1795            private_caps,
1796            workarounds,
1797        };
1798
1799        Some(crate::ExposedAdapter {
1800            adapter,
1801            info,
1802            features: available_features,
1803            capabilities,
1804        })
1805    }
1806}
1807
1808impl super::Adapter {
1809    pub fn raw_physical_device(&self) -> vk::PhysicalDevice {
1810        self.raw
1811    }
1812
1813    pub fn physical_device_capabilities(&self) -> &PhysicalDeviceProperties {
1814        &self.phd_capabilities
1815    }
1816
1817    pub fn shared_instance(&self) -> &super::InstanceShared {
1818        &self.instance
1819    }
1820
1821    pub fn required_device_extensions(&self, features: wgt::Features) -> Vec<&'static CStr> {
1822        let (supported_extensions, unsupported_extensions) = self
1823            .phd_capabilities
1824            .get_required_extensions(features)
1825            .iter()
1826            .partition::<Vec<&CStr>, _>(|&&extension| {
1827                self.phd_capabilities.supports_extension(extension)
1828            });
1829
1830        if !unsupported_extensions.is_empty() {
1831            log::warn!("Missing extensions: {:?}", unsupported_extensions);
1832        }
1833
1834        log::debug!("Supported extensions: {:?}", supported_extensions);
1835        supported_extensions
1836    }
1837
1838    /// Create a `PhysicalDeviceFeatures` for opening a logical device with
1839    /// `features` from this adapter.
1840    ///
1841    /// The given `enabled_extensions` set must include all the extensions
1842    /// selected by [`required_device_extensions`] when passed `features`.
1843    /// Otherwise, the `PhysicalDeviceFeatures` value may not be able to select
1844    /// all the Vulkan features needed to represent `features` and this
1845    /// adapter's characteristics.
1846    ///
1847    /// Typically, you'd simply call `required_device_extensions`, and then pass
1848    /// its return value and the feature set you gave it directly to this
1849    /// function. But it's fine to add more extensions to the list.
1850    ///
1851    /// [`required_device_extensions`]: Self::required_device_extensions
1852    pub fn physical_device_features(
1853        &self,
1854        enabled_extensions: &[&'static CStr],
1855        features: wgt::Features,
1856    ) -> PhysicalDeviceFeatures {
1857        PhysicalDeviceFeatures::from_extensions_and_requested_features(
1858            &self.phd_capabilities,
1859            &self.phd_features,
1860            enabled_extensions,
1861            features,
1862            self.downlevel_flags,
1863            &self.private_caps,
1864        )
1865    }
1866
1867    /// # Safety
1868    ///
1869    /// - `raw_device` must be created from this adapter.
1870    /// - `raw_device` must be created using `family_index`, `enabled_extensions` and `physical_device_features()`
1871    /// - `enabled_extensions` must be a superset of `required_device_extensions()`.
1872    /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of `raw_device`. If
1873    ///   `drop_callback` is [`Some`], `raw_device` must be valid until the callback is called.
1874    #[allow(clippy::too_many_arguments)]
1875    pub unsafe fn device_from_raw(
1876        &self,
1877        raw_device: ash::Device,
1878        drop_callback: Option<crate::DropCallback>,
1879        enabled_extensions: &[&'static CStr],
1880        features: wgt::Features,
1881        memory_hints: &wgt::MemoryHints,
1882        family_index: u32,
1883        queue_index: u32,
1884    ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> {
1885        let mem_properties = {
1886            profiling::scope!("vkGetPhysicalDeviceMemoryProperties");
1887            unsafe {
1888                self.instance
1889                    .raw
1890                    .get_physical_device_memory_properties(self.raw)
1891            }
1892        };
1893        let memory_types = &mem_properties.memory_types_as_slice();
1894        let valid_ash_memory_types = memory_types.iter().enumerate().fold(0, |u, (i, mem)| {
1895            if self.known_memory_flags.contains(mem.property_flags) {
1896                u | (1 << i)
1897            } else {
1898                u
1899            }
1900        });
1901
1902        let swapchain_fn = khr::swapchain::Device::new(&self.instance.raw, &raw_device);
1903
1904        // Note that VK_EXT_debug_utils is an instance extension (enabled at the instance
1905        // level) but contains a few functions that can be loaded directly on the Device for a
1906        // dispatch-table-less pointer.
1907        let debug_utils_fn = if self.instance.extensions.contains(&ext::debug_utils::NAME) {
1908            Some(ext::debug_utils::Device::new(
1909                &self.instance.raw,
1910                &raw_device,
1911            ))
1912        } else {
1913            None
1914        };
1915        let indirect_count_fn = if enabled_extensions.contains(&khr::draw_indirect_count::NAME) {
1916            Some(khr::draw_indirect_count::Device::new(
1917                &self.instance.raw,
1918                &raw_device,
1919            ))
1920        } else {
1921            None
1922        };
1923        let timeline_semaphore_fn = if enabled_extensions.contains(&khr::timeline_semaphore::NAME) {
1924            Some(super::ExtensionFn::Extension(
1925                khr::timeline_semaphore::Device::new(&self.instance.raw, &raw_device),
1926            ))
1927        } else if self.phd_capabilities.device_api_version >= vk::API_VERSION_1_2 {
1928            Some(super::ExtensionFn::Promoted)
1929        } else {
1930            None
1931        };
1932        let ray_tracing_fns = if enabled_extensions.contains(&khr::acceleration_structure::NAME)
1933            && enabled_extensions.contains(&khr::buffer_device_address::NAME)
1934        {
1935            Some(super::RayTracingDeviceExtensionFunctions {
1936                acceleration_structure: khr::acceleration_structure::Device::new(
1937                    &self.instance.raw,
1938                    &raw_device,
1939                ),
1940                buffer_device_address: khr::buffer_device_address::Device::new(
1941                    &self.instance.raw,
1942                    &raw_device,
1943                ),
1944            })
1945        } else {
1946            None
1947        };
1948        let mesh_shading_fns = if enabled_extensions.contains(&ext::mesh_shader::NAME) {
1949            Some(ext::mesh_shader::Device::new(
1950                &self.instance.raw,
1951                &raw_device,
1952            ))
1953        } else {
1954            None
1955        };
1956
1957        let naga_options = {
1958            use naga::back::spv;
1959
1960            // The following capabilities are always available
1961            // see https://registry.khronos.org/vulkan/specs/1.3-extensions/html/chap52.html#spirvenv-capabilities
1962            let mut capabilities = vec![
1963                spv::Capability::Shader,
1964                spv::Capability::Matrix,
1965                spv::Capability::Sampled1D,
1966                spv::Capability::Image1D,
1967                spv::Capability::ImageQuery,
1968                spv::Capability::DerivativeControl,
1969                spv::Capability::StorageImageExtendedFormats,
1970            ];
1971
1972            if self
1973                .downlevel_flags
1974                .contains(wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES)
1975            {
1976                capabilities.push(spv::Capability::SampledCubeArray);
1977            }
1978
1979            if self
1980                .downlevel_flags
1981                .contains(wgt::DownlevelFlags::MULTISAMPLED_SHADING)
1982            {
1983                capabilities.push(spv::Capability::SampleRateShading);
1984            }
1985
1986            if features.contains(wgt::Features::MULTIVIEW) {
1987                capabilities.push(spv::Capability::MultiView);
1988            }
1989
1990            if features.contains(wgt::Features::SHADER_PRIMITIVE_INDEX) {
1991                capabilities.push(spv::Capability::Geometry);
1992            }
1993
1994            if features.intersects(wgt::Features::SUBGROUP | wgt::Features::SUBGROUP_VERTEX) {
1995                capabilities.push(spv::Capability::GroupNonUniform);
1996                capabilities.push(spv::Capability::GroupNonUniformVote);
1997                capabilities.push(spv::Capability::GroupNonUniformArithmetic);
1998                capabilities.push(spv::Capability::GroupNonUniformBallot);
1999                capabilities.push(spv::Capability::GroupNonUniformShuffle);
2000                capabilities.push(spv::Capability::GroupNonUniformShuffleRelative);
2001                capabilities.push(spv::Capability::GroupNonUniformQuad);
2002            }
2003
2004            if features.intersects(
2005                wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING
2006                    | wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING
2007                    | wgt::Features::UNIFORM_BUFFER_BINDING_ARRAYS,
2008            ) {
2009                capabilities.push(spv::Capability::ShaderNonUniform);
2010            }
2011            if features.contains(wgt::Features::BGRA8UNORM_STORAGE) {
2012                capabilities.push(spv::Capability::StorageImageWriteWithoutFormat);
2013            }
2014
2015            if features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) {
2016                capabilities.push(spv::Capability::RayQueryKHR);
2017            }
2018
2019            if features.contains(wgt::Features::SHADER_INT64) {
2020                capabilities.push(spv::Capability::Int64);
2021            }
2022
2023            if features.contains(wgt::Features::SHADER_F16) {
2024                capabilities.push(spv::Capability::Float16);
2025            }
2026
2027            if features.intersects(
2028                wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS
2029                    | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX
2030                    | wgt::Features::TEXTURE_INT64_ATOMIC,
2031            ) {
2032                capabilities.push(spv::Capability::Int64Atomics);
2033            }
2034
2035            if features.intersects(wgt::Features::TEXTURE_INT64_ATOMIC) {
2036                capabilities.push(spv::Capability::Int64ImageEXT);
2037            }
2038
2039            if features.contains(wgt::Features::SHADER_FLOAT32_ATOMIC) {
2040                capabilities.push(spv::Capability::AtomicFloat32AddEXT);
2041            }
2042
2043            if features.contains(wgt::Features::CLIP_DISTANCES) {
2044                capabilities.push(spv::Capability::ClipDistance);
2045            }
2046
2047            let mut flags = spv::WriterFlags::empty();
2048            flags.set(
2049                spv::WriterFlags::DEBUG,
2050                self.instance.flags.contains(wgt::InstanceFlags::DEBUG),
2051            );
2052            flags.set(
2053                spv::WriterFlags::LABEL_VARYINGS,
2054                self.phd_capabilities.properties.vendor_id != crate::auxil::db::qualcomm::VENDOR,
2055            );
2056            flags.set(
2057                spv::WriterFlags::FORCE_POINT_SIZE,
2058                //Note: we could technically disable this when we are compiling separate entry points,
2059                // and we know exactly that the primitive topology is not `PointList`.
2060                // But this requires cloning the `spv::Options` struct, which has heap allocations.
2061                true, // could check `super::Workarounds::SEPARATE_ENTRY_POINTS`
2062            );
2063            if features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) {
2064                capabilities.push(spv::Capability::RayQueryKHR);
2065            }
2066            if features.contains(wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN) {
2067                capabilities.push(spv::Capability::RayQueryPositionFetchKHR)
2068            }
2069            if self.private_caps.shader_integer_dot_product {
2070                // See <https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_shader_integer_dot_product.html#_new_spir_v_capabilities>.
2071                capabilities.extend(&[
2072                    spv::Capability::DotProductInputAllKHR,
2073                    spv::Capability::DotProductInput4x8BitKHR,
2074                    spv::Capability::DotProductInput4x8BitPackedKHR,
2075                    spv::Capability::DotProductKHR,
2076                ]);
2077            }
2078            if self.private_caps.shader_int8 {
2079                // See <https://registry.khronos.org/vulkan/specs/latest/man/html/VkPhysicalDeviceShaderFloat16Int8Features.html#extension-features-shaderInt8>.
2080                capabilities.extend(&[spv::Capability::Int8]);
2081            }
2082            spv::Options {
2083                lang_version: match self.phd_capabilities.device_api_version {
2084                    // Use maximum supported SPIR-V version according to
2085                    // <https://github.com/KhronosGroup/Vulkan-Docs/blob/19b7651/appendices/spirvenv.adoc?plain=1#L21-L40>.
2086                    vk::API_VERSION_1_0..vk::API_VERSION_1_1 => (1, 0),
2087                    vk::API_VERSION_1_1..vk::API_VERSION_1_2 => (1, 3),
2088                    vk::API_VERSION_1_2..vk::API_VERSION_1_3 => (1, 5),
2089                    vk::API_VERSION_1_3.. => (1, 6),
2090                    _ => unreachable!(),
2091                },
2092                flags,
2093                capabilities: Some(capabilities.iter().cloned().collect()),
2094                bounds_check_policies: naga::proc::BoundsCheckPolicies {
2095                    index: naga::proc::BoundsCheckPolicy::Restrict,
2096                    buffer: if self.private_caps.robust_buffer_access2 {
2097                        naga::proc::BoundsCheckPolicy::Unchecked
2098                    } else {
2099                        naga::proc::BoundsCheckPolicy::Restrict
2100                    },
2101                    image_load: if self.private_caps.robust_image_access {
2102                        naga::proc::BoundsCheckPolicy::Unchecked
2103                    } else {
2104                        naga::proc::BoundsCheckPolicy::Restrict
2105                    },
2106                    // TODO: support bounds checks on binding arrays
2107                    binding_array: naga::proc::BoundsCheckPolicy::Unchecked,
2108                },
2109                zero_initialize_workgroup_memory: if self
2110                    .private_caps
2111                    .zero_initialize_workgroup_memory
2112                {
2113                    spv::ZeroInitializeWorkgroupMemoryMode::Native
2114                } else {
2115                    spv::ZeroInitializeWorkgroupMemoryMode::Polyfill
2116                },
2117                force_loop_bounding: true,
2118                // We need to build this separately for each invocation, so just default it out here
2119                binding_map: BTreeMap::default(),
2120                debug_info: None,
2121            }
2122        };
2123
2124        let raw_queue = {
2125            profiling::scope!("vkGetDeviceQueue");
2126            unsafe { raw_device.get_device_queue(family_index, queue_index) }
2127        };
2128
2129        let driver_version = self
2130            .phd_capabilities
2131            .properties
2132            .driver_version
2133            .to_be_bytes();
2134        #[rustfmt::skip]
2135        let pipeline_cache_validation_key = [
2136            driver_version[0], driver_version[1], driver_version[2], driver_version[3],
2137            0, 0, 0, 0,
2138            0, 0, 0, 0,
2139            0, 0, 0, 0,
2140        ];
2141
2142        let drop_guard = crate::DropGuard::from_option(drop_callback);
2143
2144        let shared = Arc::new(super::DeviceShared {
2145            raw: raw_device,
2146            family_index,
2147            queue_index,
2148            raw_queue,
2149            drop_guard,
2150            instance: Arc::clone(&self.instance),
2151            physical_device: self.raw,
2152            enabled_extensions: enabled_extensions.into(),
2153            extension_fns: super::DeviceExtensionFunctions {
2154                debug_utils: debug_utils_fn,
2155                draw_indirect_count: indirect_count_fn,
2156                timeline_semaphore: timeline_semaphore_fn,
2157                ray_tracing: ray_tracing_fns,
2158                mesh_shading: mesh_shading_fns,
2159            },
2160            pipeline_cache_validation_key,
2161            vendor_id: self.phd_capabilities.properties.vendor_id,
2162            timestamp_period: self.phd_capabilities.properties.limits.timestamp_period,
2163            private_caps: self.private_caps.clone(),
2164            features,
2165            workarounds: self.workarounds,
2166            render_passes: Mutex::new(Default::default()),
2167            sampler_cache: Mutex::new(super::sampler::SamplerCache::new(
2168                self.private_caps.maximum_samplers,
2169            )),
2170            memory_allocations_counter: Default::default(),
2171
2172            texture_identity_factory: super::ResourceIdentityFactory::new(),
2173            texture_view_identity_factory: super::ResourceIdentityFactory::new(),
2174        });
2175
2176        let relay_semaphores = super::RelaySemaphores::new(&shared)?;
2177
2178        let queue = super::Queue {
2179            raw: raw_queue,
2180            swapchain_fn,
2181            device: Arc::clone(&shared),
2182            family_index,
2183            relay_semaphores: Mutex::new(relay_semaphores),
2184            signal_semaphores: Default::default(),
2185        };
2186
2187        let mem_allocator = {
2188            let limits = self.phd_capabilities.properties.limits;
2189
2190            // Note: the parameters here are not set in stone nor where they picked with
2191            // strong confidence.
2192            // `final_free_list_chunk` should be bigger than starting_free_list_chunk if
2193            // we want the behavior of starting with smaller block sizes and using larger
2194            // ones only after we observe that the small ones aren't enough, which I think
2195            // is a good "I don't know what the workload is going to be like" approach.
2196            //
2197            // For reference, `VMA`, and `gpu_allocator` both start with 256 MB blocks
2198            // (then VMA doubles the block size each time it needs a new block).
2199            // At some point it would be good to experiment with real workloads
2200            //
2201            // TODO(#5925): The plan is to switch the Vulkan backend from `gpu_alloc` to
2202            // `gpu_allocator` which has a different (simpler) set of configuration options.
2203            //
2204            // TODO: These parameters should take hardware capabilities into account.
2205            let mb = 1024 * 1024;
2206            let perf_cfg = gpu_alloc::Config {
2207                starting_free_list_chunk: 128 * mb,
2208                final_free_list_chunk: 512 * mb,
2209                minimal_buddy_size: 1,
2210                initial_buddy_dedicated_size: 8 * mb,
2211                dedicated_threshold: 32 * mb,
2212                preferred_dedicated_threshold: mb,
2213                transient_dedicated_threshold: 128 * mb,
2214            };
2215            let mem_usage_cfg = gpu_alloc::Config {
2216                starting_free_list_chunk: 8 * mb,
2217                final_free_list_chunk: 64 * mb,
2218                minimal_buddy_size: 1,
2219                initial_buddy_dedicated_size: 8 * mb,
2220                dedicated_threshold: 8 * mb,
2221                preferred_dedicated_threshold: mb,
2222                transient_dedicated_threshold: 16 * mb,
2223            };
2224            let config = match memory_hints {
2225                wgt::MemoryHints::Performance => perf_cfg,
2226                wgt::MemoryHints::MemoryUsage => mem_usage_cfg,
2227                wgt::MemoryHints::Manual {
2228                    suballocated_device_memory_block_size,
2229                } => gpu_alloc::Config {
2230                    starting_free_list_chunk: suballocated_device_memory_block_size.start,
2231                    final_free_list_chunk: suballocated_device_memory_block_size.end,
2232                    initial_buddy_dedicated_size: suballocated_device_memory_block_size.start,
2233                    ..perf_cfg
2234                },
2235            };
2236
2237            let max_memory_allocation_size =
2238                if let Some(maintenance_3) = self.phd_capabilities.maintenance_3 {
2239                    maintenance_3.max_memory_allocation_size
2240                } else {
2241                    u64::MAX
2242                };
2243            let properties = gpu_alloc::DeviceProperties {
2244                max_memory_allocation_count: limits.max_memory_allocation_count,
2245                max_memory_allocation_size,
2246                non_coherent_atom_size: limits.non_coherent_atom_size,
2247                memory_types: memory_types
2248                    .iter()
2249                    .map(|memory_type| gpu_alloc::MemoryType {
2250                        props: gpu_alloc::MemoryPropertyFlags::from_bits_truncate(
2251                            memory_type.property_flags.as_raw() as u8,
2252                        ),
2253                        heap: memory_type.heap_index,
2254                    })
2255                    .collect(),
2256                memory_heaps: mem_properties
2257                    .memory_heaps_as_slice()
2258                    .iter()
2259                    .map(|&memory_heap| gpu_alloc::MemoryHeap {
2260                        size: memory_heap.size,
2261                    })
2262                    .collect(),
2263                buffer_device_address: enabled_extensions
2264                    .contains(&khr::buffer_device_address::NAME),
2265            };
2266            gpu_alloc::GpuAllocator::new(config, properties)
2267        };
2268        let desc_allocator = gpu_descriptor::DescriptorAllocator::new(
2269            if let Some(di) = self.phd_capabilities.descriptor_indexing {
2270                di.max_update_after_bind_descriptors_in_all_pools
2271            } else {
2272                0
2273            },
2274        );
2275
2276        let device = super::Device {
2277            shared,
2278            mem_allocator: Mutex::new(mem_allocator),
2279            desc_allocator: Mutex::new(desc_allocator),
2280            valid_ash_memory_types,
2281            naga_options,
2282            #[cfg(feature = "renderdoc")]
2283            render_doc: Default::default(),
2284            counters: Default::default(),
2285        };
2286
2287        Ok(crate::OpenDevice { device, queue })
2288    }
2289
2290    pub fn texture_format_as_raw(&self, texture_format: wgt::TextureFormat) -> vk::Format {
2291        self.private_caps.map_texture_format(texture_format)
2292    }
2293
2294    /// # Safety:
2295    /// - Same as `open` plus
2296    /// - The callback may not change anything that the device does not support.
2297    /// - The callback may not remove features.
2298    pub unsafe fn open_with_callback<'a>(
2299        &self,
2300        features: wgt::Features,
2301        memory_hints: &wgt::MemoryHints,
2302        callback: Option<Box<super::CreateDeviceCallback<'a>>>,
2303    ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> {
2304        let mut enabled_extensions = self.required_device_extensions(features);
2305        let mut enabled_phd_features = self.physical_device_features(&enabled_extensions, features);
2306
2307        let family_index = 0; //TODO
2308        let family_info = vk::DeviceQueueCreateInfo::default()
2309            .queue_family_index(family_index)
2310            .queue_priorities(&[1.0]);
2311        let mut family_infos = Vec::from([family_info]);
2312
2313        let mut pre_info = vk::DeviceCreateInfo::default();
2314
2315        if let Some(callback) = callback {
2316            callback(super::CreateDeviceCallbackArgs {
2317                extensions: &mut enabled_extensions,
2318                device_features: &mut enabled_phd_features,
2319                queue_create_infos: &mut family_infos,
2320                create_info: &mut pre_info,
2321                _phantom: PhantomData,
2322            })
2323        }
2324
2325        let str_pointers = enabled_extensions
2326            .iter()
2327            .map(|&s| {
2328                // Safe because `enabled_extensions` entries have static lifetime.
2329                s.as_ptr()
2330            })
2331            .collect::<Vec<_>>();
2332
2333        let pre_info = pre_info
2334            .queue_create_infos(&family_infos)
2335            .enabled_extension_names(&str_pointers);
2336        let info = enabled_phd_features.add_to_device_create(pre_info);
2337        let raw_device = {
2338            profiling::scope!("vkCreateDevice");
2339            unsafe {
2340                self.instance
2341                    .raw
2342                    .create_device(self.raw, &info, None)
2343                    .map_err(map_err)?
2344            }
2345        };
2346        fn map_err(err: vk::Result) -> crate::DeviceError {
2347            match err {
2348                vk::Result::ERROR_TOO_MANY_OBJECTS => crate::DeviceError::OutOfMemory,
2349                vk::Result::ERROR_INITIALIZATION_FAILED => crate::DeviceError::Lost,
2350                vk::Result::ERROR_EXTENSION_NOT_PRESENT | vk::Result::ERROR_FEATURE_NOT_PRESENT => {
2351                    crate::hal_usage_error(err)
2352                }
2353                other => super::map_host_device_oom_and_lost_err(other),
2354            }
2355        }
2356
2357        unsafe {
2358            self.device_from_raw(
2359                raw_device,
2360                None,
2361                &enabled_extensions,
2362                features,
2363                memory_hints,
2364                family_info.queue_family_index,
2365                0,
2366            )
2367        }
2368    }
2369}
2370
2371impl crate::Adapter for super::Adapter {
2372    type A = super::Api;
2373
2374    unsafe fn open(
2375        &self,
2376        features: wgt::Features,
2377        _limits: &wgt::Limits,
2378        memory_hints: &wgt::MemoryHints,
2379    ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> {
2380        unsafe { self.open_with_callback(features, memory_hints, None) }
2381    }
2382
2383    unsafe fn texture_format_capabilities(
2384        &self,
2385        format: wgt::TextureFormat,
2386    ) -> crate::TextureFormatCapabilities {
2387        use crate::TextureFormatCapabilities as Tfc;
2388
2389        let vk_format = self.private_caps.map_texture_format(format);
2390        let properties = unsafe {
2391            self.instance
2392                .raw
2393                .get_physical_device_format_properties(self.raw, vk_format)
2394        };
2395        let features = properties.optimal_tiling_features;
2396
2397        let mut flags = Tfc::empty();
2398        flags.set(
2399            Tfc::SAMPLED,
2400            features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE),
2401        );
2402        flags.set(
2403            Tfc::SAMPLED_LINEAR,
2404            features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_LINEAR),
2405        );
2406        // flags.set(
2407        //     Tfc::SAMPLED_MINMAX,
2408        //     features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_MINMAX),
2409        // );
2410        flags.set(
2411            Tfc::STORAGE_READ_WRITE
2412                | Tfc::STORAGE_WRITE_ONLY
2413                | Tfc::STORAGE_READ_ONLY
2414                | Tfc::STORAGE_ATOMIC,
2415            features.contains(vk::FormatFeatureFlags::STORAGE_IMAGE),
2416        );
2417        flags.set(
2418            Tfc::STORAGE_ATOMIC,
2419            features.contains(vk::FormatFeatureFlags::STORAGE_IMAGE_ATOMIC),
2420        );
2421        flags.set(
2422            Tfc::COLOR_ATTACHMENT,
2423            features.contains(vk::FormatFeatureFlags::COLOR_ATTACHMENT),
2424        );
2425        flags.set(
2426            Tfc::COLOR_ATTACHMENT_BLEND,
2427            features.contains(vk::FormatFeatureFlags::COLOR_ATTACHMENT_BLEND),
2428        );
2429        flags.set(
2430            Tfc::DEPTH_STENCIL_ATTACHMENT,
2431            features.contains(vk::FormatFeatureFlags::DEPTH_STENCIL_ATTACHMENT),
2432        );
2433        flags.set(
2434            Tfc::COPY_SRC,
2435            features.intersects(vk::FormatFeatureFlags::TRANSFER_SRC),
2436        );
2437        flags.set(
2438            Tfc::COPY_DST,
2439            features.intersects(vk::FormatFeatureFlags::TRANSFER_DST),
2440        );
2441        flags.set(
2442            Tfc::STORAGE_ATOMIC,
2443            features.intersects(vk::FormatFeatureFlags::STORAGE_IMAGE_ATOMIC),
2444        );
2445        // Vulkan is very permissive about MSAA
2446        flags.set(Tfc::MULTISAMPLE_RESOLVE, !format.is_compressed());
2447
2448        // get the supported sample counts
2449        let format_aspect = crate::FormatAspects::from(format);
2450        let limits = self.phd_capabilities.properties.limits;
2451
2452        let sample_flags = if format_aspect.contains(crate::FormatAspects::DEPTH) {
2453            limits
2454                .framebuffer_depth_sample_counts
2455                .min(limits.sampled_image_depth_sample_counts)
2456        } else if format_aspect.contains(crate::FormatAspects::STENCIL) {
2457            limits
2458                .framebuffer_stencil_sample_counts
2459                .min(limits.sampled_image_stencil_sample_counts)
2460        } else {
2461            let first_aspect = format_aspect
2462                .iter()
2463                .next()
2464                .expect("All texture should at least one aspect")
2465                .map();
2466
2467            // We should never get depth or stencil out of this, due to the above.
2468            assert_ne!(first_aspect, wgt::TextureAspect::DepthOnly);
2469            assert_ne!(first_aspect, wgt::TextureAspect::StencilOnly);
2470
2471            match format.sample_type(Some(first_aspect), None).unwrap() {
2472                wgt::TextureSampleType::Float { .. } => limits
2473                    .framebuffer_color_sample_counts
2474                    .min(limits.sampled_image_color_sample_counts),
2475                wgt::TextureSampleType::Sint | wgt::TextureSampleType::Uint => {
2476                    limits.sampled_image_integer_sample_counts
2477                }
2478                _ => unreachable!(),
2479            }
2480        };
2481
2482        flags.set(
2483            Tfc::MULTISAMPLE_X2,
2484            sample_flags.contains(vk::SampleCountFlags::TYPE_2),
2485        );
2486        flags.set(
2487            Tfc::MULTISAMPLE_X4,
2488            sample_flags.contains(vk::SampleCountFlags::TYPE_4),
2489        );
2490        flags.set(
2491            Tfc::MULTISAMPLE_X8,
2492            sample_flags.contains(vk::SampleCountFlags::TYPE_8),
2493        );
2494        flags.set(
2495            Tfc::MULTISAMPLE_X16,
2496            sample_flags.contains(vk::SampleCountFlags::TYPE_16),
2497        );
2498
2499        flags
2500    }
2501
2502    unsafe fn surface_capabilities(
2503        &self,
2504        surface: &super::Surface,
2505    ) -> Option<crate::SurfaceCapabilities> {
2506        if !self.private_caps.can_present {
2507            return None;
2508        }
2509        let queue_family_index = 0; //TODO
2510        {
2511            profiling::scope!("vkGetPhysicalDeviceSurfaceSupportKHR");
2512            match unsafe {
2513                surface.functor.get_physical_device_surface_support(
2514                    self.raw,
2515                    queue_family_index,
2516                    surface.raw,
2517                )
2518            } {
2519                Ok(true) => (),
2520                Ok(false) => return None,
2521                Err(e) => {
2522                    log::error!("get_physical_device_surface_support: {}", e);
2523                    return None;
2524                }
2525            }
2526        }
2527
2528        let caps = {
2529            profiling::scope!("vkGetPhysicalDeviceSurfaceCapabilitiesKHR");
2530            match unsafe {
2531                surface
2532                    .functor
2533                    .get_physical_device_surface_capabilities(self.raw, surface.raw)
2534            } {
2535                Ok(caps) => caps,
2536                Err(e) => {
2537                    log::error!("get_physical_device_surface_capabilities: {}", e);
2538                    return None;
2539                }
2540            }
2541        };
2542
2543        // If image count is 0, the support number of images is unlimited.
2544        let max_image_count = if caps.max_image_count == 0 {
2545            !0
2546        } else {
2547            caps.max_image_count
2548        };
2549
2550        // `0xFFFFFFFF` indicates that the extent depends on the created swapchain.
2551        let current_extent = if caps.current_extent.width != !0 && caps.current_extent.height != !0
2552        {
2553            Some(wgt::Extent3d {
2554                width: caps.current_extent.width,
2555                height: caps.current_extent.height,
2556                depth_or_array_layers: 1,
2557            })
2558        } else {
2559            None
2560        };
2561
2562        let raw_present_modes = {
2563            profiling::scope!("vkGetPhysicalDeviceSurfacePresentModesKHR");
2564            match unsafe {
2565                surface
2566                    .functor
2567                    .get_physical_device_surface_present_modes(self.raw, surface.raw)
2568            } {
2569                Ok(present_modes) => present_modes,
2570                Err(e) => {
2571                    log::error!("get_physical_device_surface_present_modes: {}", e);
2572                    // Per definition of `SurfaceCapabilities`, there must be at least one present mode.
2573                    return None;
2574                }
2575            }
2576        };
2577
2578        let raw_surface_formats = {
2579            profiling::scope!("vkGetPhysicalDeviceSurfaceFormatsKHR");
2580            match unsafe {
2581                surface
2582                    .functor
2583                    .get_physical_device_surface_formats(self.raw, surface.raw)
2584            } {
2585                Ok(formats) => formats,
2586                Err(e) => {
2587                    log::error!("get_physical_device_surface_formats: {}", e);
2588                    // Per definition of `SurfaceCapabilities`, there must be at least one present format.
2589                    return None;
2590                }
2591            }
2592        };
2593
2594        let formats = raw_surface_formats
2595            .into_iter()
2596            .filter_map(conv::map_vk_surface_formats)
2597            .collect();
2598        Some(crate::SurfaceCapabilities {
2599            formats,
2600            // TODO: Right now we're always trunkating the swap chain
2601            // (presumably - we're actually setting the min image count which isn't necessarily the swap chain size)
2602            // Instead, we should use extensions when available to wait in present.
2603            // See https://github.com/gfx-rs/wgpu/issues/2869
2604            maximum_frame_latency: (caps.min_image_count - 1)..=(max_image_count - 1), // Note this can't underflow since both `min_image_count` is at least one and we already patched `max_image_count`.
2605            current_extent,
2606            usage: conv::map_vk_image_usage(caps.supported_usage_flags),
2607            present_modes: raw_present_modes
2608                .into_iter()
2609                .flat_map(conv::map_vk_present_mode)
2610                .collect(),
2611            composite_alpha_modes: conv::map_vk_composite_alpha(caps.supported_composite_alpha),
2612        })
2613    }
2614
2615    unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp {
2616        // VK_GOOGLE_display_timing is the only way to get presentation
2617        // timestamps on vulkan right now and it is only ever available
2618        // on android and linux. This includes mac, but there's no alternative
2619        // on mac, so this is fine.
2620        #[cfg(unix)]
2621        {
2622            let mut timespec = libc::timespec {
2623                tv_sec: 0,
2624                tv_nsec: 0,
2625            };
2626            unsafe {
2627                libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut timespec);
2628            }
2629
2630            wgt::PresentationTimestamp(
2631                timespec.tv_sec as u128 * 1_000_000_000 + timespec.tv_nsec as u128,
2632            )
2633        }
2634        #[cfg(not(unix))]
2635        {
2636            wgt::PresentationTimestamp::INVALID_TIMESTAMP
2637        }
2638    }
2639}
2640
2641fn is_format_16bit_norm_supported(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool {
2642    let tiling = vk::ImageTiling::OPTIMAL;
2643    let features = vk::FormatFeatureFlags::SAMPLED_IMAGE
2644        | vk::FormatFeatureFlags::STORAGE_IMAGE
2645        | vk::FormatFeatureFlags::TRANSFER_SRC
2646        | vk::FormatFeatureFlags::TRANSFER_DST;
2647    let r16unorm = supports_format(instance, phd, vk::Format::R16_UNORM, tiling, features);
2648    let r16snorm = supports_format(instance, phd, vk::Format::R16_SNORM, tiling, features);
2649    let rg16unorm = supports_format(instance, phd, vk::Format::R16G16_UNORM, tiling, features);
2650    let rg16snorm = supports_format(instance, phd, vk::Format::R16G16_SNORM, tiling, features);
2651    let rgba16unorm = supports_format(
2652        instance,
2653        phd,
2654        vk::Format::R16G16B16A16_UNORM,
2655        tiling,
2656        features,
2657    );
2658    let rgba16snorm = supports_format(
2659        instance,
2660        phd,
2661        vk::Format::R16G16B16A16_SNORM,
2662        tiling,
2663        features,
2664    );
2665
2666    r16unorm && r16snorm && rg16unorm && rg16snorm && rgba16unorm && rgba16snorm
2667}
2668
2669fn is_float32_filterable_supported(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool {
2670    let tiling = vk::ImageTiling::OPTIMAL;
2671    let features = vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_LINEAR;
2672    let r_float = supports_format(instance, phd, vk::Format::R32_SFLOAT, tiling, features);
2673    let rg_float = supports_format(instance, phd, vk::Format::R32G32_SFLOAT, tiling, features);
2674    let rgba_float = supports_format(
2675        instance,
2676        phd,
2677        vk::Format::R32G32B32A32_SFLOAT,
2678        tiling,
2679        features,
2680    );
2681    r_float && rg_float && rgba_float
2682}
2683
2684fn supports_format(
2685    instance: &ash::Instance,
2686    phd: vk::PhysicalDevice,
2687    format: vk::Format,
2688    tiling: vk::ImageTiling,
2689    features: vk::FormatFeatureFlags,
2690) -> bool {
2691    let properties = unsafe { instance.get_physical_device_format_properties(phd, format) };
2692    match tiling {
2693        vk::ImageTiling::LINEAR => properties.linear_tiling_features.contains(features),
2694        vk::ImageTiling::OPTIMAL => properties.optimal_tiling_features.contains(features),
2695        _ => false,
2696    }
2697}
2698
2699fn supports_astc_3d(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool {
2700    let mut supports = true;
2701
2702    let astc_formats = [
2703        vk::Format::ASTC_4X4_UNORM_BLOCK,
2704        vk::Format::ASTC_4X4_SRGB_BLOCK,
2705        vk::Format::ASTC_5X4_UNORM_BLOCK,
2706        vk::Format::ASTC_5X4_SRGB_BLOCK,
2707        vk::Format::ASTC_5X5_UNORM_BLOCK,
2708        vk::Format::ASTC_5X5_SRGB_BLOCK,
2709        vk::Format::ASTC_6X5_UNORM_BLOCK,
2710        vk::Format::ASTC_6X5_SRGB_BLOCK,
2711        vk::Format::ASTC_6X6_UNORM_BLOCK,
2712        vk::Format::ASTC_6X6_SRGB_BLOCK,
2713        vk::Format::ASTC_8X5_UNORM_BLOCK,
2714        vk::Format::ASTC_8X5_SRGB_BLOCK,
2715        vk::Format::ASTC_8X6_UNORM_BLOCK,
2716        vk::Format::ASTC_8X6_SRGB_BLOCK,
2717        vk::Format::ASTC_8X8_UNORM_BLOCK,
2718        vk::Format::ASTC_8X8_SRGB_BLOCK,
2719        vk::Format::ASTC_10X5_UNORM_BLOCK,
2720        vk::Format::ASTC_10X5_SRGB_BLOCK,
2721        vk::Format::ASTC_10X6_UNORM_BLOCK,
2722        vk::Format::ASTC_10X6_SRGB_BLOCK,
2723        vk::Format::ASTC_10X8_UNORM_BLOCK,
2724        vk::Format::ASTC_10X8_SRGB_BLOCK,
2725        vk::Format::ASTC_10X10_UNORM_BLOCK,
2726        vk::Format::ASTC_10X10_SRGB_BLOCK,
2727        vk::Format::ASTC_12X10_UNORM_BLOCK,
2728        vk::Format::ASTC_12X10_SRGB_BLOCK,
2729        vk::Format::ASTC_12X12_UNORM_BLOCK,
2730        vk::Format::ASTC_12X12_SRGB_BLOCK,
2731    ];
2732
2733    for &format in &astc_formats {
2734        let result = unsafe {
2735            instance.get_physical_device_image_format_properties(
2736                phd,
2737                format,
2738                vk::ImageType::TYPE_3D,
2739                vk::ImageTiling::OPTIMAL,
2740                vk::ImageUsageFlags::SAMPLED,
2741                vk::ImageCreateFlags::empty(),
2742            )
2743        };
2744        if result.is_err() {
2745            supports = false;
2746            break;
2747        }
2748    }
2749
2750    supports
2751}
2752
2753fn supports_bgra8unorm_storage(
2754    instance: &ash::Instance,
2755    phd: vk::PhysicalDevice,
2756    device_api_version: u32,
2757) -> bool {
2758    // See https://github.com/KhronosGroup/Vulkan-Docs/issues/2027#issuecomment-1380608011
2759
2760    // This check gates the function call and structures used below.
2761    // TODO: check for (`VK_KHR_get_physical_device_properties2` or VK1.1) and (`VK_KHR_format_feature_flags2` or VK1.3).
2762    // Right now we only check for VK1.3.
2763    if device_api_version < vk::API_VERSION_1_3 {
2764        return false;
2765    }
2766
2767    unsafe {
2768        let mut properties3 = vk::FormatProperties3::default();
2769        let mut properties2 = vk::FormatProperties2::default().push_next(&mut properties3);
2770
2771        instance.get_physical_device_format_properties2(
2772            phd,
2773            vk::Format::B8G8R8A8_UNORM,
2774            &mut properties2,
2775        );
2776
2777        let features2 = properties2.format_properties.optimal_tiling_features;
2778        let features3 = properties3.optimal_tiling_features;
2779
2780        features2.contains(vk::FormatFeatureFlags::STORAGE_IMAGE)
2781            && features3.contains(vk::FormatFeatureFlags2::STORAGE_WRITE_WITHOUT_FORMAT)
2782    }
2783}
2784
2785// For https://github.com/gfx-rs/wgpu/issues/4599
2786// Intel iGPUs with outdated drivers can break rendering if `VK_EXT_robustness2` is used.
2787// Driver version 31.0.101.2115 works, but there's probably an earlier functional version.
2788fn is_intel_igpu_outdated_for_robustness2(
2789    props: vk::PhysicalDeviceProperties,
2790    driver: Option<vk::PhysicalDeviceDriverPropertiesKHR>,
2791) -> bool {
2792    const DRIVER_VERSION_WORKING: u32 = (101 << 14) | 2115; // X.X.101.2115
2793
2794    let is_outdated = props.vendor_id == crate::auxil::db::intel::VENDOR
2795        && props.device_type == vk::PhysicalDeviceType::INTEGRATED_GPU
2796        && props.driver_version < DRIVER_VERSION_WORKING
2797        && driver
2798            .map(|driver| driver.driver_id == vk::DriverId::INTEL_PROPRIETARY_WINDOWS)
2799            .unwrap_or_default();
2800
2801    if is_outdated {
2802        log::warn!(
2803            "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)",
2804            props.driver_version,
2805            DRIVER_VERSION_WORKING
2806        );
2807    }
2808    is_outdated
2809}